/var/www/hkosl.com/e-ims/file_manager/function_auth.php


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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php
require_once __DIR__.'/inc/Db.php';
require_once 
'function_login_block.php';

defined('HTML_EOL') or define('HTML_EOL''<br />');

/*
 * Usage:
*
* -authentication
* Sys_user::auth($userid, $pwd, $return_user);
* return true or false
*
* -change password
* Sys_user::changePassword($id, $orginal_password, $new_password, $confirm_password=null);
* return true or false
*
* -check the (SESSION) user is valid
* Sys_user::checkLogin();
* return true or false
*/

class Sys_user {

    
/*
     * Database USER Table defination
     */
    
const TBL_NAME             "sys_login";
    const 
FLD_ID            "loginid";
    const 
FLD_USER            "username";
    const 
FLD_LOGINNAME        "loginname";    
    const 
FLD_PASSWORD        "loginpw";
    const 
FLD_ROLE            "role";
    const 
FLD_CREATEDATE    "createdate";
    const 
FLD_MODIFYDATE    "lastupdate";
    const 
FLD_STATUS        "status";
    const 
STATUS_ALLOW        "1"// allow status=1 to login

    //settings
    
static $SHOW_WARNING     false;
    static 
$ENABLE_CALLBACK    true;

    
/*
     * To be called if authorization is OK
     */
    
protected static function authSuccessCallback($row){
        
//put some variables into SESSION
        
$_SESSION['loginname']    = $row{self::FLD_LOGINNAME};
        
$_SESSION['loginid']    = $row{self::FLD_ID};
        
$_SESSION['role']    = $row{self::FLD_ROLE};

        if(
$_POST['autologin'] == 1)
        {
            
//disabled cookie
                
            //$password_hash = md5($row{'cmsloginpw'}); // will result in a 32 characters hash
            //setcookie ($cookie_name, 'usr='.$row{'cmsloginname'}.'&hash='.$password_hash, time() + $cookie_time);
            //insert_login_log($usrid, true);
        
}
        
insert_login_log($row{self::FLD_USER}, true);

        
header("Location: index.php");
        exit;
    }

    
/*
     * To be called if authorization is Failed
     */
    
protected static function authFailCallback(){
        
//put a log into System_log table
        
global $login_error;
        
$login_error true;
        
insert_login_log($usridfalse);
        
die_if_login_block();
    }

    
/*
     * Customize procedure to check during authorization
     * return ture to allow this authorization
     */
    
protected static function whenAuth(){
        
//you can add some checking
        //return false to reject the authorization
        
return true;
    }

    
// --------------  DO NOT MODIFY BELOW --------------------------------------------

    /*
     * check the loginid has a valid status (usually run in every script)
     * $loginid - login ID to be checked ($_SESSION['loginname'] if empty)
     */
    
static function checkLogin($loginid=null){

        global 
$loggin;
        
        if(empty(
$loginid)){
            
$loginid $_SESSION['loginname'];
        }

        
$sql "SELECT * FROM ".self::TBL_NAME
                
." WHERE ".self::FLD_LOGINNAME " = :loginname "
                
." AND "self::FLD_STATUS." = :status ";
                
        
$sql_param = array(
            
':loginname' => $loginid,
            
':status' => self::STATUS_ALLOW,
        );

        
$sth Db::getDbh()->prepare($sql);
        
//echo $sth->getSQL( $sql_param ).HTML_EOL;
        
$sth->execute$sql_param );    
        if( 
$error $sth->getError($sql_param) ){
            
var_dump($error);
        }
            
        if(
$row $sth->fetch()){
            
$loggin 1;
            return 
true;
        }
        
$loggin false;
        return 
false;
    }

    
//user authenication
    
