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