]> BookStack Code Mirror - bookstack/blob - app/Users/Models/User.php
Fix Dark theme
[bookstack] / app / Users / Models / User.php
1 <?php
2
3 namespace BookStack\Users\Models;
4
5 use BookStack\Access\Mfa\MfaValue;
6 use BookStack\Access\SocialAccount;
7 use BookStack\Activity\Models\Favourite;
8 use BookStack\Activity\Models\Loggable;
9 use BookStack\Api\ApiToken;
10 use BookStack\App\Model;
11 use BookStack\App\Sluggable;
12 use BookStack\Entities\Tools\SlugGenerator;
13 use BookStack\Notifications\ResetPassword;
14 use BookStack\Uploads\Image;
15 use Carbon\Carbon;
16 use Exception;
17 use Illuminate\Auth\Authenticatable;
18 use Illuminate\Auth\Passwords\CanResetPassword;
19 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
20 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
21 use Illuminate\Database\Eloquent\Builder;
22 use Illuminate\Database\Eloquent\Factories\HasFactory;
23 use Illuminate\Database\Eloquent\Relations\BelongsTo;
24 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
25 use Illuminate\Database\Eloquent\Relations\HasMany;
26 use Illuminate\Notifications\Notifiable;
27 use Illuminate\Support\Collection;
28
29 /**
30  * Class User.
31  *
32  * @property int        $id
33  * @property string     $name
34  * @property string     $slug
35  * @property string     $email
36  * @property string     $password
37  * @property Carbon     $created_at
38  * @property Carbon     $updated_at
39  * @property bool       $email_confirmed
40  * @property int        $image_id
41  * @property string     $external_auth_id
42  * @property string     $system_name
43  * @property Collection $roles
44  * @property Collection $mfaValues
45  */
46 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
47 {
48     use HasFactory;
49     use Authenticatable;
50     use CanResetPassword;
51     use Notifiable;
52
53     /**
54      * The database table used by the model.
55      *
56      * @var string
57      */
58     protected $table = 'users';
59
60     /**
61      * The attributes that are mass assignable.
62      *
63      * @var array
64      */
65     protected $fillable = ['name', 'email'];
66
67     protected $casts = ['last_activity_at' => 'datetime'];
68
69     /**
70      * The attributes excluded from the model's JSON form.
71      *
72      * @var array
73      */
74     protected $hidden = [
75         'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
76         'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
77     ];
78
79     /**
80      * This holds the user's permissions when loaded.
81      */
82     protected ?Collection $permissions;
83
84     /**
85      * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
86      */
87     protected string $avatarUrl = '';
88
89     /**
90      * This holds the default user when loaded.
91      *
92      * @var null|User
93      */
94     protected static ?User $defaultUser = null;
95
96     /**
97      * Returns the default public user.
98      */
99     public static function getDefault(): self
100     {
101         if (!is_null(static::$defaultUser)) {
102             return static::$defaultUser;
103         }
104
105         static::$defaultUser = static::query()->where('system_name', '=', 'public')->first();
106
107         return static::$defaultUser;
108     }
109
110     /**
111      * Check if the user is the default public user.
112      */
113     public function isDefault(): bool
114     {
115         return $this->system_name === 'public';
116     }
117
118     /**
119      * The roles that belong to the user.
120      *
121      * @return BelongsToMany
122      */
123     public function roles()
124     {
125         if ($this->id === 0) {
126             return;
127         }
128
129         return $this->belongsToMany(Role::class);
130     }
131
132     /**
133      * Check if the user has a role.
134      */
135     public function hasRole($roleId): bool
136     {
137         return $this->roles->pluck('id')->contains($roleId);
138     }
139
140     /**
141      * Check if the user has a role.
142      */
143     public function hasSystemRole(string $roleSystemName): bool
144     {
145         return $this->roles->pluck('system_name')->contains($roleSystemName);
146     }
147
148     /**
149      * Attach the default system role to this user.
150      */
151     public function attachDefaultRole(): void
152     {
153         $roleId = intval(setting('registration-role'));
154         if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
155             $this->roles()->attach($roleId);
156         }
157     }
158
159     /**
160      * Check if the user has a particular permission.
161      */
162     public function can(string $permissionName): bool
163     {
164         if ($this->email === 'guest') {
165             return false;
166         }
167
168         return $this->permissions()->contains($permissionName);
169     }
170
171     /**
172      * Get all permissions belonging to the current user.
173      */
174     protected function permissions(): Collection
175     {
176         if (isset($this->permissions)) {
177             return $this->permissions;
178         }
179
180         $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
181             ->select('role_permissions.name as name')->distinct()
182             ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
183             ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
184             ->where('ru.user_id', '=', $this->id)
185             ->pluck('name');
186
187         return $this->permissions;
188     }
189
190     /**
191      * Clear any cached permissions on this instance.
192      */
193     public function clearPermissionCache()
194     {
195         $this->permissions = null;
196     }
197
198     /**
199      * Attach a role to this user.
200      */
201     public function attachRole(Role $role)
202     {
203         $this->roles()->attach($role->id);
204         $this->unsetRelation('roles');
205     }
206
207     /**
208      * Get the social account associated with this user.
209      */
210     public function socialAccounts(): HasMany
211     {
212         return $this->hasMany(SocialAccount::class);
213     }
214
215     /**
216      * Check if the user has a social account,
217      * If a driver is passed it checks for that single account type.
218      *
219      * @param bool|string $socialDriver
220      *
221      * @return bool
222      */
223     public function hasSocialAccount($socialDriver = false)
224     {
225         if ($socialDriver === false) {
226             return $this->socialAccounts()->count() > 0;
227         }
228
229         return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
230     }
231
232     /**
233      * Returns a URL to the user's avatar.
234      */
235     public function getAvatar(int $size = 50): string
236     {
237         $default = url('/user_avatar.png');
238         $imageId = $this->image_id;
239         if ($imageId === 0 || $imageId === '0' || $imageId === null) {
240             return $default;
241         }
242
243         if (!empty($this->avatarUrl)) {
244             return $this->avatarUrl;
245         }
246
247         try {
248             $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
249         } catch (Exception $err) {
250             $avatar = $default;
251         }
252
253         $this->avatarUrl = $avatar;
254
255         return $avatar;
256     }
257
258     /**
259      * Get the avatar for the user.
260      */
261     public function avatar(): BelongsTo
262     {
263         return $this->belongsTo(Image::class, 'image_id');
264     }
265
266     /**
267      * Get the API tokens assigned to this user.
268      */
269     public function apiTokens(): HasMany
270     {
271         return $this->hasMany(ApiToken::class);
272     }
273
274     /**
275      * Get the favourite instances for this user.
276      */
277     public function favourites(): HasMany
278     {
279         return $this->hasMany(Favourite::class);
280     }
281
282     /**
283      * Get the MFA values belonging to this use.
284      */
285     public function mfaValues(): HasMany
286     {
287         return $this->hasMany(MfaValue::class);
288     }
289
290     /**
291      * Get the last activity time for this user.
292      */
293     public function scopeWithLastActivityAt(Builder $query)
294     {
295         $query->addSelect(['activities.created_at as last_activity_at'])
296             ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
297                 $query->from('activities')->select('user_id')
298                     ->selectRaw('max(created_at) as created_at')
299                     ->groupBy('user_id');
300             }, 'activities', 'users.id', '=', 'activities.user_id');
301     }
302
303     /**
304      * Get the url for editing this user.
305      */
306     public function getEditUrl(string $path = ''): string
307     {
308         $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
309
310         return url(rtrim($uri, '/'));
311     }
312
313     /**
314      * Get the url that links to this user's profile.
315      */
316     public function getProfileUrl(): string
317     {
318         return url('/user/' . $this->slug);
319     }
320
321     /**
322      * Get a shortened version of the user's name.
323      */
324     public function getShortName(int $chars = 8): string
325     {
326         if (mb_strlen($this->name) <= $chars) {
327             return $this->name;
328         }
329
330         $splitName = explode(' ', $this->name);
331         if (mb_strlen($splitName[0]) <= $chars) {
332             return $splitName[0];
333         }
334
335         return '';
336     }
337
338     /**
339      * Send the password reset notification.
340      *
341      * @param string $token
342      *
343      * @return void
344      */
345     public function sendPasswordResetNotification($token)
346     {
347         $this->notify(new ResetPassword($token));
348     }
349
350     /**
351      * {@inheritdoc}
352      */
353     public function logDescriptor(): string
354     {
355         return "({$this->id}) {$this->name}";
356     }
357
358     /**
359      * {@inheritdoc}
360      */
361     public function refreshSlug(): string
362     {
363         $this->slug = app(SlugGenerator::class)->generate($this);
364
365         return $this->slug;
366     }
367 }