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