]> BookStack Code Mirror - bookstack/blob - app/Users/Models/User.php
Images: Prevented base64 extraction without permission
[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\LocaleDefinition;
16 use BookStack\Translation\LocaleManager;
17 use BookStack\Uploads\Image;
18 use Carbon\Carbon;
19 use Exception;
20 use Illuminate\Auth\Authenticatable;
21 use Illuminate\Auth\Passwords\CanResetPassword;
22 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
23 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
24 use Illuminate\Database\Eloquent\Builder;
25 use Illuminate\Database\Eloquent\Factories\HasFactory;
26 use Illuminate\Database\Eloquent\Relations\BelongsTo;
27 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
28 use Illuminate\Database\Eloquent\Relations\HasMany;
29 use Illuminate\Notifications\Notifiable;
30 use Illuminate\Support\Collection;
31
32 /**
33  * Class User.
34  *
35  * @property int        $id
36  * @property string     $name
37  * @property string     $slug
38  * @property string     $email
39  * @property string     $password
40  * @property Carbon     $created_at
41  * @property Carbon     $updated_at
42  * @property bool       $email_confirmed
43  * @property int        $image_id
44  * @property string     $external_auth_id
45  * @property string     $system_name
46  * @property Collection $roles
47  * @property Collection $mfaValues
48  */
49 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, Sluggable
50 {
51     use HasFactory;
52     use Authenticatable;
53     use CanResetPassword;
54     use Notifiable;
55
56     /**
57      * The database table used by the model.
58      *
59      * @var string
60      */
61     protected $table = 'users';
62
63     /**
64      * The attributes that are mass assignable.
65      *
66      * @var array
67      */
68     protected $fillable = ['name', 'email'];
69
70     protected $casts = ['last_activity_at' => 'datetime'];
71
72     /**
73      * The attributes excluded from the model's JSON form.
74      *
75      * @var array
76      */
77     protected $hidden = [
78         'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
79         'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
80     ];
81
82     /**
83      * This holds the user's permissions when loaded.
84      */
85     protected ?Collection $permissions;
86
87     /**
88      * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
89      */
90     protected string $avatarUrl = '';
91
92     /**
93      * Returns the default public user.
94      * Fetches from the container as a singleton to effectively cache at an app level.
95      */
96     public static function getGuest(): self
97     {
98         return app()->make('users.default');
99     }
100
101     /**
102      * Check if the user is the default public user.
103      */
104     public function isGuest(): bool
105     {
106         return $this->system_name === 'public';
107     }
108
109     /**
110      * Check if the user has general access to the application.
111      */
112     public function hasAppAccess(): bool
113     {
114         return !$this->isGuest() || setting('app-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         return $this->permissions()->contains($permissionName);
164     }
165
166     /**
167      * Get all permissions belonging to the current user.
168      */
169     protected function permissions(): Collection
170     {
171         if (isset($this->permissions)) {
172             return $this->permissions;
173         }
174
175         $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
176             ->select('role_permissions.name as name')->distinct()
177             ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
178             ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
179             ->where('ru.user_id', '=', $this->id)
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         $this->unsetRelation('roles');
200     }
201
202     /**
203      * Get the social account associated with this user.
204      */
205     public function socialAccounts(): HasMany
206     {
207         return $this->hasMany(SocialAccount::class);
208     }
209
210     /**
211      * Check if the user has a social account,
212      * If a driver is passed it checks for that single account type.
213      *
214      * @param bool|string $socialDriver
215      *
216      * @return bool
217      */
218     public function hasSocialAccount($socialDriver = false)
219     {
220         if ($socialDriver === false) {
221             return $this->socialAccounts()->count() > 0;
222         }
223
224         return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
225     }
226
227     /**
228      * Returns a URL to the user's avatar.
229      */
230     public function getAvatar(int $size = 50): string
231     {
232         $default = url('/user_avatar.png');
233         $imageId = $this->image_id;
234         if ($imageId === 0 || $imageId === '0' || $imageId === null) {
235             return $default;
236         }
237
238         if (!empty($this->avatarUrl)) {
239             return $this->avatarUrl;
240         }
241
242         try {
243             $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
244         } catch (Exception $err) {
245             $avatar = $default;
246         }
247
248         $this->avatarUrl = $avatar;
249
250         return $avatar;
251     }
252
253     /**
254      * Get the avatar for the user.
255      */
256     public function avatar(): BelongsTo
257     {
258         return $this->belongsTo(Image::class, 'image_id');
259     }
260
261     /**
262      * Get the API tokens assigned to this user.
263      */
264     public function apiTokens(): HasMany
265     {
266         return $this->hasMany(ApiToken::class);
267     }
268
269     /**
270      * Get the favourite instances for this user.
271      */
272     public function favourites(): HasMany
273     {
274         return $this->hasMany(Favourite::class);
275     }
276
277     /**
278      * Get the MFA values belonging to this use.
279      */
280     public function mfaValues(): HasMany
281     {
282         return $this->hasMany(MfaValue::class);
283     }
284
285     /**
286      * Get the tracked entity watches for this user.
287      */
288     public function watches(): HasMany
289     {
290         return $this->hasMany(Watch::class);
291     }
292
293     /**
294      * Get the last activity time for this user.
295      */
296     public function scopeWithLastActivityAt(Builder $query)
297     {
298         $query->addSelect(['activities.created_at as last_activity_at'])
299             ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
300                 $query->from('activities')->select('user_id')
301                     ->selectRaw('max(created_at) as created_at')
302                     ->groupBy('user_id');
303             }, 'activities', 'users.id', '=', 'activities.user_id');
304     }
305
306     /**
307      * Get the url for editing this user.
308      */
309     public function getEditUrl(string $path = ''): string
310     {
311         $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
312
313         return url(rtrim($uri, '/'));
314     }
315
316     /**
317      * Get the url that links to this user's profile.
318      */
319     public function getProfileUrl(): string
320     {
321         return url('/user/' . $this->slug);
322     }
323
324     /**
325      * Get a shortened version of the user's name.
326      */
327     public function getShortName(int $chars = 8): string
328     {
329         if (mb_strlen($this->name) <= $chars) {
330             return $this->name;
331         }
332
333         $splitName = explode(' ', $this->name);
334         if (mb_strlen($splitName[0]) <= $chars) {
335             return $splitName[0];
336         }
337
338         return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
339     }
340
341     /**
342      * Get the locale for this user.
343      */
344     public function getLocale(): LocaleDefinition
345     {
346         return app()->make(LocaleManager::class)->getForUser($this);
347     }
348
349     /**
350      * Send the password reset notification.
351      *
352      * @param string $token
353      *
354      * @return void
355      */
356     public function sendPasswordResetNotification($token)
357     {
358         $this->notify(new ResetPasswordNotification($token));
359     }
360
361     /**
362      * {@inheritdoc}
363      */
364     public function logDescriptor(): string
365     {
366         return "({$this->id}) {$this->name}";
367     }
368
369     /**
370      * {@inheritdoc}
371      */
372     public function refreshSlug(): string
373     {
374         $this->slug = app()->make(SlugGenerator::class)->generate($this);
375
376         return $this->slug;
377     }
378 }