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