static function auth($userid$pwd, &$return_user=null){

        
$sql "SELECT * FROM ".self::TBL_NAME."
                WHERE "
.self::FLD_LOGINNAME." = :loginname
                        AND "
.self::FLD_PASSWORD." = :password
                        AND "
.self::FLD_STATUS." = :status ";
                
        
$sql_param = array(
            
':loginname' => $userid,
            
':password' => Password::hash($pwd),
            
':status' => self::STATUS_ALLOW,
        );

        
$sth Db::getDbh()->prepare($sql);
        
//echo $sth->getSQL( $sql_param ).HTML_EOL;
        
$sth->execute$sql_param );    
        if( 
$error $sth->getError($sql_param) ){
            
var_dump($error);
        }
            
        
$result=$sth->fetch();
            
        if( 
$result && $result[self::FLD_PASSWORD]==Password::hash($pwd) ){
            
//var_dump($result[self::FLD_PASSWORD], Password::hash($pwd), $result[self::FLD_PASSWORD]==Password::hash($pwd) ); exit;
            
$authenticated =  true;
        }else{
            if(
self::$SHOW_WARNING) { print "Login Failed <br/>";    }
            
$authenticated =  false;
        }
        
        if( 
$authenticated && !self::whenAuth() ){
            
$authenticated =  false;
        }

        if(
$authenticated){
            
$return_user $result;
            if(
self::$ENABLE_CALLBACK) { self::authSuccessCallback($return_user); }
        }else{
            if(
self::$SHOW_WARNING) { print "Login Failed <br/>"; }
            if(
self::$ENABLE_CALLBACK) { self::authFailCallback(); }
        }
        return 
$authenticated;
    }

    
//change user password
    
static function changePassword($id$orginal_password$new_password$confirm_password=null){
        
        
$sql "SELECT * FROM ".self::TBL_NAME." WHERE ".self::FLD_ID." = :id ";
                
        
$sql_param = array(
            
':id' => $id
        
);

        
$sth Db::getDbh()->prepare($sql);
        
//echo $sth->getSQL( $sql_param ).HTML_EOL;
        
$sth->execute$sql_param );    
        if( 
$error $sth->getError($sql_param) ){
            
var_dump($error);
        }
        
        if(!
$result $sth->fetch()){
            if(
self::$SHOW_WARNING) {
                print 
"User not found <br/>";
            }
            return 
false;            
        }
        
        if(
$confirm_password && $new_password==$confirm_password){
            if(
self::$SHOW_WARNING) { print "Confirm password is incorrect <br/>"; }
            return 
false;
        }
        if(
Password::hash($orginal_password)!=$result[self::FLD_PASSWORD]){
            if(
self::$SHOW_WARNING) { print "Original password is incorrect <br/>"; }
            return 
false;
        }
        
        if(
$result[self::FLD_ID]){
            
$sql "UPDATE ".self::TBL_NAME
            
." SET ".self::FLD_PASSWORD." = :password, "
                    
.self::FLD_MODIFYDATE." = :date "
            
." WHERE ".self::FLD_ID." = :id ";
                    
            
$sql_param = array(
                
':password' => Password::hash($new_password),
                
':date' => date("Y-m-d H:i:s"),
                
':id' => (int)$result[self::FLD_ID],
            );
    
            
$sth Db::getDbh()->prepare($sql);
            
//echo $sth->getSQL( $sql_param ).HTML_EOL;
            
$sth->execute$sql_param );    
            if( 
$error $sth->getError($sql_param) ){
                
var_dump($error);
                return 
false;
            }
            return 
true;        
        }
        return 
false;
    }
}

/*    
 * Usage:
*
* -hash
* Password::hash($_POST["cmsloginpw"]);
* return hashed password
*
* -strength test
* Password::strength($_REQUEST[$fld_password], $_REQUEST['username'], $msg);
* $msg: variable to store returned error messages
* return true OR false
*
* -include javascript fragment for Jquery validation
* Password::ajax_validate('cmsloginpw', 'ajax_passwordChecker.php', 'cmsloginname')
* $password: password to be validated
* $ajax_checker: validate script
* $loginname: optional username to be compared with the password
* return javascript string
*/
class Password{
    static 
$SALT1             "3ruthaQE";
    static 
$SALT2             "kaheSt6H";
    static 
$SALT3             "sA6wePej";
    static 
$SALT4             "Tha7unaT";    

