]> BookStack Code Mirror - bookstack/blob - app/Users/Models/User.php
Guest control: Cleaned methods involved in fetching/handling
[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\Sluggable;
14 use BookStack\Entities\Tools\SlugGenerator;
15 use BookStack\Translation\LanguageManager;
16 use BookStack\Uploads\Image;
17 use Carbon\Carbon;
18 use Exception;
19 use Illuminate\Auth\Authenticatable;
20 use Illuminate\Auth\Passwords\CanResetPassword;
21 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
22 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
23 use Illuminate\Database\Eloquent\Builder;
24 use Illuminate\Database\Eloquent\Factories\HasFactory;
25 use Illuminate\Database\Eloquent\Relations\BelongsTo;
26 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
27 use Illuminate\Database\Eloquent\Relations\HasMany;
28 use Illuminate\Notifications\Notifiable;
29 use Illuminate\Support\Collection;
30
31 /**
32  * Class User.
33  *
34  * @property int        $id
35  * @property string     $name
36  * @property string     $slug
37  * @property string     $email
38  * @property string     $password
39  * @property Carbon     $created_at
40  * @property Carbon     $updated_at
41  * @property bool       $email_confirmed
42  * @property int        $image_id
43  * @property string     $external_auth_id
44  * @property string     $system_name
45  * @property Collection $roles
46  * @property Collection $mfaValues
47  */
48 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
49 {
50     use HasFactory;
51     use Authenticatable;
52     use CanResetPassword;
53     use Notifiable;
54
55     /**
56      * The database table used by the model.
57      *
58      * @var string
59      */
60     protected $table = 'users';
61
62     /**
63      * The attributes that are mass assignable.
64      *
65      * @var array
66      */
67     protected $fillable = ['name', 'email'];
68
69     protected $casts = ['last_activity_at' => 'datetime'];
70
71     /**
72      * The attributes excluded from the model's JSON form.
73      *
74      * @var array
75      */
76     protected $hidden = [
77         'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
78         'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
79     ];
80
81     /**
82      * This holds the user's permissions when loaded.
83      */
84     protected ?Collection $permissions;
85
86     /**
87      * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
88      */
89     protected string $avatarUrl = '';
90
91     /**
92      * Returns the default public user.
93      * Fetches from the container as a singleton to effectively cache at an app level.
94      */
95     public static function getGuest(): self
96     {
97         return app()->make('users.default');
98     }
99
100     /**
101      * Check if the user is the default public user.
102      */
103     public function isGuest(): bool
104     {
105         return $this->system_name === 'public';
106     }
107
108     /**
109      * Check if the user has general access to the application.
110      */
111     public function hasAppAccess(): bool
112     {
113         return !$this->isGuest() || setting('app-public');
114     }
115
116     /**
117      * The roles that belong to the user.
118      *
119      * @return BelongsToMany
120      */
121     public function roles()
122     {
123         if ($this->id === 0) {
124             return;
125         }
126
127         return $this->belongsToMany(Role::class);
128     }
129
130     /**
131      * Check if the user has a role.
132      */
133     public function hasRole($roleId): bool
134     {
135         return $this->roles->pluck('id')->contains($roleId);
136     }
137
138     /**
139      * Check if the user has a role.
140      */
141     public function hasSystemRole(string $roleSystemName): bool
142     {
143         return $this->roles->pluck('system_name')->contains($roleSystemName);
144     }
145
146     /**
147      * Attach the default system role to this user.
148      */
149     public function attachDefaultRole(): void
150     {
151         $roleId = intval(setting('registration-role'));
152         if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
153             $this->roles()->attach($roleId);
154         }
155     }
156
157     /**
158      * Check if the user has a particular permission.
159      */
160     public function can(string $permissionName): bool
161     {
162         if ($this->email === 'guest') {
163             return false;
164         }
165
166         return $this->permissions()->contains($permissionName);
167     }
168
169     /**
170      * Get all permissions belonging to the current user.
171      */
172     protected function permissions(): Collection
173     {
174         if (isset($this->permissions)) {
175             return $this->permissions;
176         }
177
178         $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
179             ->select('role_permissions.name as name')->distinct()
180             ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
181             ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
182             ->where('ru.user_id', '=', $this->id)
183             ->pluck('name');
184
185         return $this->permissions;
186     }
187
188     /**
189      * Clear any cached permissions on this instance.
190      */
191     public function clearPermissionCache()
192     {
193         $this->permissions = null;
194     }
195
196     /**
197      * Attach a role to this user.
198      */
199     public function attachRole(Role $role)
200     {
201         $this->roles()->attach($role->id);
202         $this->unsetRelation('roles');
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 tracked entity watches for this user.
290      */
291     public function watches(): HasMany
292     {
293         return $this->hasMany(Watch::class);
294     }
295
296     /**
297      * Get the last activity time for this user.
298      */
299     public function scopeWithLastActivityAt(Builder $query)
300     {
301         $query->addSelect(['activities.created_at as last_activity_at'])
302             ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
303                 $query->from('activities')->select('user_id')
304                     ->selectRaw('max(created_at) as created_at')
305                     ->groupBy('user_id');
306             }, 'activities', 'users.id', '=', 'activities.user_id');
307     }
308
309     /**
310      * Get the url for editing this user.
311      */
312     public function getEditUrl(string $path = ''): string
313     {
314         $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
315
316         return url(rtrim($uri, '/'));
317     }
318
319     /**
320      * Get the url that links to this user's profile.
321      */
322     public function getProfileUrl(): string
323     {
324         return url('/user/' . $this->slug);
325     }
326
327     /**
328      * Get a shortened version of the user's name.
329      */
330     public function getShortName(int $chars = 8): string
331     {
332         if (mb_strlen($this->name) <= $chars) {
333             return $this->name;
334         }
335
336         $splitName = explode(' ', $this->name);
337         if (mb_strlen($splitName[0]) <= $chars) {
338             return $splitName[0];
339         }
340
341         return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
342     }
343
344     /**
345      * Get the system language for this user.
346      */
347     public function getLanguage(): string
348     {
349         return app()->make(LanguageManager::class)->getLanguageForUser($this);
350     }
351
352     /**
353      * Send the password reset notification.
354      *
355      * @param string $token
356      *
357      * @return void
358      */
359     public function sendPasswordResetNotification($token)
360     {
361         $this->notify(new ResetPasswordNotification($token));
362     }
363
364     /**
365      * {@inheritdoc}
366      */
367     public function logDescriptor(): string
368     {
369         return "({$this->id}) {$this->name}";
370     }
371
372     /**
373      * {@inheritdoc}
374      */
375     public function refreshSlug(): string
376     {
377         $this->slug = app(SlugGenerator::class)->generate($this);
378
379         return $this->slug;
380     }
381 }