1 <?php namespace BookStack\Auth;
3 use BookStack\Api\ApiToken;
4 use BookStack\Entities\Tools\SlugGenerator;
5 use BookStack\Interfaces\Loggable;
6 use BookStack\Interfaces\Sluggable;
8 use BookStack\Notifications\ResetPassword;
9 use BookStack\Uploads\Image;
12 use Illuminate\Auth\Authenticatable;
13 use Illuminate\Auth\Passwords\CanResetPassword;
14 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
15 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
16 use Illuminate\Database\Eloquent\Builder;
17 use Illuminate\Database\Eloquent\Relations\BelongsTo;
18 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
19 use Illuminate\Database\Eloquent\Relations\HasMany;
20 use Illuminate\Notifications\Notifiable;
21 use Illuminate\Support\Collection;
25 * @property string $id
26 * @property string $name
27 * @property string $slug
28 * @property string $email
29 * @property string $password
30 * @property Carbon $created_at
31 * @property Carbon $updated_at
32 * @property bool $email_confirmed
33 * @property int $image_id
34 * @property string $external_auth_id
35 * @property string $system_name
36 * @property Collection $roles
38 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
40 use Authenticatable, CanResetPassword, Notifiable;
43 * The database table used by the model.
46 protected $table = 'users';
49 * The attributes that are mass assignable.
52 protected $fillable = ['name', 'email'];
54 protected $casts = ['last_activity_at' => 'datetime'];
57 * The attributes excluded from the model's JSON form.
61 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
62 'created_at', 'updated_at', 'image_id',
66 * This holds the user's permissions when loaded.
69 protected $permissions;
72 * This holds the default user when loaded.
75 protected static $defaultUser = null;
78 * Returns the default public user.
80 public static function getDefault(): User
82 if (!is_null(static::$defaultUser)) {
83 return static::$defaultUser;
86 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
87 return static::$defaultUser;
91 * Check if the user is the default public user.
93 public function isDefault(): bool
95 return $this->system_name === 'public';
99 * The roles that belong to the user.
100 * @return BelongsToMany
102 public function roles()
104 if ($this->id === 0) {
107 return $this->belongsToMany(Role::class);
111 * Check if the user has a role.
113 public function hasRole($roleId): bool
115 return $this->roles->pluck('id')->contains($roleId);
119 * Check if the user has a role.
121 public function hasSystemRole(string $roleSystemName): bool
123 return $this->roles->pluck('system_name')->contains($roleSystemName);
127 * Attach the default system role to this user.
129 public function attachDefaultRole(): void
131 $roleId = setting('registration-role');
132 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
133 $this->roles()->attach($roleId);
138 * Check if the user has a particular permission.
140 public function can(string $permissionName): bool
142 if ($this->email === 'guest') {
146 return $this->permissions()->contains($permissionName);
150 * Get all permissions belonging to a the current user.
152 protected function permissions(): Collection
154 if (isset($this->permissions)) {
155 return $this->permissions;
158 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
159 ->select('role_permissions.name as name')->distinct()
160 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
161 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
162 ->where('ru.user_id', '=', $this->id)
166 return $this->permissions;
170 * Clear any cached permissions on this instance.
172 public function clearPermissionCache()
174 $this->permissions = null;
178 * Attach a role to this user.
180 public function attachRole(Role $role)
182 $this->roles()->attach($role->id);
186 * Get the social account associated with this user.
188 public function socialAccounts(): HasMany
190 return $this->hasMany(SocialAccount::class);
194 * Check if the user has a social account,
195 * If a driver is passed it checks for that single account type.
196 * @param bool|string $socialDriver
199 public function hasSocialAccount($socialDriver = false)
201 if ($socialDriver === false) {
202 return $this->socialAccounts()->count() > 0;
205 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
209 * Returns a URL to the user's avatar
211 public function getAvatar(int $size = 50): string
213 $default = url('/user_avatar.png');
214 $imageId = $this->image_id;
215 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
220 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
221 } catch (Exception $err) {
228 * Get the avatar for the user.
230 public function avatar(): BelongsTo
232 return $this->belongsTo(Image::class, 'image_id');
236 * Get the API tokens assigned to this user.
238 public function apiTokens(): HasMany
240 return $this->hasMany(ApiToken::class);
244 * Get the last activity time for this user.
246 public function scopeWithLastActivityAt(Builder $query)
248 $query->addSelect(['activities.created_at as last_activity_at'])
249 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
250 $query->from('activities')->select('user_id')
251 ->selectRaw('max(created_at) as created_at')
252 ->groupBy('user_id');
253 }, 'activities', 'users.id', '=', 'activities.user_id');
257 * Get the url for editing this user.
259 public function getEditUrl(string $path = ''): string
261 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
262 return url(rtrim($uri, '/'));
266 * Get the url that links to this user's profile.
268 public function getProfileUrl(): string
270 return url('/user/' . $this->slug);
274 * Get a shortened version of the user's name.
276 public function getShortName(int $chars = 8): string
278 if (mb_strlen($this->name) <= $chars) {
282 $splitName = explode(' ', $this->name);
283 if (mb_strlen($splitName[0]) <= $chars) {
284 return $splitName[0];
291 * Send the password reset notification.
292 * @param string $token
295 public function sendPasswordResetNotification($token)
297 $this->notify(new ResetPassword($token));
303 public function logDescriptor(): string
305 return "({$this->id}) {$this->name}";
311 public function refreshSlug(): string
313 $this->slug = app(SlugGenerator::class)->generate($this);