3 namespace BookStack\Auth;
5 use BookStack\Actions\Favourite;
6 use BookStack\Api\ApiToken;
7 use BookStack\Auth\Access\Mfa\MfaValue;
8 use BookStack\Entities\Tools\SlugGenerator;
9 use BookStack\Interfaces\Loggable;
10 use BookStack\Interfaces\Sluggable;
12 use BookStack\Notifications\ResetPassword;
13 use BookStack\Uploads\Image;
16 use Illuminate\Auth\Authenticatable;
17 use Illuminate\Auth\Passwords\CanResetPassword;
18 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
19 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
20 use Illuminate\Database\Eloquent\Builder;
21 use Illuminate\Database\Eloquent\Factories\HasFactory;
22 use Illuminate\Database\Eloquent\Relations\BelongsTo;
23 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
24 use Illuminate\Database\Eloquent\Relations\HasMany;
25 use Illuminate\Notifications\Notifiable;
26 use Illuminate\Support\Collection;
32 * @property string $name
33 * @property string $slug
34 * @property string $email
35 * @property string $password
36 * @property Carbon $created_at
37 * @property Carbon $updated_at
38 * @property bool $email_confirmed
39 * @property int $image_id
40 * @property string $external_auth_id
41 * @property string $system_name
42 * @property Collection $roles
43 * @property Collection $mfaValues
45 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
53 * The database table used by the model.
57 protected $table = 'users';
60 * The attributes that are mass assignable.
64 protected $fillable = ['name', 'email'];
66 protected $casts = ['last_activity_at' => 'datetime'];
69 * The attributes excluded from the model's JSON form.
74 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
75 'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id',
79 * This holds the user's permissions when loaded.
83 protected $permissions;
86 * This holds the default user when loaded.
90 protected static $defaultUser = null;
93 * Returns the default public user.
95 public static function getDefault(): self
97 if (!is_null(static::$defaultUser)) {
98 return static::$defaultUser;
101 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
103 return static::$defaultUser;
107 * Check if the user is the default public user.
109 public function isDefault(): bool
111 return $this->system_name === 'public';
115 * The roles that belong to the user.
117 * @return BelongsToMany
119 public function roles()
121 if ($this->id === 0) {
125 return $this->belongsToMany(Role::class);
129 * Check if the user has a role.
131 public function hasRole($roleId): bool
133 return $this->roles->pluck('id')->contains($roleId);
137 * Check if the user has a role.
139 public function hasSystemRole(string $roleSystemName): bool
141 return $this->roles->pluck('system_name')->contains($roleSystemName);
145 * Attach the default system role to this user.
147 public function attachDefaultRole(): void
149 $roleId = intval(setting('registration-role'));
150 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
151 $this->roles()->attach($roleId);
156 * Check if the user has a particular permission.
158 public function can(string $permissionName): bool
160 if ($this->email === 'guest') {
164 return $this->permissions()->contains($permissionName);
168 * Get all permissions belonging to a the current user.
170 protected function permissions(): Collection
172 if (isset($this->permissions)) {
173 return $this->permissions;
176 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
177 ->select('role_permissions.name as name')->distinct()
178 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
179 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
180 ->where('ru.user_id', '=', $this->id)
183 return $this->permissions;
187 * Clear any cached permissions on this instance.
189 public function clearPermissionCache()
191 $this->permissions = null;
195 * Attach a role to this user.
197 public function attachRole(Role $role)
199 $this->roles()->attach($role->id);
203 * Get the social account associated with this user.
205 public function socialAccounts(): HasMany
207 return $this->hasMany(SocialAccount::class);
211 * Check if the user has a social account,
212 * If a driver is passed it checks for that single account type.
214 * @param bool|string $socialDriver
218 public function hasSocialAccount($socialDriver = false)
220 if ($socialDriver === false) {
221 return $this->socialAccounts()->count() > 0;
224 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
228 * Returns a URL to the user's avatar.
230 public function getAvatar(int $size = 50): string
232 $default = url('/user_avatar.png');
233 $imageId = $this->image_id;
234 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
239 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
240 } catch (Exception $err) {
248 * Get the avatar for the user.
250 public function avatar(): BelongsTo
252 return $this->belongsTo(Image::class, 'image_id');
256 * Get the API tokens assigned to this user.
258 public function apiTokens(): HasMany
260 return $this->hasMany(ApiToken::class);
264 * Get the favourite instances for this user.
266 public function favourites(): HasMany
268 return $this->hasMany(Favourite::class);
272 * Get the MFA values belonging to this use.
274 public function mfaValues(): HasMany
276 return $this->hasMany(MfaValue::class);
280 * Get the last activity time for this user.
282 public function scopeWithLastActivityAt(Builder $query)
284 $query->addSelect(['activities.created_at as last_activity_at'])
285 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
286 $query->from('activities')->select('user_id')
287 ->selectRaw('max(created_at) as created_at')
288 ->groupBy('user_id');
289 }, 'activities', 'users.id', '=', 'activities.user_id');
293 * Get the url for editing this user.
295 public function getEditUrl(string $path = ''): string
297 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
299 return url(rtrim($uri, '/'));
303 * Get the url that links to this user's profile.
305 public function getProfileUrl(): string
307 return url('/user/' . $this->slug);
311 * Get a shortened version of the user's name.
313 public function getShortName(int $chars = 8): string
315 if (mb_strlen($this->name) <= $chars) {
319 $splitName = explode(' ', $this->name);
320 if (mb_strlen($splitName[0]) <= $chars) {
321 return $splitName[0];
328 * Send the password reset notification.
330 * @param string $token
334 public function sendPasswordResetNotification($token)
336 $this->notify(new ResetPassword($token));
342 public function logDescriptor(): string
344 return "({$this->id}) {$this->name}";
350 public function refreshSlug(): string
352 $this->slug = app(SlugGenerator::class)->generate($this);