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