3 namespace BookStack\Users\Models;
5 use BookStack\Access\Mfa\MfaValue;
6 use BookStack\Access\SocialAccount;
7 use BookStack\Activity\Models\Favourite;
8 use BookStack\Activity\Models\Loggable;
9 use BookStack\Api\ApiToken;
10 use BookStack\App\Model;
11 use BookStack\App\Sluggable;
12 use BookStack\Entities\Tools\SlugGenerator;
13 use BookStack\Notifications\ResetPassword;
14 use BookStack\Translation\LanguageManager;
15 use BookStack\Uploads\Image;
18 use Illuminate\Auth\Authenticatable;
19 use Illuminate\Auth\Passwords\CanResetPassword;
20 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
21 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
22 use Illuminate\Database\Eloquent\Builder;
23 use Illuminate\Database\Eloquent\Factories\HasFactory;
24 use Illuminate\Database\Eloquent\Relations\BelongsTo;
25 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
26 use Illuminate\Database\Eloquent\Relations\HasMany;
27 use Illuminate\Notifications\Notifiable;
28 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
47 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
55 * The database table used by the model.
59 protected $table = 'users';
62 * The attributes that are mass assignable.
66 protected $fillable = ['name', 'email'];
68 protected $casts = ['last_activity_at' => 'datetime'];
71 * The attributes excluded from the model's JSON form.
76 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
77 'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
81 * This holds the user's permissions when loaded.
83 protected ?Collection $permissions;
86 * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
88 protected string $avatarUrl = '';
91 * This holds the default user when loaded.
93 protected static ?User $defaultUser = null;
96 * Returns the default public user.
98 public static function getDefault(): self
100 if (!is_null(static::$defaultUser)) {
101 return static::$defaultUser;
104 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
106 return static::$defaultUser;
109 public static function clearDefault(): void
111 static::$defaultUser = null;
115 * Check if the user is the default public user.
117 public function isDefault(): bool
119 return $this->system_name === 'public';
123 * The roles that belong to the user.
125 * @return BelongsToMany
127 public function roles()
129 if ($this->id === 0) {
133 return $this->belongsToMany(Role::class);
137 * Check if the user has a role.
139 public function hasRole($roleId): bool
141 return $this->roles->pluck('id')->contains($roleId);
145 * Check if the user has a role.
147 public function hasSystemRole(string $roleSystemName): bool
149 return $this->roles->pluck('system_name')->contains($roleSystemName);
153 * Attach the default system role to this user.
155 public function attachDefaultRole(): void
157 $roleId = intval(setting('registration-role'));
158 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
159 $this->roles()->attach($roleId);
164 * Check if the user has a particular permission.
166 public function can(string $permissionName): bool
168 if ($this->email === 'guest') {
172 return $this->permissions()->contains($permissionName);
176 * Get all permissions belonging to the current user.
178 protected function permissions(): Collection
180 if (isset($this->permissions)) {
181 return $this->permissions;
184 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
185 ->select('role_permissions.name as name')->distinct()
186 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
187 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
188 ->where('ru.user_id', '=', $this->id)
191 return $this->permissions;
195 * Clear any cached permissions on this instance.
197 public function clearPermissionCache()
199 $this->permissions = null;
203 * Attach a role to this user.
205 public function attachRole(Role $role)
207 $this->roles()->attach($role->id);
208 $this->unsetRelation('roles');
212 * Get the social account associated with this user.
214 public function socialAccounts(): HasMany
216 return $this->hasMany(SocialAccount::class);
220 * Check if the user has a social account,
221 * If a driver is passed it checks for that single account type.
223 * @param bool|string $socialDriver
227 public function hasSocialAccount($socialDriver = false)
229 if ($socialDriver === false) {
230 return $this->socialAccounts()->count() > 0;
233 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
237 * Returns a URL to the user's avatar.
239 public function getAvatar(int $size = 50): string
241 $default = url('/user_avatar.png');
242 $imageId = $this->image_id;
243 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
247 if (!empty($this->avatarUrl)) {
248 return $this->avatarUrl;
252 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
253 } catch (Exception $err) {
257 $this->avatarUrl = $avatar;
263 * Get the avatar for the user.
265 public function avatar(): BelongsTo
267 return $this->belongsTo(Image::class, 'image_id');
271 * Get the API tokens assigned to this user.
273 public function apiTokens(): HasMany
275 return $this->hasMany(ApiToken::class);
279 * Get the favourite instances for this user.
281 public function favourites(): HasMany
283 return $this->hasMany(Favourite::class);
287 * Get the MFA values belonging to this use.
289 public function mfaValues(): HasMany
291 return $this->hasMany(MfaValue::class);
295 * Get the last activity time for this user.
297 public function scopeWithLastActivityAt(Builder $query)
299 $query->addSelect(['activities.created_at as last_activity_at'])
300 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
301 $query->from('activities')->select('user_id')
302 ->selectRaw('max(created_at) as created_at')
303 ->groupBy('user_id');
304 }, 'activities', 'users.id', '=', 'activities.user_id');
308 * Get the url for editing this user.
310 public function getEditUrl(string $path = ''): string
312 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
314 return url(rtrim($uri, '/'));
318 * Get the url that links to this user's profile.
320 public function getProfileUrl(): string
322 return url('/user/' . $this->slug);
326 * Get a shortened version of the user's name.
328 public function getShortName(int $chars = 8): string
330 if (mb_strlen($this->name) <= $chars) {
334 $splitName = explode(' ', $this->name);
335 if (mb_strlen($splitName[0]) <= $chars) {
336 return $splitName[0];
343 * Get the system language for this user.
345 public function getLanguage(): string
347 return app()->make(LanguageManager::class)->getLanguageForUser($this);
351 * Send the password reset notification.
353 * @param string $token
357 public function sendPasswordResetNotification($token)
359 $this->notify(new ResetPassword($token));
365 public function logDescriptor(): string
367 return "({$this->id}) {$this->name}";
373 public function refreshSlug(): string
375 $this->slug = app(SlugGenerator::class)->generate($this);