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\LanguageManager;
16 use BookStack\Uploads\Image;
19 use Illuminate\Auth\Authenticatable;
20 use Illuminate\Auth\Passwords\CanResetPassword;
21 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
22 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
23 use Illuminate\Database\Eloquent\Builder;
24 use Illuminate\Database\Eloquent\Factories\HasFactory;
25 use Illuminate\Database\Eloquent\Relations\BelongsTo;
26 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
27 use Illuminate\Database\Eloquent\Relations\HasMany;
28 use Illuminate\Notifications\Notifiable;
29 use Illuminate\Support\Collection;
35 * @property string $name
36 * @property string $slug
37 * @property string $email
38 * @property string $password
39 * @property Carbon $created_at
40 * @property Carbon $updated_at
41 * @property bool $email_confirmed
42 * @property int $image_id
43 * @property string $external_auth_id
44 * @property string $system_name
45 * @property Collection $roles
46 * @property Collection $mfaValues
48 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
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 * This holds the default user when loaded.
94 protected static ?User $defaultUser = null;
97 * Returns the default public user.
99 public static function getDefault(): self
101 if (!is_null(static::$defaultUser)) {
102 return static::$defaultUser;
105 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
107 return static::$defaultUser;
110 public static function clearDefault(): void
112 static::$defaultUser = null;
116 * Check if the user is the default public user.
118 public function isDefault(): bool
120 return $this->system_name === 'public';
124 * The roles that belong to the user.
126 * @return BelongsToMany
128 public function roles()
130 if ($this->id === 0) {
134 return $this->belongsToMany(Role::class);
138 * Check if the user has a role.
140 public function hasRole($roleId): bool
142 return $this->roles->pluck('id')->contains($roleId);
146 * Check if the user has a role.
148 public function hasSystemRole(string $roleSystemName): bool
150 return $this->roles->pluck('system_name')->contains($roleSystemName);
154 * Attach the default system role to this user.
156 public function attachDefaultRole(): void
158 $roleId = intval(setting('registration-role'));
159 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
160 $this->roles()->attach($roleId);
165 * Check if the user has a particular permission.
167 public function can(string $permissionName): bool
169 if ($this->email === 'guest') {
173 return $this->permissions()->contains($permissionName);
177 * Get all permissions belonging to the current user.
179 protected function permissions(): Collection
181 if (isset($this->permissions)) {
182 return $this->permissions;
185 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
186 ->select('role_permissions.name as name')->distinct()
187 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
188 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
189 ->where('ru.user_id', '=', $this->id)
192 return $this->permissions;
196 * Clear any cached permissions on this instance.
198 public function clearPermissionCache()
200 $this->permissions = null;
204 * Attach a role to this user.
206 public function attachRole(Role $role)
208 $this->roles()->attach($role->id);
209 $this->unsetRelation('roles');
213 * Get the social account associated with this user.
215 public function socialAccounts(): HasMany
217 return $this->hasMany(SocialAccount::class);
221 * Check if the user has a social account,
222 * If a driver is passed it checks for that single account type.
224 * @param bool|string $socialDriver
228 public function hasSocialAccount($socialDriver = false)
230 if ($socialDriver === false) {
231 return $this->socialAccounts()->count() > 0;
234 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
238 * Returns a URL to the user's avatar.
240 public function getAvatar(int $size = 50): string
242 $default = url('/user_avatar.png');
243 $imageId = $this->image_id;
244 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
248 if (!empty($this->avatarUrl)) {
249 return $this->avatarUrl;
253 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
254 } catch (Exception $err) {
258 $this->avatarUrl = $avatar;
264 * Get the avatar for the user.
266 public function avatar(): BelongsTo
268 return $this->belongsTo(Image::class, 'image_id');
272 * Get the API tokens assigned to this user.
274 public function apiTokens(): HasMany
276 return $this->hasMany(ApiToken::class);
280 * Get the favourite instances for this user.
282 public function favourites(): HasMany
284 return $this->hasMany(Favourite::class);
288 * Get the MFA values belonging to this use.
290 public function mfaValues(): HasMany
292 return $this->hasMany(MfaValue::class);
296 * Get the tracked entity watches for this user.
298 public function watches(): HasMany
300 return $this->hasMany(Watch::class);
304 * Get the last activity time for this user.
306 public function scopeWithLastActivityAt(Builder $query)
308 $query->addSelect(['activities.created_at as last_activity_at'])
309 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
310 $query->from('activities')->select('user_id')
311 ->selectRaw('max(created_at) as created_at')
312 ->groupBy('user_id');
313 }, 'activities', 'users.id', '=', 'activities.user_id');
317 * Get the url for editing this user.
319 public function getEditUrl(string $path = ''): string
321 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
323 return url(rtrim($uri, '/'));
327 * Get the url that links to this user's profile.
329 public function getProfileUrl(): string
331 return url('/user/' . $this->slug);
335 * Get a shortened version of the user's name.
337 public function getShortName(int $chars = 8): string
339 if (mb_strlen($this->name) <= $chars) {
343 $splitName = explode(' ', $this->name);
344 if (mb_strlen($splitName[0]) <= $chars) {
345 return $splitName[0];
348 return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
352 * Get the system language for this user.
354 public function getLanguage(): string
356 return app()->make(LanguageManager::class)->getLanguageForUser($this);
360 * Send the password reset notification.
362 * @param string $token
366 public function sendPasswordResetNotification($token)
368 $this->notify(new ResetPasswordNotification($token));
374 public function logDescriptor(): string
376 return "({$this->id}) {$this->name}";
382 public function refreshSlug(): string
384 $this->slug = app(SlugGenerator::class)->generate($this);