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