1 <?php namespace BookStack\Auth;
3 use BookStack\Api\ApiToken;
4 use BookStack\Interfaces\Loggable;
6 use BookStack\Notifications\ResetPassword;
7 use BookStack\Uploads\Image;
10 use Illuminate\Auth\Authenticatable;
11 use Illuminate\Auth\Passwords\CanResetPassword;
12 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
13 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Eloquent\Relations\BelongsTo;
16 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
17 use Illuminate\Database\Eloquent\Relations\HasMany;
18 use Illuminate\Notifications\Notifiable;
19 use Illuminate\Support\Collection;
23 * @property string $id
24 * @property string $name
25 * @property string $email
26 * @property string $password
27 * @property Carbon $created_at
28 * @property Carbon $updated_at
29 * @property bool $email_confirmed
30 * @property int $image_id
31 * @property string $external_auth_id
32 * @property string $system_name
34 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable
36 use Authenticatable, CanResetPassword, Notifiable;
39 * The database table used by the model.
42 protected $table = 'users';
45 * The attributes that are mass assignable.
48 protected $fillable = ['name', 'email'];
50 protected $casts = ['last_activity_at' => 'datetime'];
53 * The attributes excluded from the model's JSON form.
57 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
58 'created_at', 'updated_at', 'image_id',
62 * This holds the user's permissions when loaded.
65 protected $permissions;
68 * This holds the default user when loaded.
71 protected static $defaultUser = null;
74 * Returns the default public user.
77 public static function getDefault()
79 if (!is_null(static::$defaultUser)) {
80 return static::$defaultUser;
83 static::$defaultUser = static::where('system_name', '=', 'public')->first();
84 return static::$defaultUser;
88 * Check if the user is the default public user.
91 public function isDefault()
93 return $this->system_name === 'public';
97 * The roles that belong to the user.
98 * @return BelongsToMany
100 public function roles()
102 if ($this->id === 0) {
105 return $this->belongsToMany(Role::class);
109 * Check if the user has a role.
111 public function hasRole($roleId): bool
113 return $this->roles->pluck('id')->contains($roleId);
117 * Check if the user has a role.
121 public function hasSystemRole($role)
123 return $this->roles->pluck('system_name')->contains($role);
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.
189 public function socialAccounts()
191 return $this->hasMany(SocialAccount::class);
195 * Check if the user has a social account,
196 * If a driver is passed it checks for that single account type.
197 * @param bool|string $socialDriver
200 public function hasSocialAccount($socialDriver = false)
202 if ($socialDriver === false) {
203 return $this->socialAccounts()->count() > 0;
206 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
210 * Returns the user's avatar,
214 public function getAvatar($size = 50)
216 $default = url('/user_avatar.png');
217 $imageId = $this->image_id;
218 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
223 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
224 } catch (Exception $err) {
231 * Get the avatar for the user.
234 public function avatar()
236 return $this->belongsTo(Image::class, 'image_id');
240 * Get the API tokens assigned to this user.
242 public function apiTokens(): HasMany
244 return $this->hasMany(ApiToken::class);
248 * Get the last activity time for this user.
250 public function scopeWithLastActivityAt(Builder $query)
252 $query->addSelect(['activities.created_at as last_activity_at'])
253 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
254 $query->from('activities')->select('user_id')
255 ->selectRaw('max(created_at) as created_at')
256 ->groupBy('user_id');
257 }, 'activities', 'users.id', '=', 'activities.user_id');
261 * Get the url for editing this user.
263 public function getEditUrl(string $path = ''): string
265 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
266 return url(rtrim($uri, '/'));
270 * Get the url that links to this user's profile.
272 public function getProfileUrl(): string
274 return url('/user/' . $this->id);
278 * Get a shortened version of the user's name.
282 public function getShortName($chars = 8)
284 if (mb_strlen($this->name) <= $chars) {
288 $splitName = explode(' ', $this->name);
289 if (mb_strlen($splitName[0]) <= $chars) {
290 return $splitName[0];
297 * Send the password reset notification.
298 * @param string $token
301 public function sendPasswordResetNotification($token)
303 $this->notify(new ResetPassword($token));
309 public function logDescriptor(): string
311 return "({$this->id}) {$this->name}";