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