]> BookStack Code Mirror - bookstack/blob - app/User.php
Updated views for permissions and added notifications. Fixes #2 and #7
[bookstack] / app / User.php
1 <?php
2
3 namespace Oxbow;
4
5 use Illuminate\Auth\Authenticatable;
6 use Illuminate\Database\Eloquent\Model;
7 use Illuminate\Auth\Passwords\CanResetPassword;
8 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
9 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
10
11 class User extends Model implements AuthenticatableContract, CanResetPasswordContract
12 {
13     use Authenticatable, CanResetPassword;
14
15     /**
16      * The database table used by the model.
17      *
18      * @var string
19      */
20     protected $table = 'users';
21
22     /**
23      * The attributes that are mass assignable.
24      *
25      * @var array
26      */
27     protected $fillable = ['name', 'email'];
28
29     /**
30      * The attributes excluded from the model's JSON form.
31      *
32      * @var array
33      */
34     protected $hidden = ['password', 'remember_token'];
35
36     /**
37      * Returns a default guest user.
38      */
39     public static function getDefault()
40     {
41         return new static([
42             'email' => 'guest',
43             'name'  => 'Guest'
44         ]);
45     }
46
47     /**
48      * Permissions and roles
49      */
50
51     /**
52      * The roles that belong to the user.
53      */
54     public function roles()
55     {
56         return $this->belongsToMany('Oxbow\Role');
57     }
58
59     public function getRoleAttribute()
60     {
61         return $this->roles()->first();
62     }
63
64     /**
65      * Check if the user has a particular permission.
66      * @param $permissionName
67      * @return bool
68      */
69     public function can($permissionName)
70     {
71         $permissions = $this->role->permissions()->get();
72         $permissionSearch = $permissions->search(function ($item, $key) use ($permissionName) {
73             return $item->name == $permissionName;
74         });
75         return $permissionSearch !== false;
76     }
77
78     /**
79      * Attach a role to this user.
80      * @param Role $role
81      */
82     public function attachRole(Role $role)
83     {
84         $this->attachRoleId($role->id);
85     }
86
87     /**
88      * Attach a role id to this user.
89      * @param $id
90      */
91     public function attachRoleId($id)
92     {
93         $this->roles()->sync([$id]);
94     }
95
96     /**
97      * Returns the user's avatar,
98      * Uses Gravatar as the avatar service.
99      *
100      * @param int $size
101      * @return string
102      */
103     public function getAvatar($size = 50)
104     {
105         $emailHash = md5(strtolower(trim($this->email)));
106         return '//www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
107     }
108 }