Completed
Push — master ( b79faa...aa40d3 )
by Sherif
14:14
created

UserRepository::refreshtoken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
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
     * Check if the logged in user or the given user 
19
     * has the given permissions on the given model.
20
     * 
21
     * @param  string  $nameOfPermission
22
     * @param  string  $model            
23
     * @param  boolean $user
24
     * @return boolean
25
     */
26
    public function can($nameOfPermission, $model, $user = false )
27
    {       
28
        $user        = $user ?: \JWTAuth::parseToken()->authenticate();
29
        $permissions = [];
30
        $this->find($user->id, ['groups.permissions'])->groups->lists('permissions')->each(function ($permission) use (&$permissions, $model){
31
            $permissions = array_merge($permissions, $permission->where('model', $model)->lists('name')->toArray()); 
32
        });
33
        
34
        return in_array($nameOfPermission, $permissions);
35
    }
36
37
    /**
38
     * Check if the logged in user has the given group.
39
     * 
40
     * @param  string  $groupName
41
     * @return boolean
42
     */
43
    public function hasGroup($groupName)
44
    {
45
        $groups = $this->find(\JWTAuth::parseToken()->authenticate()->id)->groups;
46
        return $groups->lists('name')->search($groupName, true) === false ? false : true;
47
    }
48
49
    /**
50
     * Assign the given group ids to the given user.
51
     * 
52
     * @param  integer $user_id    
53
     * @param  array   $group_ids
54
     * @return object
55
     */
56 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...
57
    {
58
        \DB::transaction(function () use ($user_id, $group_ids) {
59
            $user = $this->find($user_id);
60
            $user->groups()->detach();
61
            $user->groups()->attach($group_ids);
62
        });
63
64
        return $this->find($user_id);
65
    }
66
67
    /**
68
     * Handle a login request to the application.
69
     * 
70
     * @param  array   $credentials    
71
     * @param  boolean $adminLogin
72
     * @return string
73
     */
74
    public function login($credentials, $adminLogin = false)
75
    {
76
        if ( ! $user = $this->first(['email' => $credentials['email']])) 
77
        {
78
            \ErrorHandler::loginFailed();
79
        }
80
        else if ($adminLogin && $user->groups->lists('name')->search('Admin', true) === false) 
81
        {
82
            \ErrorHandler::loginFailed();
83
        }
84
        else if ( ! $adminLogin && $user->groups->lists('name')->search('Admin', true) !== false) 
85
        {
86
            \ErrorHandler::loginFailed();
87
        }
88
        else if ($user->blocked)
89
        {
90
            \ErrorHandler::userIsBlocked();
91
        }
92
        else if ($token = \JWTAuth::attempt($credentials))
93
        {
94
            return ['token' => $token];
95
        }
96
        else
97
        {
98
            \ErrorHandler::loginFailed();
99
        }
100
    }
101
102
    /**
103
     * Handle a social login request of the none admin to the application.
104
     * 
105
     * @param  array   $credentials
106
     * @return string
107
     */
108
    public function loginSocial($credentials)
109
    {
110
        $access_token = $credentials['auth_code'] ? \Socialite::driver($credentials['type'])->getAccessToken($credentials['auth_code']) : $credentials['access_token'];   
111
        $user         = \Socialite::driver($credentials['type'])->userFromToken($access_token);
112
113
        if ( ! $user->email)
114
        {
115
            \ErrorHandler::noSocialEmail();
116
        }
117
118
        if ( ! $registeredUser = $this->model->where('email', $user->email)->first()) 
119
        {
120
            $data = ['email' => $user->email, 'password' => ''];
121
            return $this->register($data);
122
        }
123
        else
124
        {
125
            return $this->login(['email' => $registeredUser->email, 'password' => ''], false);
126
        }
127
    }
128
    
129
    /**
130
     * Handle a registration request.
131
     * 
132
     * @param  array $credentials
133
     * @return string
134
     */
135
    public function register($credentials)
136
    {
137
        return ['token' => \JWTAuth::fromUser($this->model->create($credentials))];
138
    }
139
140
    /**
141
     * Logout the user.
142
     * 
143
     * @return boolean
144
     */
145
    public function logout()
146
    {
147
        return \JWTAuth::invalidate(\JWTAuth::getToken());
148
    }
149
150
    /**
151
     * Block the user.
152
     *
153
     * @param  integer $user_id
154
     * @return object
155
     */
156
    public function block($user_id)
157
    {
158
        if ( ! $user = $this->find($user_id)) 
159
        {
160
            \ErrorHandler::notFound('user');
161
        }
162
        if ( ! $this->hasGroup('Admin'))
163
        {
164
            \ErrorHandler::noPermissions();
165
        }
166
        else if (\JWTAuth::parseToken()->authenticate()->id == $user_id)
167
        {
168
            \ErrorHandler::noPermissions();
169
        }
170
        else if ($user->groups->lists('name')->search('Admin', true) !== false) 
171
        {
172
            \ErrorHandler::noPermissions();
173
        }
174
175
        $user->blocked = 1;
176
        $user->save();
177
        
178
        return $user;
179
    }
180
181
    /**
182
     * Unblock the user.
183
     *
184
     * @param  integer $user_id
185
     * @return object
186
     */
187
    public function unblock($user_id)
188
    {
189
        if ( ! $this->hasGroup('Admin'))
190
        {
191
            \ErrorHandler::noPermissions();
192
        }
193
194
        $user          = $this->find($user_id);
195
        $user->blocked = 0;
196
        $user->save();
197
198
        return $user;
199
    }
200
201
    /**
202
     * Send a reset link to the given user.
203
     *
204
     * @param  string  $url
205
     * @param  string  $email
206
     * @return void
207
     */
208
    public function sendReset($email, $url)
209
    {
210
        view()->composer('auth.emails.password', function($view) use ($url) {
211
            $view->with(['url' => $url]);
212
        });
213
214
        $response = \Password::sendResetLink($email, function (\Illuminate\Mail\Message $message) {
215
            $message->subject('Your Password Reset Link');
216
        });
217
218
        switch ($response) 
219
        {
220
            case \Password::INVALID_USER:
221
                \ErrorHandler::notFound('email');
222
        }
223
    }
224
225
    /**
226
     * Reset the given user's password.
227
     *
228
     * @param  array  $credentials
229
     * @return integer
230
     */
231
    public function resetPassword($credentials)
232
    {
233
        $token    = false;
234
        $response = \Password::reset($credentials, function ($user, $password) use (&$token) {
235
            $user->password = bcrypt($password);
236
            $user->save();
237
238
            $token = \JWTAuth::fromUser($user);
239
        });
240
241
242
        switch ($response) {
243
            case \Password::PASSWORD_RESET:
244
                return $token;
245
                
246
            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...
247
                \ErrorHandler::invalidResetToken('token');
248
249
            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...
250
                \ErrorHandler::invalidResetPassword('email');
251
252
            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...
253
                \ErrorHandler::notFound('user');
254
255
            default:
256
                \ErrorHandler::generalError();
257
        }
258
    }
259
260
    /**
261
     * Refresh the expired login token.
262
     *
263
     * @return string
264
     */
265
    public function refreshtoken()
266
    {
267
        $token = \JWTAuth::parseToken()->refresh();
268
269
        return ['token' => $token];
270
    }
271
}
272