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\SluggableInterface;
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\Database\Eloquent\Relations\Relation;
30 use Illuminate\Notifications\Notifiable;
31 use Illuminate\Support\Collection;
37 * @property string $name
38 * @property string $slug
39 * @property string $email
40 * @property string $password
41 * @property Carbon $created_at
42 * @property Carbon $updated_at
43 * @property bool $email_confirmed
44 * @property int $image_id
45 * @property string $external_auth_id
46 * @property string $system_name
47 * @property Collection $roles
48 * @property Collection $mfaValues
49 * @property ?Image $avatar
51 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, SluggableInterface
59 * The database table used by the model.
63 protected $table = 'users';
66 * The attributes that are mass assignable.
70 protected $fillable = ['name', 'email'];
72 protected $casts = ['last_activity_at' => 'datetime'];
75 * The attributes excluded from the model's JSON form.
80 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
81 'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
85 * This holds the user's permissions when loaded.
87 protected ?Collection $permissions;
90 * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
92 protected string $avatarUrl = '';
95 * Returns the default public user.
96 * Fetches from the container as a singleton to effectively cache at an app level.
98 public static function getGuest(): self
100 return app()->make('users.default');
104 * Check if the user is the default public user.
106 public function isGuest(): bool
108 return $this->system_name === 'public';
112 * Check if the user has general access to the application.
114 public function hasAppAccess(): bool
116 return !$this->isGuest() || setting('app-public');
120 * The roles that belong to the user.
122 * @return BelongsToMany<Role, $this>
124 public function roles(): BelongsToMany
126 return $this->belongsToMany(Role::class);
130 * Check if the user has a role.
132 public function hasRole($roleId): bool
134 return $this->roles->pluck('id')->contains($roleId);
138 * Check if the user has a role.
140 public function hasSystemRole(string $roleSystemName): bool
142 return $this->roles->pluck('system_name')->contains($roleSystemName);
146 * Attach the default system role to this user.
148 public function attachDefaultRole(): void
150 $roleId = intval(setting('registration-role'));
151 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
152 $this->roles()->attach($roleId);
157 * Check if the user has a particular permission.
159 public function can(string $permissionName): bool
161 return $this->permissions()->contains($permissionName);
165 * Get all permissions belonging to the current user.
167 protected function permissions(): Collection
169 if (isset($this->permissions)) {
170 return $this->permissions;
173 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
174 ->select('role_permissions.name as name')->distinct()
175 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
176 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
177 ->where('ru.user_id', '=', $this->id)
180 return $this->permissions;
184 * Clear any cached permissions on this instance.
186 public function clearPermissionCache()
188 $this->permissions = null;
192 * Attach a role to this user.
194 public function attachRole(Role $role)
196 $this->roles()->attach($role->id);
197 $this->unsetRelation('roles');
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) {
236 if (!empty($this->avatarUrl)) {
237 return $this->avatarUrl;
241 $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
242 } catch (Exception $err) {
246 $this->avatarUrl = $avatar;
252 * Get the avatar for the user.
254 public function avatar(): BelongsTo
256 return $this->belongsTo(Image::class, 'image_id');
260 * Get the API tokens assigned to this user.
262 public function apiTokens(): HasMany
264 return $this->hasMany(ApiToken::class);
268 * Get the favourite instances for this user.
270 public function favourites(): HasMany
272 return $this->hasMany(Favourite::class);
276 * Get the MFA values belonging to this use.
278 public function mfaValues(): HasMany
280 return $this->hasMany(MfaValue::class);
284 * Get the tracked entity watches for this user.
286 public function watches(): HasMany
288 return $this->hasMany(Watch::class);
292 * Get the last activity time for this user.
294 public function scopeWithLastActivityAt(Builder $query)
296 $query->addSelect(['activities.created_at as last_activity_at'])
297 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
298 $query->from('activities')->select('user_id')
299 ->selectRaw('max(created_at) as created_at')
300 ->groupBy('user_id');
301 }, 'activities', 'users.id', '=', 'activities.user_id');
305 * Get the url for editing this user.
307 public function getEditUrl(string $path = ''): string
309 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
311 return url(rtrim($uri, '/'));
315 * Get the url that links to this user's profile.
317 public function getProfileUrl(): string
319 return url('/user/' . $this->slug);
323 * Get a shortened version of the user's name.
325 public function getShortName(int $chars = 8): string
327 if (mb_strlen($this->name) <= $chars) {
331 $splitName = explode(' ', $this->name);
332 if (mb_strlen($splitName[0]) <= $chars) {
333 return $splitName[0];
336 return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
340 * Get the locale for this user.
342 public function getLocale(): LocaleDefinition
344 return app()->make(LocaleManager::class)->getForUser($this);
348 * Send the password reset notification.
350 * @param string $token
354 public function sendPasswordResetNotification($token)
356 $this->notify(new ResetPasswordNotification($token));
362 public function logDescriptor(): string
364 return "({$this->id}) {$this->name}";
370 public function refreshSlug(): string
372 $this->slug = app()->make(SlugGenerator::class)->generate($this, $this->name);