1 <?php namespace BookStack\Auth;
3 use BookStack\Api\ApiToken;
4 use BookStack\Interfaces\Loggable;
5 use BookStack\Interfaces\Sluggable;
7 use BookStack\Notifications\ResetPassword;
8 use BookStack\Uploads\Image;
11 use Illuminate\Auth\Authenticatable;
12 use Illuminate\Auth\Passwords\CanResetPassword;
13 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
14 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Database\Eloquent\Relations\BelongsTo;
17 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
18 use Illuminate\Database\Eloquent\Relations\HasMany;
19 use Illuminate\Notifications\Notifiable;
20 use Illuminate\Support\Collection;
24 * @property string $id
25 * @property string $name
26 * @property string $slug
27 * @property string $email
28 * @property string $password
29 * @property Carbon $created_at
30 * @property Carbon $updated_at
31 * @property bool $email_confirmed
32 * @property int $image_id
33 * @property string $external_auth_id
34 * @property string $system_name
35 * @property Collection $roles
37 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
39 use Authenticatable, CanResetPassword, Notifiable;
42 * The database table used by the model.
45 protected $table = 'users';
48 * The attributes that are mass assignable.
51 protected $fillable = ['name', 'email'];
53 protected $casts = ['last_activity_at' => 'datetime'];
56 * The attributes excluded from the model's JSON form.
60 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
61 'created_at', 'updated_at', 'image_id',
65 * This holds the user's permissions when loaded.
68 protected $permissions;
71 * This holds the default user when loaded.
74 protected static $defaultUser = null;
77 * Returns the default public user.
79 public static function getDefault(): User
81 if (!is_null(static::$defaultUser)) {
82 return static::$defaultUser;
85 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
86 return static::$defaultUser;
90 * Check if the user is the default public user.
92 public function isDefault(): bool
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.
120 public function hasSystemRole(string $roleSystemName): bool
122 return $this->roles->pluck('system_name')->contains($roleSystemName);
126 * Attach the default system role to this user.
128 public function attachDefaultRole(): void
130 $roleId = setting('registration-role');
131 if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
132 $this->roles()->attach($roleId);
137 * Check if the user has a particular permission.
139 public function can(string $permissionName): bool
141 if ($this->email === 'guest') {
145 return $this->permissions()->contains($permissionName);
149 * Get all permissions belonging to a the current user.
151 protected function permissions(): Collection
153 if (isset($this->permissions)) {
154 return $this->permissions;
157 $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
158 ->select('role_permissions.name as name')->distinct()
159 ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
160 ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
161 ->where('ru.user_id', '=', $this->id)
165 return $this->permissions;
169 * Clear any cached permissions on this instance.
171 public function clearPermissionCache()
173 $this->permissions = null;
177 * Attach a role to this user.
179 public function attachRole(Role $role)
181 $this->roles()->attach($role->id);
185 * Get the social account associated with this user.
187 public function socialAccounts(): HasMany
189 return $this->hasMany(SocialAccount::class);
193 * Check if the user has a social account,
194 * If a driver is passed it checks for that single account type.
195 * @param bool|string $socialDriver
198 public function hasSocialAccount($socialDriver = false)
200 if ($socialDriver === false) {
201 return $this->socialAccounts()->count() > 0;
204 return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
208 * Returns a URL to the user's avatar
210 public function getAvatar(int $size = 50): string
212 $default = url('/user_avatar.png');
213 $imageId = $this->image_id;
214 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
219 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
220 } catch (Exception $err) {
227 * Get the avatar for the user.
229 public function avatar(): BelongsTo
231 return $this->belongsTo(Image::class, 'image_id');
235 * Get the API tokens assigned to this user.
237 public function apiTokens(): HasMany
239 return $this->hasMany(ApiToken::class);
243 * Get the last activity time for this user.
245 public function scopeWithLastActivityAt(Builder $query)
247 $query->addSelect(['activities.created_at as last_activity_at'])
248 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
249 $query->from('activities')->select('user_id')
250 ->selectRaw('max(created_at) as created_at')
251 ->groupBy('user_id');
252 }, 'activities', 'users.id', '=', 'activities.user_id');
256 * Get the url for editing this user.
258 public function getEditUrl(string $path = ''): string
260 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
261 return url(rtrim($uri, '/'));
265 * Get the url that links to this user's profile.
267 public function getProfileUrl(): string
269 return url('/user/' . $this->id);
273 * Get a shortened version of the user's name.
275 public function getShortName(int $chars = 8): string
277 if (mb_strlen($this->name) <= $chars) {
281 $splitName = explode(' ', $this->name);
282 if (mb_strlen($splitName[0]) <= $chars) {
283 return $splitName[0];
290 * Send the password reset notification.
291 * @param string $token
294 public function sendPasswordResetNotification($token)
296 $this->notify(new ResetPassword($token));
302 public function logDescriptor(): string
304 return "({$this->id}) {$this->name}";