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