Completed
Push — master ( cd8f65...e1eb39 )
by Sherif
27:44
created

UserRepository::changePassword()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php namespace App\Modules\V1\Acl\Repositories;
2
3
use App\Modules\V1\Core\AbstractRepositories\AbstractRepository;
4
5
class UserRepository extends AbstractRepository
6
{
7
    /**
8
     * Return the model full namespace.
9
     * 
10
     * @return string
11
     */
12
    protected function getModel()
13
    {
14
        return 'App\Modules\V1\Acl\AclUser';
15
    }
16
17
    /**
18
     * Return the logged in user account.
19
     *
20
     * @param  array   $relations
21
     * @return boolean
22
     */
23
    public function account($relations = [])
24
    {
25
        $permissions = [];
26
        $user        = \Core::users()->find(\JWTAuth::parseToken()->authenticate()->id, $relations);
27
        foreach ($user->groups()->get() as $group)
28
        {
29
            $group->permissions->each(function ($permission) use (&$permissions){
30
                $permissions[$permission->model][$permission->id] = $permission->name;
31
            });
32
        }
33
        $user->permissions = $permissions;
34
35
       return $user;
36
    }
37
38
    /**
39
     * Check if the logged in user or the given user 
40
     * has the given permissions on the given model.
41
     * 
42
     * @param  string  $nameOfPermission
43
     * @param  string  $model            
44
     * @param  boolean $user
45
     * @return boolean
46
     */
47
    public function can($nameOfPermission, $model, $user = false )
48
    {      
49
        $user        = $user ?: \JWTAuth::parseToken()->authenticate();
50
        $permissions = [];
51
52
        if ( ! $user = $this->find($user->id, ['groups.permissions'])) 
53
        {
54
            \ErrorHandler::tokenExpired();
55
        }
56
57
        $user->groups->lists('permissions')->each(function ($permission) use (&$permissions, $model){
58
            $permissions = array_merge($permissions, $permission->where('model', $model)->lists('name')->toArray()); 
59
        });
60
        
61
        return in_array($nameOfPermission, $permissions);
62
    }
63
64
    /**
65
     * Check if the logged in user has the given group.
66
     * 
67
     * @param  string  $groupName
68
     * @return boolean
69
     */
70
    public function hasGroup($groupName)
71
    {
72
        $groups = $this->find(\JWTAuth::parseToken()->authenticate()->id)->groups;
73
        return $groups->lists('name')->search($groupName, true) === false ? false : true;
74
    }
75
76
    /**
77
     * Assign the given group ids to the given user.
78
     * 
79
     * @param  integer $user_id    
80
     * @param  array   $group_ids
81
     * @return object
82
     */
83 View Code Duplication
    public function assignGroups($user_id, $group_ids)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
    {
85
        \DB::transaction(function () use ($user_id, $group_ids) {
86
            $user = $this->find($user_id);
87
            $user->groups()->detach();
88
            $user->groups()->attach($group_ids);
89
        });
90
91
        return $this->find($user_id);
92
    }
93
94
    /**
95
     * Handle a login request to the application.
96
     * 
97
     * @param  array   $credentials    
98
     * @param  boolean $adminLogin
99
     * @return array
100
     */
101
    public function login($credentials, $adminLogin = false)
102
    {
103
        if ( ! $user = $this->first(['email' => $credentials['email']])) 
104
        {
105
            \ErrorHandler::loginFailed();
106
        }
107
        else if ($adminLogin && $user->groups->lists('name')->search('Admin', true) === false) 
108
        {
109
            \ErrorHandler::loginFailed();
110
        }
111
        else if ( ! $adminLogin && $user->groups->lists('name')->search('Admin', true) !== false) 
112
        {
113
            \ErrorHandler::loginFailed();
114
        }
115
        else if ($user->blocked)
116
        {
117
            \ErrorHandler::userIsBlocked();
118
        }
119
        else if ($token = \JWTAuth::attempt($credentials))
120
        {
121
            return ['token' => $token];
122
        }
123
        else
124
        {
125
            \ErrorHandler::loginFailed();
126
        }
127
    }
128
129
    /**
130
     * Handle a social login request of the none admin to the application.
131
     * 
132
     * @param  array   $credentials
133
     * @return array
134
     */
135
    public function loginSocial($credentials)
136
    {
137
        $access_token = $credentials['auth_code'] ? \Socialite::driver($credentials['type'])->getAccessToken($credentials['auth_code']) : $credentials['access_token'];   
138
        $user         = \Socialite::driver($credentials['type'])->userFromToken($access_token);
139
140
        if ( ! $user->email)
141
        {
142
            \ErrorHandler::noSocialEmail();
143
        }
144
145
        if ( ! $registeredUser = $this->model->where('email', $user->email)->first()) 
146
        {
147
            $data = ['email' => $user->email, 'password' => ''];
148
            return $this->register($data);
149
        }
150
        else
151
        {
152
            if ( ! \Auth::attempt(['email' => $registeredUser->email, 'password' => '']))
153
            {
154
                \ErrorHandler::userAlreadyRegistered();
155
            }
156
            return $this->login(['email' => $registeredUser->email, 'password' => ''], false);
157
        }
158
    }
159
    
160
    /**
161
     * Handle a registration request.
162
     * 
163
     * @param  array $credentials
164
     * @return array
165
     */
166
    public function register($credentials)
167
    {
168
        return ['token' => \JWTAuth::fromUser($this->model->create($credentials))];
169
    }
170
171
    /**
172
     * Logout the user.
173
     * 
174
     * @return boolean
175
     */
176
    public function logout()
177
    {
178
        return \JWTAuth::invalidate(\JWTAuth::getToken());
179
    }
180
181
    /**
182
     * Block the user.
183
     *
184
     * @param  integer $user_id
185
     * @return object
186
     */
187
    public function block($user_id)
188
    {
189
        if ( ! $user = $this->find($user_id)) 
190
        {
191
            \ErrorHandler::notFound('user');
192
        }
193
        if ( ! $this->hasGroup('Admin'))
194
        {
195
            \ErrorHandler::noPermissions();
196
        }
197
        else if (\JWTAuth::parseToken()->authenticate()->id == $user_id)
198
        {
199
            \ErrorHandler::noPermissions();
200
        }
201
        else if ($user->groups->lists('name')->search('Admin', true) !== false) 
202
        {
203
            \ErrorHandler::noPermissions();
204
        }
205
206
        $user->blocked = 1;
207
        $user->save();
208
        
209
        return $user;
210
    }
211
212
    /**
213
     * Unblock the user.
214
     *
215
     * @param  integer $user_id
216
     * @return object
217
     */
218
    public function unblock($user_id)
219
    {
220
        if ( ! $this->hasGroup('Admin'))
221
        {
222
            \ErrorHandler::noPermissions();
223
        }
224
225
        $user          = $this->find($user_id);
226
        $user->blocked = 0;
227
        $user->save();
228
229
        return $user;
230
    }
231
232
    /**
233
     * Send a reset link to the given user.
234
     *
235
     * @param  string  $url
236
     * @param  string  $email
237
     * @return void
238
     */
239
    public function sendReset($email, $url)
240
    {
241
        view()->composer('auth.emails.password', function($view) use ($url) {
242
            $view->with(['url' => $url]);
243
        });
244
245
        $response = \Password::sendResetLink($email, function (\Illuminate\Mail\Message $message) {
246
            $message->subject('Your Password Reset Link');
247
        });
248
249
        switch ($response) 
250
        {
251
            case \Password::INVALID_USER:
252
                \ErrorHandler::notFound('email');
253
        }
254
    }
255
256
    /**
257
     * Reset the given user's password.
258
     *
259
     * @param  array  $credentials
260
     * @return array
261
     */
262
    public function resetPassword($credentials)
263
    {
264
        $token    = false;
265
        $response = \Password::reset($credentials, function ($user, $password) use (&$token) {
266
            $user->password = bcrypt($password);
267
            $user->save();
268
269
            $token = \JWTAuth::fromUser($user);
270
        });
271
272
        switch ($response) {
273
            case \Password::PASSWORD_RESET:
274
                return ['token' => $token];
275
                
276
            case \Password::INVALID_TOKEN:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
277
                \ErrorHandler::invalidResetToken('token');
278
279
            case \Password::INVALID_PASSWORD:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
280
                \ErrorHandler::invalidResetPassword('email');
281
282
            case \Password::INVALID_USER:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
283
                \ErrorHandler::notFound('user');
284
285
            default:
286
                \ErrorHandler::generalError();
287
        }
288
    }
289
290
    /**
291
     * Change the logged in user password.
292
     *
293
     * @param  array  $credentials
294
     * @return void
295
     */
296
    public function changePassword($credentials)
297
    {
298
        $user = $this->find(\JWTAuth::parseToken()->authenticate()->id, $relations);
0 ignored issues
show
Bug introduced by
The variable $relations does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
299
        if ( ! \Hash::check($credentials['old_password'], $user->password)) 
300
        {
301
            \ErrorHandler::invalidOldPassword();
302
        }
303
304
        $user->password = $credentials['password'];
305
        $user->save();
306
    }
307
308
    /**
309
     * Refresh the expired login token.
310
     *
311
     * @return array
312
     */
313
    public function refreshtoken()
314
    {
315
        $token = \JWTAuth::parseToken()->refresh();
316
317
        return ['token' => $token];
318
    }
319
}
320