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\Permissions\Permission;
16 use BookStack\Translation\LocaleDefinition;
17 use BookStack\Translation\LocaleManager;
18 use BookStack\Uploads\Image;
21 use Illuminate\Auth\Authenticatable;
22 use Illuminate\Auth\Passwords\CanResetPassword;
23 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
24 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
25 use Illuminate\Database\Eloquent\Builder;
26 use Illuminate\Database\Eloquent\Factories\HasFactory;
27 use Illuminate\Database\Eloquent\Relations\BelongsTo;
28 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
29 use Illuminate\Database\Eloquent\Relations\HasMany;
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|Permission $permission): bool
161 $permissionName = is_string($permission) ? $permission : $permission->value;
162 return $this->permissions()->contains($permissionName);
166 * Get all permissions belonging to 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 in this instance.
187 public function clearPermissionCache(): void
189 $this->permissions = null;
193 * Attach a role to this user.
195 public function attachRole(Role $role): void
197 $this->roles()->attach($role->id);
198 $this->unsetRelation('roles');
202 * Get the social account associated with this user.
204 public function socialAccounts(): HasMany
206 return $this->hasMany(SocialAccount::class);
210 * Check if the user has a social account,
211 * If a driver is passed, it checks for that single account type.
213 public function hasSocialAccount(string $socialDriver = ''): bool
215 if (empty($socialDriver)) {
216 return $this->socialAccounts()->count() > 0;
219 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
223 * Returns a URL to the user's avatar.
225 public function getAvatar(int $size = 50): string
227 $default = url('/user_avatar.png');
228 $imageId = $this->image_id;
229 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
233 if (!empty($this->avatarUrl)) {
234 return $this->avatarUrl;
238 $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
239 } catch (Exception $err) {
243 $this->avatarUrl = $avatar;
249 * Get the avatar for the user.
251 public function avatar(): BelongsTo
253 return $this->belongsTo(Image::class, 'image_id');
257 * Get the API tokens assigned to this user.
259 public function apiTokens(): HasMany
261 return $this->hasMany(ApiToken::class);
265 * Get the favourite instances for this user.
267 public function favourites(): HasMany
269 return $this->hasMany(Favourite::class);
273 * Get the MFA values belonging to this use.
275 public function mfaValues(): HasMany
277 return $this->hasMany(MfaValue::class);
281 * Get the tracked entity watches for this user.
283 public function watches(): HasMany
285 return $this->hasMany(Watch::class);
289 * Get the last activity time for this user.
291 public function scopeWithLastActivityAt(Builder $query)
293 $query->addSelect(['activities.created_at as last_activity_at'])
294 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
295 $query->from('activities')->select('user_id')
296 ->selectRaw('max(created_at) as created_at')
297 ->groupBy('user_id');
298 }, 'activities', 'users.id', '=', 'activities.user_id');
302 * Get the url for editing this user.
304 public function getEditUrl(string $path = ''): string
306 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
308 return url(rtrim($uri, '/'));
312 * Get the url that links to this user's profile.
314 public function getProfileUrl(): string
316 return url('/user/' . $this->slug);
320 * Get a shortened version of the user's name.
322 public function getShortName(int $chars = 8): string
324 if (mb_strlen($this->name) <= $chars) {
328 $splitName = explode(' ', $this->name);
329 if (mb_strlen($splitName[0]) <= $chars) {
330 return $splitName[0];
333 return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
337 * Get the locale for this user.
339 public function getLocale(): LocaleDefinition
341 return app()->make(LocaleManager::class)->getForUser($this);
345 * Send the password reset notification.
347 * @param string $token
351 public function sendPasswordResetNotification($token)
353 $this->notify(new ResetPasswordNotification($token));
359 public function logDescriptor(): string
361 return "({$this->id}) {$this->name}";
367 public function refreshSlug(): string
369 $this->slug = app()->make(SlugGenerator::class)->generate($this, $this->name);