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