summaryrefslogtreecommitdiff
path: root/public/app/controllers/Auth.php
blob: d7b0c3b06fb28eb0f56efbbab9d2daab5d9a8074 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<?php
namespace app\controllers;

use Registry;
use Render;

// user classes and models
use app\extends\Classroom_user;
use app\extends\Classroom_manager;
use app\models\admin\User_model;

use app\extends\Send_mail;
use app\extends\Mail_jet;


/** class Auth
 * 
 * handles user's Authentication and Authorizarion
 * 
 */
class Auth {

    /** login
     * 
     * checks visitor's credentials;
     * if valid, authenticates user
     * 
     */
    public static function login()
    {
        $req = Registry::get('REQUEST');

        // get the record of the target user
        $record = User_model::checkUser($req->POST['email']);
       
        // if no user exists, return false
        if ($record === false)     return false;
        
        // user is valid; check user password
        // create a user object
        $user = (new Classroom_user())
            ->setID($record['id'])
            ->setUserName($record['email'])
            ->setName($record['first_name'] .' '. $record['last_name'])
            ->setPassword($record['password'])
            ->setEnabled($record['active']);

        // let user manager to validate user credentials
        $userManager = new Classroom_manager();
        
        if ($userManager->isPasswordValid($user, $req->POST['password'])) {

            // get user's security attributes
            $attributes = User_Model::getUser($record['id']);
            $user
                ->setRoles(json_decode($attributes['Roles_json']))
                ->setPrivileges(
                    array_merge(
                        json_decode($attributes['RootPrivileges_json']),
                        self::merge_lists_array(
                            json_decode($attributes['SubPrivileges_json'])
                        )
                    )
                );
            
            // regeneration session ID (prevent session fixation)
            session_regenerate_id();
            // set cookie for connected user
            setcookie(
                'cluser',
                'connected;'. $user->getName(),
                time()+60*60*8,     // 8 hours
                '/'
            );

    
            // login OK, set Token in session
            $userManager->createUserToken($user);
            return true;
    
        } else {
            return false;
        }
    }


    /**
     * merges an array of lists to one list
     */
    private static function merge_lists_array( $list )
    {
        $current = [];
        foreach($list as $sublist) {
            $current = array_merge($current, $sublist);
        }
        return $current;
    }


    /** activate
     * resolves a call like: /account/activate?ticket=ca42d68cfba5fbbafeacc010b8e3a551
     */
    public static function activate()
    {
        $req = Registry::get('REQUEST');

        // get the record of the target user
        $check = User_model::activate($req->GET['ticket']);

        if ($check == true) {
            Render::view('/error/general', [
                'title' => ACCOUNT_ACTIVATED_TITLE,
                 'message' => ACCOUNT_ACTIVATED_MESSAGE
            ]);

        } else  {
            Render::view('/error/general', [
                'title' => NOT_VALID_ACTIVATION_TITLE,
                 'message' => NOT_VALID_ACTIVATION_MESSAGE
            ]);
        }

    }

    /** register
     * 
     * Method for new user registration
     * 
     */
    public static function register()
    {
        $userManager = new Classroom_manager();
        $req = Registry::get('REQUEST');

        // create a salted password hash
        $password = $userManager->cryptPassword($req->POST['password']);

        // echo $password; print_r($req->POST); die(); // OK!
        
        $user = (new Classroom_user())
            ->setUserName($req->POST['email'])
            ->setName($req->POST['name'] .' '. $req->POST['surname'])
            ->setPassword($password)
            ->setRoles([ READER ])      // Role: authorized reader
            ->setPrivileges([]);        // none privilege until acount confirmation

        // create user record
        $activation_code = User_model::registerUser($req->POST, $password);

        // TODO:
        // handle error on user registration
        // ...
        //
        // if ($activatopn_code[] == -1) {
        //     return [
        //         'success' => false,
        //         'message' => REGISTRATION_USER_EXISTS
        //     ];
        // }

        $send_mail = Send_mail::send_activation_code([
            'email' => $req->POST['email'],
            'name' => $req->POST['name'] .' '. $req->POST['surname'],
            'code' => $activation_code['activation']
        ]);

        // Send replies
        if ($send_mail) {
            return [
                'success' => true,
                'message' => REGISTRATION_SUCCESS
            ];

        } else {
            return [
                'success' => false,
                'message' => 'error on sending email'
            ];
        }  

    }


    public static function is_connected()
    {
        $manager = new Classroom_manager();
        if ($manager->hasUserToken()) {

            echo 'user is connected';
            $token = $manager->getUserToken();
            $user = $token->getUser();

            return $user;

        } else {
            echo 'user is not connected';
            return false;
        }
    }



    public static function logout()
    {
        $userManager = new Classroom_manager();
        $userManager->logout();

        // regeneration session ID (prevent session fixation)
        session_regenerate_id();

        // remove user-conected cookie
        if (isset($_COOKIE['cluser'])) {
            unset($_COOKIE['cluser']); 
            setcookie('cluser', '', -1, '/'); 
            return true;
        } else {
            return false;
        }
    }



    /** hasPermition( PERMIT )
     * 
     * checks if the user owns the specified permition
     * to access the source
     * 
     */
    public static function hasPermition($permit = [])
    {
        if ($permit == [])    return true;
    }


    /** isAuthenticated()
     * 
     * chechs if the user's roles and permitions
     * satisfy the specified requirements 
     * to access the source
     * 
     * @param $requirements (array of rules-array)
     * 
     * example:
     * [
     *    [
     *       role => ['editor','designer']
     *       permition => ['10', '12', '18']
     *    ],
     *    [
     *       role => ['admin' , 'developερ']
     *    ],
     *    [
     *       permition => [ 3 ]
     *    ]
     * ]
     * 
     * defines (and parses to) a requirements rule of:
     * [
     *    user should be editor or designer
     *    and have permition 10 or 12 or 18
     * ]
     * OR
     * [
     *    user should be an administratoe or developer
     * ]
     * OR
     * [
     *    user should have permition #3
     * ]
     *
     * 
     */
    public static function isAuthorized($requirements)
    {
        $authorized = false;
        foreach($requirements as $required) {
            if ( (self::isGranted($required['role'] ?? []))
            && (self::hasPermition($required['permition'] ?? [])) ) {
                $authorized = true;
            }
        }
        return $authorized;
    }




    public static function forgot_pass()
    {
    }



    public static function validate_otp()
    {
    }


    /** allowRoles
     * 
     * method filters access for certain roles
     * if user is not grented acces, a forbiden message is sent and app ends._
     * otherwise the method returns true (app will continue)
     * 
     * @param $allowed (array) : array of allowed roles
     * @return true or die();
     */
    public static function allowRoles($allowed)
    {
        $manager = new Classroom_manager();
        if ($manager->isGranted($allowed)) {    // if valid, return true (continue)
            return true;

        } else {    // no user, no access; die._
            Render::view('error/general', [
                'title' => 'Forbidden',
                'message' => 'Access is forbidden'
            ]);
            die();
            return false;       // this line will never run
        }
    }


    
}


// NOTE:
// check: https://netcorecloud.com/tutorials/send-an-email-via-gmail-smtp-server-using-php/