Completed
Push — master ( 7b165f...1aacae )
by Pavel
13s
created

User::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
namespace App\Model;
3
4
use Illuminate\Database\Eloquent\SoftDeletes;
5
use App\Common\Helper;
6
use App\Common\Auth;
7
8
/**
9
 * Class User
10
 *
11
 * @property integer        $id
12
 * @property string         $email
13
 * @property string         $full_name
14
 * @property string         $password
15
 * @property string         $password_reset_token
16
 * @property integer        $role_id
17
 * @property integer        $created_by
18
 * @property integer        $updated_by
19
 * @property \Carbon\Carbon $created_at
20
 * @property \Carbon\Carbon $updated_at
21
 * @property \Carbon\Carbon $deleted_at
22
 * @property integer        $status
23
 * @property-read Role      $role
24
 *
25
 * @package App\Model
26
 */
27
final class User extends BaseModel
28
{
29
    use SoftDeletes;
30
31
    const STATUS_BLOCKED     = 0;
32
    const STATUS_ACTIVE      = 1;
33
    const STATUS_WAIT        = 2;
34
35
    const ROLE_ADMIN         = 1;
36
    const ROLE_USER          = 2;
37
38
    const EXPIRE_RESET_TOKEN = 3600;
39
40
    protected $table = 'users';
41
42
    protected $fillable = [
43
        'full_name',
44
        'email',
45
        'role_id',
46
        'status'
47
    ];
48
49
    protected $hidden = [
50
        'password',
51
        'password_reset_token',
52
    ];
53
54
    public static $rules = [
55
        'create' => [
56
            'email'    => 'required|email',
57
            'role_id'  => 'required',
58
            'password' => 'required',
59
        ],
60
        'update' => [
61
            'email'   => 'required|email',
62
            'role_id' => 'required',
63
        ]
64
    ];
65
66
    /**
67
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
68
     */
69
    public function role()
70
    {
71
        return $this->hasOne('App\Model\Role', 'id', 'role_id');
72
    }
73
74
    /**
75
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
76
     */
77
    public function accessTokens()
78
    {
79
        return $this->hasMany('App\Model\AccessToken', 'user_id', 'id');
80
    }
81
82
    /**
83
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
84
     */
85
    public function refreshTokens()
86
    {
87
        return $this->hasMany('App\Model\RefreshToken', 'user_id', 'id');
88
    }
89
90
    /**
91
     * @param $query
92
     *
93
     * @return mixed
94
     */
95
    public function scopeCurrentUser($query)
96
    {
97
        $user = Auth::getUser();
98
99
        if ($user) {
100
            if ($user->role_id == self::ROLE_ADMIN) {
101
                return $query;
102
            }
103
104
            $query->where('id', $user->id);
105
        } else {
106
            $query->where('id', 0);
107
        }
108
109
        return $query;
110
    }
111
112
    /**
113
     * Create new User instance and save it
114
     *
115
     * @param $attributes
116
     * @param $password
117
     * @return User|null
118
     */
119
    public static function create($attributes, $password)
120
    {
121
        $user = new self($attributes);
122
        $user->setPassword($password);
123
        if (!$user->save()) {
124
            return null;
125
        }
126
127
        return $user;
128
    }
129
130
131
    /**
132
     * @param $email
133
     *
134
     * @return bool
135
     */
136
    public static function exist($email)
137
    {
138
        return self::where('email', $email)->count() > 0;
139
    }
140
141
    /**
142
     * @param string $email
143
     *
144
     * @return User|null
145
     */
146
    public static function findUserByEmail($email)
147
    {
148
        return self::where('email', $email)->where('status', self::STATUS_ACTIVE)->first();
149
    }
150
151
    /**
152
     * @param string $resetToken
153
     *
154
     * @return User|null
155
     */
156
    public static function findByPasswordResetToken($resetToken)
157
    {
158
        if (!self::isPasswordResetTokenValid($resetToken)) {
159
            return null;
160
        }
161
162
        return self::where('password_reset_token', $resetToken)->where('status', self::STATUS_ACTIVE)->first();
163
    }
164
165
    /**
166
     * @param string $token
167
     *
168
     * @return bool
169
     */
170
    public static function isPasswordResetTokenValid($token)
171
    {
172
        if (empty($token)) {
173
            return false;
174
        }
175
176
        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
177
        $expire    = self::EXPIRE_RESET_TOKEN;
178
        return $timestamp + $expire >= time();
179
    }
180
181
    /**
182
     * @void
183
     */
184
    public function generatePasswordResetToken()
185
    {
186
        $this->password_reset_token = Helper::generateRandomString().'_'.time();
187
    }
188
189
    /**
190
     * @void
191
     */
192
    public function removePasswordResetToken()
193
    {
194
        $this->password_reset_token = null;
195
    }
196
197
    /**
198
     * @param string $password
199
     */
200
    public function setPassword($password)
201
    {
202
        // we need to invalidate tokens when changing password
203
        AccessToken::where('user_id', $this->id)->delete();
204
        RefreshToken::where('user_id', $this->id)->delete();
205
206
        $this->password = password_hash($password, PASSWORD_DEFAULT, ['cost' => 13]);
207
    }
208
}
209