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