3 namespace BookStack\Auth;
5 use BookStack\Actions\Favourite;
6 use BookStack\Api\ApiToken;
7 use BookStack\Entities\Tools\SlugGenerator;
8 use BookStack\Interfaces\Loggable;
9 use BookStack\Interfaces\Sluggable;
11 use BookStack\Notifications\ResetPassword;
12 use BookStack\Uploads\Image;
15 use Illuminate\Auth\Authenticatable;
16 use Illuminate\Auth\Passwords\CanResetPassword;
17 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
18 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
19 use Illuminate\Database\Eloquent\Builder;
20 use Illuminate\Database\Eloquent\Relations\BelongsTo;
21 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
22 use Illuminate\Database\Eloquent\Relations\HasMany;
23 use Illuminate\Notifications\Notifiable;
24 use Illuminate\Support\Collection;
29 * @property string $id
30 * @property string $name
31 * @property string $slug
32 * @property string $email
33 * @property string $password
34 * @property Carbon $created_at
35 * @property Carbon $updated_at
36 * @property bool $email_confirmed
37 * @property int $image_id
38 * @property string $external_auth_id
39 * @property string $system_name
40 * @property Collection $roles
42 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
49 * The database table used by the model.
53 protected $table = 'users';
56 * The attributes that are mass assignable.
60 protected $fillable = ['name', 'email'];
62 protected $casts = ['last_activity_at' => 'datetime'];
65 * The attributes excluded from the model's JSON form.
70 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
71 'created_at', 'updated_at', 'image_id',
75 * This holds the user's permissions when loaded.
79 protected $permissions;
82 * This holds the default user when loaded.
86 protected static $defaultUser = null;
89 * Returns the default public user.
91 public static function getDefault(): User
93 if (!is_null(static::$defaultUser)) {
94 return static::$defaultUser;
97 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
99 return static::$defaultUser;
103 * Check if the user is the default public user.
105 public function isDefault(): bool
107 return $this->system_name === 'public';
111 * The roles that belong to the user.
113 * @return BelongsToMany
115 public function roles()
117 if ($this->id === 0) {
121 return $this->belongsToMany(Role::class);
125 * Check if the user has a role.
127 public function hasRole($roleId): bool
129 return $this->roles->pluck('id')->contains($roleId);
133 * Check if the user has a role.
135 public function hasSystemRole(string $roleSystemName): bool
137 return $this->roles->pluck('system_name')->contains($roleSystemName);
141 * Attach the default system role to this user.
143 public function attachDefaultRole(): void
145 $roleId = setting('registration-role');
146 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
147 $this->roles()->attach($roleId);
152 * Check if the user has a particular permission.
154 public function can(string $permissionName): bool
156 if ($this->email === 'guest') {
160 return $this->permissions()->contains($permissionName);
164 * Get all permissions belonging to a the current user.
166 protected function permissions(): Collection
168 if (isset($this->permissions)) {
169 return $this->permissions;
172 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
173 ->select('role_permissions.name as name')->distinct()
174 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
175 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
176 ->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);
200 * Get the social account associated with this user.
202 public function socialAccounts(): HasMany
204 return $this->hasMany(SocialAccount::class);
208 * Check if the user has a social account,
209 * If a driver is passed it checks for that single account type.
211 * @param bool|string $socialDriver
215 public function hasSocialAccount($socialDriver = false)
217 if ($socialDriver === false) {
218 return $this->socialAccounts()->count() > 0;
221 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
225 * Returns a URL to the user's avatar.
227 public function getAvatar(int $size = 50): string
229 $default = url('/user_avatar.png');
230 $imageId = $this->image_id;
231 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
236 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
237 } catch (Exception $err) {
245 * Get the avatar for the user.
247 public function avatar(): BelongsTo
249 return $this->belongsTo(Image::class, 'image_id');
253 * Get the API tokens assigned to this user.
255 public function apiTokens(): HasMany
257 return $this->hasMany(ApiToken::class);
261 * Get the favourite instances for this user.
263 public function favourites(): HasMany
265 return $this->hasMany(Favourite::class);
269 * Get the last activity time for this user.
271 public function scopeWithLastActivityAt(Builder $query)
273 $query->addSelect(['activities.created_at as last_activity_at'])
274 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
275 $query->from('activities')->select('user_id')
276 ->selectRaw('max(created_at) as created_at')
277 ->groupBy('user_id');
278 }, 'activities', 'users.id', '=', 'activities.user_id');
282 * Get the url for editing this user.
284 public function getEditUrl(string $path = ''): string
286 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
288 return url(rtrim($uri, '/'));
292 * Get the url that links to this user's profile.
294 public function getProfileUrl(): string
296 return url('/user/' . $this->slug);
300 * Get a shortened version of the user's name.
302 public function getShortName(int $chars = 8): string
304 if (mb_strlen($this->name) <= $chars) {
308 $splitName = explode(' ', $this->name);
309 if (mb_strlen($splitName[0]) <= $chars) {
310 return $splitName[0];
317 * Send the password reset notification.
319 * @param string $token
323 public function sendPasswordResetNotification($token)
325 $this->notify(new ResetPassword($token));
331 public function logDescriptor(): string
333 return "({$this->id}) {$this->name}";
339 public function refreshSlug(): string
341 $this->slug = app(SlugGenerator::class)->generate($this);