3 namespace BookStack\Users\Models;
5 use BookStack\Access\Mfa\MfaValue;
6 use BookStack\Access\Notifications\ResetPasswordNotification;
7 use BookStack\Access\SocialAccount;
8 use BookStack\Activity\Models\Favourite;
9 use BookStack\Activity\Models\Loggable;
10 use BookStack\Activity\Models\Watch;
11 use BookStack\Api\ApiToken;
12 use BookStack\App\Model;
13 use BookStack\App\SluggableInterface;
14 use BookStack\Permissions\Permission;
15 use BookStack\Translation\LocaleDefinition;
16 use BookStack\Translation\LocaleManager;
17 use BookStack\Uploads\Image;
20 use Illuminate\Auth\Authenticatable;
21 use Illuminate\Auth\Passwords\CanResetPassword;
22 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
23 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
24 use Illuminate\Database\Eloquent\Builder;
25 use Illuminate\Database\Eloquent\Factories\HasFactory;
26 use Illuminate\Database\Eloquent\Relations\BelongsTo;
27 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
28 use Illuminate\Database\Eloquent\Relations\HasMany;
29 use Illuminate\Notifications\Notifiable;
30 use Illuminate\Support\Collection;
34 * @property string $name
35 * @property string $slug
36 * @property string $email
37 * @property string $password
38 * @property Carbon $created_at
39 * @property Carbon $updated_at
40 * @property bool $email_confirmed
41 * @property int $image_id
42 * @property string $external_auth_id
43 * @property string $system_name
44 * @property Collection $roles
45 * @property Collection $mfaValues
46 * @property ?Image $avatar
48 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, SluggableInterface
56 * The database table used by the model.
60 protected $table = 'users';
63 * The attributes that are mass assignable.
67 protected $fillable = ['name', 'email'];
69 protected $casts = ['last_activity_at' => 'datetime'];
72 * The attributes excluded from the model's JSON form.
77 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
78 'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
82 * This holds the user's permissions when loaded.
84 protected ?Collection $permissions;
87 * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
89 protected string $avatarUrl = '';
92 * Returns the default public user.
93 * Fetches from the container as a singleton to effectively cache at an app level.
95 public static function getGuest(): self
97 return app()->make('users.default');
101 * Check if the user is the default public user.
103 public function isGuest(): bool
105 return $this->system_name === 'public';
109 * Check if the user has general access to the application.
111 public function hasAppAccess(): bool
113 return !$this->isGuest() || setting('app-public');
117 * The roles that belong to the user.
119 * @return BelongsToMany<Role, $this>
121 public function roles(): BelongsToMany
123 return $this->belongsToMany(Role::class);
127 * Check if the user has a role.
129 public function hasRole($roleId): bool
131 return $this->roles->pluck('id')->contains($roleId);
135 * Check if the user has a role.
137 public function hasSystemRole(string $roleSystemName): bool
139 return $this->roles->pluck('system_name')->contains($roleSystemName);
143 * Attach the default system role to this user.
145 public function attachDefaultRole(): void
147 $roleId = intval(setting('registration-role'));
148 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
149 $this->roles()->attach($roleId);
154 * Check if the user has a particular permission.
156 public function can(string|Permission $permission): bool
158 $permissionName = is_string($permission) ? $permission : $permission->value;
159 return $this->permissions()->contains($permissionName);
163 * Get all permissions belonging to the current user.
165 protected function permissions(): Collection
167 if (isset($this->permissions)) {
168 return $this->permissions;
171 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
172 ->select('role_permissions.name as name')->distinct()
173 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
174 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
175 ->where('ru.user_id', '=', $this->id)
178 return $this->permissions;
182 * Clear any cached permissions in this instance.
184 public function clearPermissionCache(): void
186 $this->permissions = null;
190 * Attach a role to this user.
192 public function attachRole(Role $role): void
194 $this->roles()->attach($role->id);
195 $this->unsetRelation('roles');
199 * Get the social account associated with this user.
201 public function socialAccounts(): HasMany
203 return $this->hasMany(SocialAccount::class);
207 * Check if the user has a social account,
208 * If a driver is passed, it checks for that single account type.
210 public function hasSocialAccount(string $socialDriver = ''): bool
212 if (empty($socialDriver)) {
213 return $this->socialAccounts()->count() > 0;
216 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
220 * Returns a URL to the user's avatar.
222 public function getAvatar(int $size = 50): string
224 $default = url('/user_avatar.png');
225 $imageId = $this->image_id;
226 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
230 if (!empty($this->avatarUrl)) {
231 return $this->avatarUrl;
235 $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
236 } catch (Exception $err) {
240 $this->avatarUrl = $avatar;
246 * Get the avatar for the user.
248 public function avatar(): BelongsTo
250 return $this->belongsTo(Image::class, 'image_id');
254 * Get the API tokens assigned to this user.
256 public function apiTokens(): HasMany
258 return $this->hasMany(ApiToken::class);
262 * Get the favourite instances for this user.
264 public function favourites(): HasMany
266 return $this->hasMany(Favourite::class);
270 * Get the MFA values belonging to this use.
272 public function mfaValues(): HasMany
274 return $this->hasMany(MfaValue::class);
278 * Get the tracked entity watches for this user.
280 public function watches(): HasMany
282 return $this->hasMany(Watch::class);
286 * Get the last activity time for this user.
288 public function scopeWithLastActivityAt(Builder $query)
290 $query->addSelect(['activities.created_at as last_activity_at'])
291 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
292 $query->from('activities')->select('user_id')
293 ->selectRaw('max(created_at) as created_at')
294 ->groupBy('user_id');
295 }, 'activities', 'users.id', '=', 'activities.user_id');
299 * Get the url for editing this user.
301 public function getEditUrl(string $path = ''): string
303 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
305 return url(rtrim($uri, '/'));
309 * Get the url that links to this user's profile.
311 public function getProfileUrl(): string
313 return url('/user/' . $this->slug);
317 * Get a shortened version of the user's name.
319 public function getShortName(int $chars = 8): string
321 if (mb_strlen($this->name) <= $chars) {
325 $splitName = explode(' ', $this->name);
326 if (mb_strlen($splitName[0]) <= $chars) {
327 return $splitName[0];
330 return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
334 * Get the locale for this user.
336 public function getLocale(): LocaleDefinition
338 return app()->make(LocaleManager::class)->getForUser($this);
342 * Send the password reset notification.
344 * @param string $token
348 public function sendPasswordResetNotification($token)
350 $this->notify(new ResetPasswordNotification($token));
356 public function logDescriptor(): string
358 return "({$this->id}) {$this->name}";