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\Sluggable;
14 use BookStack\Entities\Tools\SlugGenerator;
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;
36 * @property string $name
37 * @property string $slug
38 * @property string $email
39 * @property string $password
40 * @property Carbon $created_at
41 * @property Carbon $updated_at
42 * @property bool $email_confirmed
43 * @property int $image_id
44 * @property string $external_auth_id
45 * @property string $system_name
46 * @property Collection $roles
47 * @property Collection $mfaValues
49 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
57 * The database table used by the model.
61 protected $table = 'users';
64 * The attributes that are mass assignable.
68 protected $fillable = ['name', 'email'];
70 protected $casts = ['last_activity_at' => 'datetime'];
73 * The attributes excluded from the model's JSON form.
78 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
79 'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
83 * This holds the user's permissions when loaded.
85 protected ?Collection $permissions;
88 * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
90 protected string $avatarUrl = '';
93 * Returns the default public user.
94 * Fetches from the container as a singleton to effectively cache at an app level.
96 public static function getGuest(): self
98 return app()->make('users.default');
102 * Check if the user is the default public user.
104 public function isGuest(): bool
106 return $this->system_name === 'public';
110 * Check if the user has general access to the application.
112 public function hasAppAccess(): bool
114 return !$this->isGuest() || setting('app-public');
118 * The roles that belong to the user.
120 * @return BelongsToMany
122 public function roles()
124 if ($this->id === 0) {
128 return $this->belongsToMany(Role::class);
132 * Check if the user has a role.
134 public function hasRole($roleId): bool
136 return $this->roles->pluck('id')->contains($roleId);
140 * Check if the user has a role.
142 public function hasSystemRole(string $roleSystemName): bool
144 return $this->roles->pluck('system_name')->contains($roleSystemName);
148 * Attach the default system role to this user.
150 public function attachDefaultRole(): void
152 $roleId = intval(setting('registration-role'));
153 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
154 $this->roles()->attach($roleId);
159 * Check if the user has a particular permission.
161 public function can(string $permissionName): bool
163 if ($this->email === 'guest') {
167 return $this->permissions()->contains($permissionName);
171 * Get all permissions belonging to the current user.
173 protected function permissions(): Collection
175 if (isset($this->permissions)) {
176 return $this->permissions;
179 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
180 ->select('role_permissions.name as name')->distinct()
181 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
182 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
183 ->where('ru.user_id', '=', $this->id)
186 return $this->permissions;
190 * Clear any cached permissions on this instance.
192 public function clearPermissionCache()
194 $this->permissions = null;
198 * Attach a role to this user.
200 public function attachRole(Role $role)
202 $this->roles()->attach($role->id);
203 $this->unsetRelation('roles');
207 * Get the social account associated with this user.
209 public function socialAccounts(): HasMany
211 return $this->hasMany(SocialAccount::class);
215 * Check if the user has a social account,
216 * If a driver is passed it checks for that single account type.
218 * @param bool|string $socialDriver
222 public function hasSocialAccount($socialDriver = false)
224 if ($socialDriver === false) {
225 return $this->socialAccounts()->count() > 0;
228 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
232 * Returns a URL to the user's avatar.
234 public function getAvatar(int $size = 50): string
236 $default = url('/user_avatar.png');
237 $imageId = $this->image_id;
238 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
242 if (!empty($this->avatarUrl)) {
243 return $this->avatarUrl;
247 $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
248 } catch (Exception $err) {
252 $this->avatarUrl = $avatar;
258 * Get the avatar for the user.
260 public function avatar(): BelongsTo
262 return $this->belongsTo(Image::class, 'image_id');
266 * Get the API tokens assigned to this user.
268 public function apiTokens(): HasMany
270 return $this->hasMany(ApiToken::class);
274 * Get the favourite instances for this user.
276 public function favourites(): HasMany
278 return $this->hasMany(Favourite::class);
282 * Get the MFA values belonging to this use.
284 public function mfaValues(): HasMany
286 return $this->hasMany(MfaValue::class);
290 * Get the tracked entity watches for this user.
292 public function watches(): HasMany
294 return $this->hasMany(Watch::class);
298 * Get the last activity time for this user.
300 public function scopeWithLastActivityAt(Builder $query)
302 $query->addSelect(['activities.created_at as last_activity_at'])
303 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
304 $query->from('activities')->select('user_id')
305 ->selectRaw('max(created_at) as created_at')
306 ->groupBy('user_id');
307 }, 'activities', 'users.id', '=', 'activities.user_id');
311 * Get the url for editing this user.
313 public function getEditUrl(string $path = ''): string
315 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
317 return url(rtrim($uri, '/'));
321 * Get the url that links to this user's profile.
323 public function getProfileUrl(): string
325 return url('/user/' . $this->slug);
329 * Get a shortened version of the user's name.
331 public function getShortName(int $chars = 8): string
333 if (mb_strlen($this->name) <= $chars) {
337 $splitName = explode(' ', $this->name);
338 if (mb_strlen($splitName[0]) <= $chars) {
339 return $splitName[0];
342 return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
346 * Get the locale for this user.
348 public function getLocale(): LocaleDefinition
350 return app()->make(LocaleManager::class)->getForUser($this);
354 * Send the password reset notification.
356 * @param string $token
360 public function sendPasswordResetNotification($token)
362 $this->notify(new ResetPasswordNotification($token));
368 public function logDescriptor(): string
370 return "({$this->id}) {$this->name}";
376 public function refreshSlug(): string
378 $this->slug = app()->make(SlugGenerator::class)->generate($this);