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
33 * @property Collection $roles
35 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable
37 use Authenticatable, CanResetPassword, Notifiable;
40 * The database table used by the model.
43 protected $table = 'users';
46 * The attributes that are mass assignable.
49 protected $fillable = ['name', 'email'];
51 protected $casts = ['last_activity_at' => 'datetime'];
54 * The attributes excluded from the model's JSON form.
58 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
59 'created_at', 'updated_at', 'image_id',
63 * This holds the user's permissions when loaded.
66 protected $permissions;
69 * This holds the default user when loaded.
72 protected static $defaultUser = null;
75 * Returns the default public user.
78 public static function getDefault()
80 if (!is_null(static::$defaultUser)) {
81 return static::$defaultUser;
84 static::$defaultUser = static::where('system_name', '=', 'public')->first();
85 return static::$defaultUser;
89 * Check if the user is the default public user.
92 public function isDefault()
94 return $this->system_name === 'public';
98 * The roles that belong to the user.
99 * @return BelongsToMany
101 public function roles()
103 if ($this->id === 0) {
106 return $this->belongsToMany(Role::class);
110 * Check if the user has a role.
112 public function hasRole($roleId): bool
114 return $this->roles->pluck('id')->contains($roleId);
118 * Check if the user has a role.
122 public function hasSystemRole($role)
124 return $this->roles->pluck('system_name')->contains($role);
128 * Attach the default system role to this user.
130 public function attachDefaultRole(): void
132 $roleId = setting('registration-role');
133 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
134 $this->roles()->attach($roleId);
139 * Check if the user has a particular permission.
141 public function can(string $permissionName): bool
143 if ($this->email === 'guest') {
147 return $this->permissions()->contains($permissionName);
151 * Get all permissions belonging to a the current user.
153 protected function permissions(): Collection
155 if (isset($this->permissions)) {
156 return $this->permissions;
159 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
160 ->select('role_permissions.name as name')->distinct()
161 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
162 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
163 ->where('ru.user_id', '=', $this->id)
167 return $this->permissions;
171 * Clear any cached permissions on this instance.
173 public function clearPermissionCache()
175 $this->permissions = null;
179 * Attach a role to this user.
181 public function attachRole(Role $role)
183 $this->roles()->attach($role->id);
187 * Get the social account associated with this user.
190 public function socialAccounts()
192 return $this->hasMany(SocialAccount::class);
196 * Check if the user has a social account,
197 * If a driver is passed it checks for that single account type.
198 * @param bool|string $socialDriver
201 public function hasSocialAccount($socialDriver = false)
203 if ($socialDriver === false) {
204 return $this->socialAccounts()->count() > 0;
207 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
211 * Returns the user's avatar,
215 public function getAvatar($size = 50)
217 $default = url('/user_avatar.png');
218 $imageId = $this->image_id;
219 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
224 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
225 } catch (Exception $err) {
232 * Get the avatar for the user.
235 public function avatar()
237 return $this->belongsTo(Image::class, 'image_id');
241 * Get the API tokens assigned to this user.
243 public function apiTokens(): HasMany
245 return $this->hasMany(ApiToken::class);
249 * Get the last activity time for this user.
251 public function scopeWithLastActivityAt(Builder $query)
253 $query->addSelect(['activities.created_at as last_activity_at'])
254 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
255 $query->from('activities')->select('user_id')
256 ->selectRaw('max(created_at) as created_at')
257 ->groupBy('user_id');
258 }, 'activities', 'users.id', '=', 'activities.user_id');
262 * Get the url for editing this user.
264 public function getEditUrl(string $path = ''): string
266 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
267 return url(rtrim($uri, '/'));
271 * Get the url that links to this user's profile.
273 public function getProfileUrl(): string
275 return url('/user/' . $this->id);
279 * Get a shortened version of the user's name.
283 public function getShortName($chars = 8)
285 if (mb_strlen($this->name) <= $chars) {
289 $splitName = explode(' ', $this->name);
290 if (mb_strlen($splitName[0]) <= $chars) {
291 return $splitName[0];
298 * Send the password reset notification.
299 * @param string $token
302 public function sendPasswordResetNotification($token)
304 $this->notify(new ResetPassword($token));
310 public function logDescriptor(): string
312 return "({$this->id}) {$this->name}";