1 <?php namespace BookStack\Auth;
3 use BookStack\Actions\Favourite;
4 use BookStack\Api\ApiToken;
5 use BookStack\Entities\Tools\SlugGenerator;
6 use BookStack\Interfaces\Loggable;
7 use BookStack\Interfaces\Sluggable;
9 use BookStack\Notifications\ResetPassword;
10 use BookStack\Uploads\Image;
13 use Illuminate\Auth\Authenticatable;
14 use Illuminate\Auth\Passwords\CanResetPassword;
15 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
16 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
17 use Illuminate\Database\Eloquent\Builder;
18 use Illuminate\Database\Eloquent\Relations\BelongsTo;
19 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
20 use Illuminate\Database\Eloquent\Relations\HasMany;
21 use Illuminate\Notifications\Notifiable;
22 use Illuminate\Support\Collection;
26 * @property string $id
27 * @property string $name
28 * @property string $slug
29 * @property string $email
30 * @property string $password
31 * @property Carbon $created_at
32 * @property Carbon $updated_at
33 * @property bool $email_confirmed
34 * @property int $image_id
35 * @property string $external_auth_id
36 * @property string $system_name
37 * @property Collection $roles
39 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
41 use Authenticatable, CanResetPassword, Notifiable;
44 * The database table used by the model.
47 protected $table = 'users';
50 * The attributes that are mass assignable.
53 protected $fillable = ['name', 'email'];
55 protected $casts = ['last_activity_at' => 'datetime'];
58 * The attributes excluded from the model's JSON form.
62 'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
63 'created_at', 'updated_at', 'image_id',
67 * This holds the user's permissions when loaded.
70 protected $permissions;
73 * This holds the default user when loaded.
76 protected static $defaultUser = null;
79 * Returns the default public user.
81 public static function getDefault(): User
83 if (!is_null(static::$defaultUser)) {
84 return static::$defaultUser;
87 static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
88 return static::$defaultUser;
92 * Check if the user is the default public user.
94 public function isDefault(): bool
96 return $this->system_name === 'public';
100 * The roles that belong to the user.
101 * @return BelongsToMany
103 public function roles()
105 if ($this->id === 0) {
108 return $this->belongsToMany(Role::class);
112 * Check if the user has a role.
114 public function hasRole($roleId): bool
116 return $this->roles->pluck('id')->contains($roleId);
120 * Check if the user has a role.
122 public function hasSystemRole(string $roleSystemName): bool
124 return $this->roles->pluck('system_name')->contains($roleSystemName);
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.
189 public function socialAccounts(): HasMany
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 a URL to the user's avatar
212 public function getAvatar(int $size = 50): string
214 $default = url('/user_avatar.png');
215 $imageId = $this->image_id;
216 if ($imageId === 0 || $imageId === '0' || $imageId === null) {
221 $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
222 } catch (Exception $err) {
229 * Get the avatar for the user.
231 public function avatar(): BelongsTo
233 return $this->belongsTo(Image::class, 'image_id');
237 * Get the API tokens assigned to this user.
239 public function apiTokens(): HasMany
241 return $this->hasMany(ApiToken::class);
245 * Get the favourite instances for this user.
247 public function favourites(): HasMany
249 return $this->hasMany(Favourite::class);
253 * Get the last activity time for this user.
255 public function scopeWithLastActivityAt(Builder $query)
257 $query->addSelect(['activities.created_at as last_activity_at'])
258 ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
259 $query->from('activities')->select('user_id')
260 ->selectRaw('max(created_at) as created_at')
261 ->groupBy('user_id');
262 }, 'activities', 'users.id', '=', 'activities.user_id');
266 * Get the url for editing this user.
268 public function getEditUrl(string $path = ''): string
270 $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
271 return url(rtrim($uri, '/'));
275 * Get the url that links to this user's profile.
277 public function getProfileUrl(): string
279 return url('/user/' . $this->slug);
283 * Get a shortened version of the user's name.
285 public function getShortName(int $chars = 8): string
287 if (mb_strlen($this->name) <= $chars) {
291 $splitName = explode(' ', $this->name);
292 if (mb_strlen($splitName[0]) <= $chars) {
293 return $splitName[0];
300 * Send the password reset notification.
301 * @param string $token
304 public function sendPasswordResetNotification($token)
306 $this->notify(new ResetPassword($token));
312 public function logDescriptor(): string
314 return "({$this->id}) {$this->name}";
320 public function refreshSlug(): string
322 $this->slug = app(SlugGenerator::class)->generate($this);