    static function 
hash($str){
        
$len strlen($str);
        
$len_a = (int)($len/3);
        
$len_b = (int)($len/3);
        
//$len_c = $len - $a - $b;
        
$a substr($str0$len_a);
        
$b substr($str$len_a$len_b);
        
$c substr($str$len_a+$len_b);                
        
//var_dump(self::$SALT1.$c.self::$SALT2.$b.self::$SALT3.$a.self::$SALT4);
        
return hash('sha256'self::$SALT1.$c.self::$SALT2.$b.self::$SALT3.$a.self::$SALT4);
    }
    
    static function 
strength($password$username='', &$msg=''){
        
//ref: http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/
        //$pattern = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])(?=.*[\d]).{8,15}$/";
        //$t1 = preg_match($pattern, $password, $matches);
        
$result true;
        
        
$pattern "/^.{8,15}$/";
        if(!
preg_match($pattern$password$matches)){
            
$msg .= '<li>Must be 8-15 characters long</li>';    
            
$result false;
        }
        
$pattern "/(?=.*[a-z])/";
        if(!
preg_match($pattern$password$matches)){
            
$msg .= '<li>Include a lower case letter</li>';    
            
$result false;
        }
        
$pattern "/(?=.*[A-Z])/";
        if(!
preg_match($pattern$password$matches)){
            
$msg .= '<li>Include an upper case letter</li>';    
            
$result false;
        }
        
$pattern "/(?=.*[\d])/";
        if(!
preg_match($pattern$password$matches)){
            
$msg .= '<li>Include a number</li>';    
            
$result false;
        }
        
$pattern "/(?=.*[\W_])/";
        if(!
preg_match($pattern$password$matches)){
            
$msg .= '<li>Include a special character</li>';    
            
$result false;
        }
        if(
stripos($password$username)!==false){
            
$msg .= '<li>Password cannot contain the username</li>';    
            
$result false;            
        }
        if(
$msg){
            
$msg '<ul class="validerr">'.$msg.'</ul>';    
        }
    
        return 
$result;
    }    
    
    

    static function 
ajax_validate($id$ajaxChecker='ajax_passwordChecker.php'$usernameInput_id=''$required=false){
            
$s .='
<script>
$(document).ready(function(e) {
    $( "#'
.$id.'" ).rules( "add", {
        "required": '
.($required?'true':'false').',
        "minlength": 8,
        "maxlength": 15,
            messages: {
                 remote: "Invalid password format"
            },
        "remote": { 
            url: "'
.$ajaxChecker.'",
            type: "post",
            data:{
                allowEmpty: "'
.($required?'false':'true').'",
                fld: "'
.$id.'",
                username: function(){
                    return $("#'
.$usernameInput_id.'").val();
                }
            },
        }
    });
});
</script>'
;

        return 
$s;
    }    
    
    static function 
html_input($tag_attr$id$ajaxChecking=true$ajaxChecker='ajax_passwordChecker.php'$usernameInput_id=''){
        if(empty(
$id)){
            
$id=rand(1000,999999);
        }            
        
$s='<input type="text" '.$tag_attr.' id="'.$id.'" >';
        if(
$ajaxChecking){//change, blur, keyup
            
if($usernameInput_id){
                
$usernameInput ", #".$usernameInput_id;    
            }
            
$s .='<script>
                    $("#'
.$id.$usernameInput.'").on("change, blur, keyup", function(e){
                        $.getJSON( "'
.$ajaxChecker.'", {
                                password: $("#'
.$id.'").val(),
                                username: $("#'
.$usernameInput_id.'").val(),
                            },
                            function(data) {
                                if(data.strength){
                                    $("#'
.$id.'").removeClass("bad").addClass("ok");
                                }else{
                                    $("#'
.$id.'").removeClass("ok").addClass("bad");
                                }
                        });
                    });
                 </script>'
;
        }        
        return 
$s;
    }


}