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\Sluggable;
14 use BookStack\Entities\Tools\SlugGenerator;
15 use BookStack\Translation\LocaleManager;
16 use BookStack\Uploads\Image;
19 use Illuminate\Auth\Authenticatable;
20 use Illuminate\Auth\Passwords\CanResetPassword;
21 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
22 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
23 use Illuminate\Database\Eloquent\Builder;
24 use Illuminate\Database\Eloquent\Factories\HasFactory;
25 use Illuminate\Database\Eloquent\Relations\BelongsTo;
26 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
27 use Illuminate\Database\Eloquent\Relations\HasMany;
28 use Illuminate\Notifications\Notifiable;
29 use Illuminate\Support\Collection;
35 * @property string $name
36 * @property string $slug
37 * @property string $email
38 * @property string $password
39 * @property Carbon $created_at
40 * @property Carbon $updated_at
41 * @property bool $email_confirmed
42 * @property int $image_id
43 * @property string $external_auth_id
44 * @property string $system_name
45 * @property Collection $roles
46 * @property Collection $mfaValues
48 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
56 * The database table used by the model.
60 protected $table = 'users';
63 * The attributes that are mass assignable.
67 protected $fillable = ['name', 'email'];
69 protected $casts = ['last_activity_at' => 'datetime'];
72 * The attributes excluded from the model's JSON form.
77 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
78 'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
82 * This holds the user's permissions when loaded.
84 protected ?Collection $permissions;
87 * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
89 protected string $avatarUrl = '';
92 * Returns the default public user.
93 * Fetches from the container as a singleton to effectively cache at an app level.
95 public static function getGuest(): self
97 return app()->make('users.default');
101 * Check if the user is the default public user.
103 public function isGuest(): bool
105 return $this->system_name === 'public';
109 * Check if the user has general access to the application.
111 public function hasAppAccess(): bool
113 return !$this->isGuest() || setting('app-public');
117 * The roles that belong to the user.
119 * @return BelongsToMany
121 public function roles()
123 if ($this->id === 0) {
127 return $this->belongsToMany(Role::class);
131 * Check if the user has a role.
133 public function hasRole($roleId): bool
135 return $this->roles->pluck('id')->contains($roleId);
139 * Check if the user has a role.
141 public function hasSystemRole(string $roleSystemName): bool
143 return $this->roles->pluck('system_name')->contains($roleSystemName);
147 * Attach the default system role to this user.
149 public function attachDefaultRole(): void
151 $roleId = intval(setting('registration-role'));
152 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
153 $this->roles()->attach($roleId);
158 * Check if the user has a particular permission.
160 public function can(string $permissionName): bool
162 if ($this->email === 'guest') {
166 return $this->permissions()->contains($permissionName);
170 * Get all permissions belonging to the current user.
172 protected function permissions(): Collection
174 if (isset($this->permissions)) {
175 return $this->permissions;
178 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
179 ->select('role_permissions.name as name')->distinct()
180 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
181 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
182 ->where('ru.user_id', '=', $this->id)
185 return $this->permissions;
189 * Clear any cached permissions on this instance.
191 public function clearPermissionCache()
193 $this->permissions = null;
197 * Attach a role to this user.
199 public function attachRole(Role $role)
201 $this->roles()->attach($role->id);
202 $this->unsetRelation('roles');
206 * Get the social account associated with this user.
208 public function socialAccounts(): HasMany
210 return $this->hasMany(SocialAccount::class);
214 * Check if the user has a social account,
215 * If a driver is passed it checks for that single account type.
217 * @param bool|string $socialDriver
221 public function hasSocialAccount($socialDriver = false)
223 if ($socialDriver === false) {
224 return $this->socialAccounts()->count() > 0;
227 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
231 * Returns a URL to the user's avatar.
233 public function getAvatar(int $size = 50): string
235 $default = url('/user_avatar.png');
236 $imageId = $this->image_id;
237 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
241 if (!empty($this->avatarUrl)) {
242 return $this->avatarUrl;
246 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
247 } catch (Exception $err) {
251 $this->avatarUrl = $avatar;
257 * Get the avatar for the user.
259 public function avatar(): BelongsTo
261 return $this->belongsTo(Image::class, 'image_id');
265 * Get the API tokens assigned to this user.
267 public function apiTokens(): HasMany
269 return $this->hasMany(ApiToken::class);
273 * Get the favourite instances for this user.
275 public function favourites(): HasMany
277 return $this->hasMany(Favourite::class);
281 * Get the MFA values belonging to this use.
283 public function mfaValues(): HasMany
285 return $this->hasMany(MfaValue::class);
289 * Get the tracked entity watches for this user.
291 public function watches(): HasMany
293 return $this->hasMany(Watch::class);
297 * Get the last activity time for this user.
299 public function scopeWithLastActivityAt(Builder $query)
301 $query->addSelect(['activities.created_at as last_activity_at'])
302 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
303 $query->from('activities')->select('user_id')
304 ->selectRaw('max(created_at) as created_at')
305 ->groupBy('user_id');
306 }, 'activities', 'users.id', '=', 'activities.user_id');
310 * Get the url for editing this user.
312 public function getEditUrl(string $path = ''): string
314 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
316 return url(rtrim($uri, '/'));
320 * Get the url that links to this user's profile.
322 public function getProfileUrl(): string
324 return url('/user/' . $this->slug);
328 * Get a shortened version of the user's name.
330 public function getShortName(int $chars = 8): string
332 if (mb_strlen($this->name) <= $chars) {
336 $splitName = explode(' ', $this->name);
337 if (mb_strlen($splitName[0]) <= $chars) {
338 return $splitName[0];
341 return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
345 * Get the system language for this user.
347 public function getLanguage(): string
349 return app()->make(LocaleManager::class)->getForUser($this)->appLocale();
353 * Send the password reset notification.
355 * @param string $token
359 public function sendPasswordResetNotification($token)
361 $this->notify(new ResetPasswordNotification($token));
367 public function logDescriptor(): string
369 return "({$this->id}) {$this->name}";
375 public function refreshSlug(): string
377 $this->slug = app()->make(SlugGenerator::class)->generate($this);