]> BookStack Code Mirror - bookstack/blob - app/Users/Models/User.php
Permissions: Removed unused role-perm columns, added permission enum
[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\Notifications\ResetPasswordNotification;
7 use BookStack\Access\SocialAccount;
8 use BookStack\Activity\Models\Favourite;
9 use BookStack\Activity\Models\Loggable;
10 use BookStack\Activity\Models\Watch;
11 use BookStack\Api\ApiToken;
12 use BookStack\App\Model;
13 use BookStack\App\SluggableInterface;
14 use BookStack\Entities\Tools\SlugGenerator;
15 use BookStack\Permissions\Permission;
16 use BookStack\Translation\LocaleDefinition;
17 use BookStack\Translation\LocaleManager;
18 use BookStack\Uploads\Image;
19 use Carbon\Carbon;
20 use Exception;
21 use Illuminate\Auth\Authenticatable;
22 use Illuminate\Auth\Passwords\CanResetPassword;
23 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
24 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
25 use Illuminate\Database\Eloquent\Builder;
26 use Illuminate\Database\Eloquent\Factories\HasFactory;
27 use Illuminate\Database\Eloquent\Relations\BelongsTo;
28 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
29 use Illuminate\Database\Eloquent\Relations\HasMany;
30 use Illuminate\Notifications\Notifiable;
31 use Illuminate\Support\Collection;
32
33 /**
34  * Class User.
35  *
36  * @property int        $id
37  * @property string     $name
38  * @property string     $slug
39  * @property string     $email
40  * @property string     $password
41  * @property Carbon     $created_at
42  * @property Carbon     $updated_at
43  * @property bool       $email_confirmed
44  * @property int        $image_id
45  * @property string     $external_auth_id
46  * @property string     $system_name
47  * @property Collection $roles
48  * @property Collection $mfaValues
49  * @property ?Image     $avatar
50  */
51 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, SluggableInterface
52 {
53     use HasFactory;
54     use Authenticatable;
55     use CanResetPassword;
56     use Notifiable;
57
58     /**
59      * The database table used by the model.
60      *
61      * @var string
62      */
63     protected $table = 'users';
64
65     /**
66      * The attributes that are mass assignable.
67      *
68      * @var list<string>
69      */
70     protected $fillable = ['name', 'email'];
71
72     protected $casts = ['last_activity_at' => 'datetime'];
73
74     /**
75      * The attributes excluded from the model's JSON form.
76      *
77      * @var list<string>
78      */
79     protected $hidden = [
80         'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
81         'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
82     ];
83
84     /**
85      * This holds the user's permissions when loaded.
86      */
87     protected ?Collection $permissions;
88
89     /**
90      * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
91      */
92     protected string $avatarUrl = '';
93
94     /**
95      * Returns the default public user.
96      * Fetches from the container as a singleton to effectively cache at an app level.
97      */
98     public static function getGuest(): self
99     {
100         return app()->make('users.default');
101     }
102
103     /**
104      * Check if the user is the default public user.
105      */
106     public function isGuest(): bool
107     {
108         return $this->system_name === 'public';
109     }
110
111     /**
112      * Check if the user has general access to the application.
113      */
114     public function hasAppAccess(): bool
115     {
116         return !$this->isGuest() || setting('app-public');
117     }
118
119     /**
120      * The roles that belong to the user.
121      *
122      * @return BelongsToMany<Role, $this>
123      */
124     public function roles(): BelongsToMany
125     {
126         return $this->belongsToMany(Role::class);
127     }
128
129     /**
130      * Check if the user has a role.
131      */
132     public function hasRole($roleId): bool
133     {
134         return $this->roles->pluck('id')->contains($roleId);
135     }
136
137     /**
138      * Check if the user has a role.
139      */
140     public function hasSystemRole(string $roleSystemName): bool
141     {
142         return $this->roles->pluck('system_name')->contains($roleSystemName);
143     }
144
145     /**
146      * Attach the default system role to this user.
147      */
148     public function attachDefaultRole(): void
149     {
150         $roleId = intval(setting('registration-role'));
151         if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
152             $this->roles()->attach($roleId);
153         }
154     }
155
156     /**
157      * Check if the user has a particular permission.
158      */
159     public function can(string|Permission $permission): bool
160     {
161         $permissionName = is_string($permission) ? $permission : $permission->value;
162         return $this->permissions()->contains($permissionName);
163     }
164
165     /**
166      * Get all permissions belonging to 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             ->pluck('name');
180
181         return $this->permissions;
182     }
183
184     /**
185      * Clear any cached permissions in this instance.
186      */
187     public function clearPermissionCache(): void
188     {
189         $this->permissions = null;
190     }
191
192     /**
193      * Attach a role to this user.
194      */
195     public function attachRole(Role $role): void
196     {
197         $this->roles()->attach($role->id);
198         $this->unsetRelation('roles');
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     public function hasSocialAccount(string $socialDriver = ''): bool
214     {
215         if (empty($socialDriver)) {
216             return $this->socialAccounts()->count() > 0;
217         }
218
219         return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
220     }
221
222     /**
223      * Returns a URL to the user's avatar.
224      */
225     public function getAvatar(int $size = 50): string
226     {
227         $default = url('/user_avatar.png');
228         $imageId = $this->image_id;
229         if ($imageId === 0 || $imageId === '0' || $imageId === null) {
230             return $default;
231         }
232
233         if (!empty($this->avatarUrl)) {
234             return $this->avatarUrl;
235         }
236
237         try {
238             $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
239         } catch (Exception $err) {
240             $avatar = $default;
241         }
242
243         $this->avatarUrl = $avatar;
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 tracked entity watches for this user.
282      */
283     public function watches(): HasMany
284     {
285         return $this->hasMany(Watch::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 mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
334     }
335
336     /**
337      * Get the locale for this user.
338      */
339     public function getLocale(): LocaleDefinition
340     {
341         return app()->make(LocaleManager::class)->getForUser($this);
342     }
343
344     /**
345      * Send the password reset notification.
346      *
347      * @param string $token
348      *
349      * @return void
350      */
351     public function sendPasswordResetNotification($token)
352     {
353         $this->notify(new ResetPasswordNotification($token));
354     }
355
356     /**
357      * {@inheritdoc}
358      */
359     public function logDescriptor(): string
360     {
361         return "({$this->id}) {$this->name}";
362     }
363
364     /**
365      * {@inheritdoc}
366      */
367     public function refreshSlug(): string
368     {
369         $this->slug = app()->make(SlugGenerator::class)->generate($this, $this->name);
370
371         return $this->slug;
372     }
373 }