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.
81 protected ?Collection $permissions;
84 * This holds the default user when loaded.
88 protected static ?User $defaultUser = null;
91 * Returns the default public user.
93 public static function getDefault(): self
95 if (!is_null(static::$defaultUser)) {
96 return static::$defaultUser;
99 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
101 return static::$defaultUser;
105 * Check if the user is the default public user.
107 public function isDefault(): bool
109 return $this->system_name === 'public';
113 * The roles that belong to the user.
115 * @return BelongsToMany
117 public function roles()
119 if ($this->id === 0) {
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 $permissionName): bool
158 if ($this->email === 'guest') {
162 return $this->permissions()->contains($permissionName);
166 * Get all permissions belonging to a the current user.
168 protected function permissions(): Collection
170 if (isset($this->permissions)) {
171 return $this->permissions;
174 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
175 ->select('role_permissions.name as name')->distinct()
176 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
177 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
178 ->where('ru.user_id', '=', $this->id)
181 return $this->permissions;
185 * Clear any cached permissions on this instance.
187 public function clearPermissionCache()
189 $this->permissions = null;
193 * Attach a role to this user.
195 public function attachRole(Role $role)
197 $this->roles()->attach($role->id);
201 * Get the social account associated with this user.
203 public function socialAccounts(): HasMany
205 return $this->hasMany(SocialAccount::class);
209 * Check if the user has a social account,
210 * If a driver is passed it checks for that single account type.
212 * @param bool|string $socialDriver
216 public function hasSocialAccount($socialDriver = false)
218 if ($socialDriver === false) {
219 return $this->socialAccounts()->count() > 0;
222 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
226 * Returns a URL to the user's avatar.
228 public function getAvatar(int $size = 50): string
230 $default = url('/user_avatar.png');
231 $imageId = $this->image_id;
232 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
237 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
238 } catch (Exception $err) {
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 last activity time for this user.
280 public function scopeWithLastActivityAt(Builder $query)
282 $query->addSelect(['activities.created_at as last_activity_at'])
283 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
284 $query->from('activities')->select('user_id')
285 ->selectRaw('max(created_at) as created_at')
286 ->groupBy('user_id');
287 }, 'activities', 'users.id', '=', 'activities.user_id');
291 * Get the url for editing this user.
293 public function getEditUrl(string $path = ''): string
295 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
297 return url(rtrim($uri, '/'));
301 * Get the url that links to this user's profile.
303 public function getProfileUrl(): string
305 return url('/user/' . $this->slug);
309 * Get a shortened version of the user's name.
311 public function getShortName(int $chars = 8): string
313 if (mb_strlen($this->name) <= $chars) {
317 $splitName = explode(' ', $this->name);
318 if (mb_strlen($splitName[0]) <= $chars) {
319 return $splitName[0];
326 * Send the password reset notification.
328 * @param string $token
332 public function sendPasswordResetNotification($token)
334 $this->notify(new ResetPassword($token));
340 public function logDescriptor(): string
342 return "({$this->id}) {$this->name}";
348 public function refreshSlug(): string
350 $this->slug = app(SlugGenerator::class)->generate($this);