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