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