Completed
Push — master ( 492857...2250ba )
by Sherif
02:53
created

UserRepository::editProfile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 1
eloc 5
nc 1
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
     * 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
        \Core::users()->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 = \Core::users()->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 = \Core::users()->find($user_id);
60
            $user->groups()->detach();
61
            $user->groups()->attach($group_ids);
62
        });
63
64
        return \Core::users()->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 = \Core::users()->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 registration request.
104
     * 
105
     * @param  array $credentials
106
     * @return string
107
     */
108
    public function register($credentials)
109
    {
110
        $user = \Core::users()->model->create($credentials);
111
        $this->assignGroups($user->id, \Core::groups()->model->where('name', 'User')->select('id')->lists('id')->toArray());
112
113
        return ['token' => \JWTAuth::fromUser($user)];
114
    }
115
116
    /**
117
     * Logout the user.
118
     * 
119
     * @return boolean
120
     */
121
    public function logout()
122
    {
123
        return \JWTAuth::invalidate(\JWTAuth::getToken());
124
    }
125
126
    /**
127
     * Block the user.
128
     *
129
     * @param  integer $user_id
130
     * @return object
131
     */
132
    public function block($user_id)
133
    {
134
        if ( ! $user = \Core::users()->find($user_id)) 
135
        {
136
            \ErrorHandler::notFound('user');
137
        }
138
        if ( ! $this->hasGroup('Admin'))
139
        {
140
            \ErrorHandler::noPermissions();
141
        }
142
        else if (\JWTAuth::parseToken()->authenticate()->id == $user_id)
143
        {
144
            \ErrorHandler::noPermissions();
145
        }
146
        else if ($user->groups->lists('name')->search('Admin', true) !== false) 
147
        {
148
            \ErrorHandler::noPermissions();
149
        }
150
151
        $user->blocked = 1;
152
        $user->save();
153
        
154
        return $user;
155
    }
156
157
    /**
158
     * Unblock the user.
159
     *
160
     * @param  integer $user_id
161
     * @return object
162
     */
163
    public function unblock($user_id)
164
    {
165
        if ( ! $this->hasGroup('Admin'))
166
        {
167
            \ErrorHandler::noPermissions();
168
        }
169
170
        $user          = \Core::users()->find($user_id);
171
        $user->blocked = 0;
172
        $user->save();
173
174
        return $user;
175
    }
176
177
    /**
178
     * Send a reset link to the given user.
179
     *
180
     * @param  string  $url
181
     * @param  string  $email
182
     * @return void
183
     */
184
    public function sendReset($email, $url)
185
    {
186
        view()->composer('auth.emails.password', function($view) use ($url) {
187
            $view->with(['url' => $url]);
188
        });
189
190
        $response = \Password::sendResetLink($email, function (\Illuminate\Mail\Message $message) {
191
            $message->subject('Your Password Reset Link');
192
        });
193
194
        switch ($response) 
195
        {
196
            case \Password::INVALID_USER:
197
                \ErrorHandler::notFound('email');
198
        }
199
    }
200
201
    /**
202
     * Reset the given user's password.
203
     *
204
     * @param  array  $credentials
205
     * @return integer
206
     */
207
    public function resetPassword($credentials)
208
    {
209
        $token    = false;
210
        $response = \Password::reset($credentials, function ($user, $password) use (&$token) {
211
            $user->password = bcrypt($password);
212
            $user->save();
213
214
            $token = \JWTAuth::fromUser($user);
215
        });
216
217
218
        switch ($response) {
219
            case \Password::PASSWORD_RESET:
220
                return $token;
221
                
222
            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...
223
                \ErrorHandler::invalidResetToken('token');
224
225
            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...
226
                \ErrorHandler::invalidResetPassword('email');
227
228
            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...
229
                \ErrorHandler::notFound('user');
230
231
            default:
232
                \ErrorHandler::generalError();
233
        }
234
    }
235
}
236