Statistics
| Branch: | Revision:

m2u-upass-core / src / my / com / upass / spassword / PasswordController.java @ 0:02300db8682b

History | View | Annotate | Download (22.3 KB)

1
/**
2
 * 
3
 */
4
package my.com.upass.spassword;
5

    
6
import java.io.UnsupportedEncodingException;
7
import java.security.MessageDigest;
8
import java.security.NoSuchAlgorithmException;
9
import java.util.Date;
10
import java.util.Calendar;
11
import java.util.Map;
12
import java.util.Properties;
13
import java.util.StringTokenizer;
14
import java.util.regex.Matcher;
15
import java.util.regex.Pattern;
16

    
17
import org.apache.log4j.Logger;
18
import my.com.upass.Config;
19
import my.com.upass.ConfigBean;
20
import my.com.upass.Constants;
21
import my.com.upass.pojo.UserBean;
22

    
23

    
24
/**
25
 * @author Administrator
26
 *
27
 */
28
public class PasswordController {
29

    
30
        private static  final Logger logger = Logger.getLogger (PasswordController.class);
31
        static int _MAX_ERROR = 3;
32
        static int _MAX_PASSWD_REUSED = 3;
33
        static int _EXPIRY_DAY = 0;
34
        static int _MIN_LENGTH = 0;
35
        static int _COMPLEXITY = 0;
36
        static String _PASSWORD_PATTERN = "(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).{8,}";
37
        static String _USERNAME_PATTERN = "^[a-zA-Z0-9_-]{6,}$";
38
        static String _PASSWORD_ACCEPT_PATTERN = "^[a-zA-Z0-9!@#$%^&*()_+<>?]{0,}$";
39
        static int _USER_DORMANT_PERIOD = 0;
40
        
41
        private UserBean userBean; 
42
        private Map<Integer, ConfigBean> configurationsMap;
43
        
44
        public PasswordController(UserBean userBean,
45
                        Map<Integer, ConfigBean> configurationsMap)
46
                        throws Exception
47
        {
48
                this.userBean = userBean;
49
                this.configurationsMap = configurationsMap;
50
        }
51
        
52
        public ConfigBean getConfigBean()
53
        {
54
                return configurationsMap.get (this.userBean.getApplicationId());
55
        }
56
                
57
        public PasswordController(){
58
                getSystemProperties();
59
        }
60
        
61
        public PasswordController(UserBean userBean){
62
                this.userBean = userBean;
63
                getSystemProperties();
64
        }
65
        
66
        public PasswordController(UserBean userBean, boolean loadConfig){
67
                this.userBean = userBean;
68
                if(loadConfig){getSystemProperties ();}
69
        }
70
        
71
        public void setObject(UserBean userBean) {
72
                this.userBean = userBean;
73
        }
74
        
75
        public UserBean getUpdatedObject() {
76
                return (UserBean)userBean;
77
        }
78
        
79
        private void getSystemProperties() {
80
                Config cfg = Config.getInstance();
81
                Properties cfgData = cfg.getConfig();
82
                try {
83
                        _MAX_ERROR = Integer.parseInt(cfgData.get("PASSWORD_MAX_ERROR").toString());
84
                        _MAX_PASSWD_REUSED = Integer.parseInt(cfgData.get("PASSWORD_GENERAION").toString());
85
                        _EXPIRY_DAY = Integer.parseInt(cfgData.get("PASSWORD_EXPIRY_DAY").toString());
86
                        _MIN_LENGTH = Integer.parseInt(cfgData.get("PASSWORD_MIN_LENGTH").toString());
87
                        _COMPLEXITY = Integer.parseInt(cfgData.get("PASSWORD_COMPLEXITY").toString());
88
                        _PASSWORD_PATTERN = cfgData.get("PASSWORD_PATTERN").toString();
89
                        _USERNAME_PATTERN = cfgData.get("USERNAME_PATTERN").toString();
90
                        _PASSWORD_ACCEPT_PATTERN = cfgData.get("PASSWORD_ACCEPT_PATTERN").toString();
91
                } catch (Exception e) {
92
                        logger.error("ERR: Property entry not found..");
93
                }
94
        }
95
        
96
        
97
        ///////////////////////////////////////////////////////////////////////
98
        // Public Verify User Alias  
99
        // 20120627 - Return ERR_INVALID_USERALIAS if the given name is not matching the pattern
100
        ///////////////////////////////////////////////////////////////////////
101
        public int VerifyUserAlias(String userAlias) {
102
                logger.info("userAlias="+userAlias+" Regular Expression="+_USERNAME_PATTERN);
103
                if (patternValidator(userAlias, getConfigBean().getUserNameValidPattern())) {
104
                        return Constants.ERR_SUCCESS;
105
                }
106
                
107
                return Constants.ERR_INVALID_USERALIAS;
108
        }
109
        ///////////////////////////////////////////////////////////////////////
110
        // Public Verify Password  
111
        // 20081113 - Return passwd expired means the passwd is valid but expired
112
        ///////////////////////////////////////////////////////////////////////
113
        public int VerifyPassword(String password) {
114
                
115
                Date ts = new Date();
116
                userBean.setPdateLastUsed(ts);         
117
                userBean.setPuseCount( userBean.getPuseCount() + 1 );
118
                
119
                if (userBean.getPstate() != Constants.PASSWD_STATUS_ENABLE) {
120
                        userBean.setPerrorCount( userBean.getPerrorCount() + 1 ); 
121
                        return Constants.ERR_INVALID_STATE; 
122
                }
123
                
124
                if (userBean.getPerrorCount() > getConfigBean().getPasswordMaxTryError()-1) {
125
                        userBean.setPerrorCount( userBean.getPerrorCount() + 1 ); 
126
                        return Constants.ERR_EXCEED_MAX_TRIES; 
127
                }
128
                
129
                if (userBean.getPdateFirstUsed() == null) {
130
                        userBean.setPdateFirstUsed(ts); 
131
                }
132

    
133
                if ( comparePassword(password) ) {
134
                        //valid password
135
                        userBean.setPerrorCount(0); //reset error count
136
                        
137
                        //modified on July 03, 2012 by Tan Lee Yong
138
                        //the require changed that password expire date must take effective as the _EXPIRY_DAY changed.
139
                        //therefore, the validation of this date change to dynamic, rather than static
140
                        if ( ( userBean.getPexpiredStatus() == Constants.PASSWD_WILL_EXPIRE) && 
141
                                        (userBean.getPdateExpired() != null) ){
142
                                
143
                                        Date lastPasswordChangeDate = userBean.getPdateExpired();
144
                                        Calendar expiryDate = Calendar.getInstance();
145
                                        expiryDate.setTime(lastPasswordChangeDate);
146
                                        expiryDate.add(Calendar.DATE, +getConfigBean().getPasswordExpiry());
147
                                        Date passwordExpireDate = expiryDate.getTime();
148
                                        
149
                                        int notifAlert = getConfigBean().getPasswordExpiry() - getConfigBean().getNotifAlert();
150
                                        Calendar expiryDateNotification = Calendar.getInstance();
151
                                        expiryDateNotification.setTime(lastPasswordChangeDate);
152
                                        expiryDateNotification.add(Calendar.DATE, +notifAlert);
153
                                        
154
                                        Date expiryDateNotification1 = expiryDateNotification.getTime();
155
                                        
156
                                        if (ts.after(expiryDateNotification1) && ts.before(passwordExpireDate) ){
157
                                                
158
                                                return Constants.ERR_PASSWD_EXPIRED_NOTIFICATION;
159
                                                
160
                                        }
161
                                
162
                                        //if the password expire date is a pass date compare to today's date
163
                                        //return password expired status
164
                                        if (passwordExpireDate.before(ts)) { 
165
                                                return Constants.ERR_PASSWD_EXPIRED;
166
                                        }
167
                        }
168
                        
169
                        return Constants.ERR_SUCCESS;
170
                        
171
                } else {
172
                        // invalid password
173
                        userBean.setPerrorCount( userBean.getPerrorCount() + 1 ); 
174
                        
175
                        if (userBean.getPerrorCount () == getConfigBean().getPasswordMaxTryError())
176
                        {
177
                                return Constants.ERR_EXCEED_MAX_TRIES;
178
                        }
179
                        
180
                        return Constants.ERR_INVALID_CREDENTIAL; 
181
                }
182

    
183
        }
184
        
185
        public int checkRegeneratePassword() {
186
                
187
                //added checking for password change interval.
188
                if (userBean.getPdateCreated() != null){
189
                        
190
                        Date date= new Date();
191
                        Date lastPasswordGenerationDate = userBean.getPdateCreated();
192
                        Calendar generationDate = Calendar.getInstance();
193
                        generationDate.setTime(lastPasswordGenerationDate);
194
                        generationDate.add(Calendar.MINUTE, +getConfigBean().getChangePasswordInterval());
195
                        
196
                        Date passRegenDate = generationDate.getTime();
197
                        
198
                        if (date.before(passRegenDate)) { 
199
                                return Constants.ERR_PASSWD_CHANGE_INTERVAL;
200
                        }        
201
                        
202
                }
203
        
204
                return Constants.ERR_SUCCESS;
205
        }
206

    
207
        private boolean comparePassword(String password) {
208
                String passwordCipherText = SHA256(userBean.getUserAlias(), password);
209
                return (passwordCipherText.equals(userBean.getPcipherText()));
210
        }
211
        
212
        public int GeneratePassword(String password, boolean enableHistCheck) {
213
                
214
                if ( !ValidatePasswordPattern(password) ) {
215
                        return Constants.ERR_PASSWD_WEAK;
216
                }
217
                return generatePassword (password, enableHistCheck);
218
        }
219
        ///////////////////////////////////////////////////////////////////////
220
        // Public Generate Password  
221
        ///////////////////////////////////////////////////////////////////////
222
        int generatePassword(String password, boolean enableHistCheck) {
223
                
224
//                if ( !ValidatePassword(password) ) {
225
//                        return Constants.ERR_PASSWD_WEAK;
226
//                }
227
                
228
                Date ts = new Date();
229
                String cipherText = SHA256(userBean.getUserAlias(), password);
230
                String token = null;
231
                StringBuffer sb = new StringBuffer(cipherText);
232
                
233
                if (enableHistCheck) {
234
                        // check password history here
235
                        String histList = userBean.getPhistoryList();
236
                                        
237
                        if (histList != null) {
238
                                StringTokenizer stz = new StringTokenizer(histList, ":");
239
                                while (stz.hasMoreTokens()){
240
                                        token = stz.nextToken();
241
                                        if ( cipherText.equals(token) ) {
242
                                                return Constants.ERR_REUSED_PASSWD;
243
                                        }
244
                                }
245
                                sb.append(":");
246
                                sb.append(histList);
247
                        }
248
                
249
                        // update the history list
250
                        int max_reused = (getConfigBean().getPasswordMaxReuse());
251
                        String theUpdatedHistList = sb.toString();
252
                        StringBuffer nsb = new StringBuffer();
253
                        StringTokenizer newstz = new StringTokenizer(theUpdatedHistList, ":");
254
                        if (newstz.countTokens() > max_reused) {
255
                                nsb.append(newstz.nextToken());
256
                                for (int i=0; i<max_reused-1; i++ ) {
257
                                        nsb.append(":");
258
                                        nsb.append(newstz.nextToken());
259
                                }
260
                                theUpdatedHistList = nsb.toString();
261
                        }
262
                        userBean.setPhistoryList( theUpdatedHistList );
263
                } //end enableHistCheck
264
                
265
                userBean.setPstate(Constants.PASSWD_STATUS_ENABLE);
266
                userBean.setPcipherText(cipherText);
267
                userBean.setPdateCreated(ts);
268
                userBean.setPerrorCount(0);
269
                
270
                
271
                if ( getConfigBean().getPasswordExpiry() > 0 ) {
272
                        userBean.setPexpiredStatus(Constants.PASSWD_WILL_EXPIRE);
273
                        Calendar expiryDate = Calendar.getInstance();
274
                        //modified on July 03, 2012 by Tan Lee Yong
275
                        //the require changed that password expire date must take effective as the _EXPIRY_DAY changed.
276
                        //therefore, the validation of this date change to dynamic, rather than static
277
//                        expiryDate.add(Calendar.DATE, +_EXPIRY_DAY);
278
//                        expiryDate.add(Calendar.DATE);
279
                        
280
                        userBean.setPdateExpired(expiryDate.getTime());
281
                } else {
282
                        userBean.setPexpiredStatus(Constants.PASSWD_NEVER_EXPIRE);
283
                        userBean.setPdateExpired(null);
284
                }
285
                
286
                return Constants.ERR_SUCCESS;
287
                
288
        }
289
        
290
        ///////////////////////////////////////////////////////////////////////
291
        //  validate Password - Length, complexity  
292
        ///////////////////////////////////////////////////////////////////////
293
        public boolean ValidatePasswordPattern (String password)
294
        {
295
                //if acceptable characters are defined, then check does password contain unacceptable characters
296
                if (getConfigBean().getPasswordAcceptPattern()!=null || !getConfigBean().getPasswordAcceptPattern().isEmpty()) {
297
                        if (!patternValidator(password, getConfigBean().getPasswordAcceptPattern())) {
298
                                return false;
299
                        } 
300
                        return true;
301
                }
302
                
303
                return patternValidator(password, getConfigBean().getPasswordValidPattern());
304
        }
305
        
306
        public boolean ValidatePassword(String password){
307
                boolean l1, l2, l3, l4;
308
                l1 = l2 = l3 = l4 = true;
309
                                
310
                if (password.length() < getConfigBean().getPasswordMinLength()) {
311
                        logger.info("Password length check failed");
312
                        return false;
313
                }
314
                
315
                logger.info("Password _COMPLEXITY " + getConfigBean().getPasswordComplexity());
316
                
317
                System.out.println("Password Complexity:"+ getConfigBean().getPasswordComplexity());
318
                
319
                if (getConfigBean().getPasswordComplexity() != 0) {
320
                        
321
                        l1 = l2 = l3 = l4 = false;
322
                        String validLowerChars = "abcdefghijklmnopqrstuvwxyz";
323
                        String validUpperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
324
                        String validNumber = "0123456789";
325
                        String validSpecialChar = "!@#$%^&*()_+<>?";
326
                        
327
                        for (int i=0;i<password.length();i++) {
328
                          char c = password.charAt(i);
329
                          
330
                          if (!l1 && validLowerChars.indexOf(c) != -1){
331
                                  //logger.info("lower.. Character[" + c + "] detected at position " + i);
332
                                  l1 = true;
333
                                 }
334
                          if (!l2 && validUpperChars.indexOf(c) != -1){
335
                                  //logger.info("upper.. Character[" + c + "] detected at position " + i);
336
                                  l2 = true;
337
                                  }
338
                          if (!l3 && validNumber.indexOf(c) != -1){
339
                                  //logger.info("digit.. Character[" + c + "] detected at position " + i);
340
                                  l3 = true;
341
                                  }
342
                          if (!l4 && validSpecialChar.indexOf(c) != -1){
343
                                  //logger.info("special Character[" + c + "] detected at position " + i);
344
                                  l4 = true;
345
                                  }
346
                        }
347
                }
348
                
349
                return ( l1 && l2 && l3 && l4);
350
        }
351
        
352
        ///////////////////////////////////////////////////////////////////////
353
        // Generate 64-byte SHA-256
354
        ///////////////////////////////////////////////////////////////////////
355
        public String SHA256(String userAlias, String password) {
356
                try {
357
                        String strID = userAlias;
358
                        MessageDigest md;
359
                        md = MessageDigest.getInstance("SHA-256");
360
                        byte[] sha256hash = new byte[64];
361
                        md.update(password.getBytes("iso-8859-1"), 0, password.length());
362
                        md.update(strID.getBytes("iso-8859-1"), 0, strID.length());
363
                        sha256hash = md.digest();
364
                        return convertToHex(sha256hash);
365
                } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
366
                  catch (UnsupportedEncodingException e) { e.printStackTrace(); }
367
                        return new String("******");        
368
          }        
369
        ///////////////////////////////////////////////////////////////////////
370
        // Generate 40-byte SHA-1
371
        ///////////////////////////////////////////////////////////////////////
372
        public String SHA1(String userAlias, String password) {
373
                try {
374
                        String strID = userAlias;
375
                        MessageDigest md;
376
                        md = MessageDigest.getInstance("SHA-1");
377
                        byte[] sha1hash = new byte[40];
378
                        md.update(password.getBytes("iso-8859-1"), 0, password.length());
379
                        md.update(strID.getBytes("iso-8859-1"), 0, strID.length());
380
                        sha1hash = md.digest();
381
                        return convertToHex(sha1hash);
382
                } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
383
                  catch (UnsupportedEncodingException e) { e.printStackTrace(); }
384
                        return new String("******");        
385
            }
386
        
387
        
388
        ///////////////////////////////////////////////////////////////////////
389
        // Convert byte to hex
390
        ///////////////////////////////////////////////////////////////////////
391
        private String convertToHex(byte[] data) {
392
                StringBuffer buf = new StringBuffer();
393
                for (int i = 0; i < data.length; i++) {
394
                        int halfbyte = (data[i] >>> 4) & 0x0F;
395
                        int two_halfs = 0;
396
                        do {
397
                                    if ((0 <= halfbyte) && (halfbyte <= 9))
398
                                        buf.append((char) ('0' + halfbyte));
399
                                    else
400
                                            buf.append((char) ('A' + (halfbyte - 10)));
401
                                            halfbyte = data[i] & 0x0F;
402
                        } while(two_halfs++ < 1);
403
                }
404
                return buf.toString();
405
            }
406
        
407
        /**
408
         * <pre>
409
         * Validate dataToValidate with regular expression the defined in the patternStr.
410
         * Sample Regular Expression for different needs:-
411
         *
412
         ======================
413
         Username Pattern
414
         ======================
415
        "^[a-zA-Z0-9_-]{6,16}$"
416
                        - allow a-z, A-Z, 0-9, dash and underscore characters, min length 6, max length 16
417
                        
418
        "^[a-zA-Z0-9_-]{6,}$"
419
                        - allow a-z, A-Z, 0-9, dash and underscore characters, min length 6
420
         *</pre>
421
         <pre>
422
         ======================
423
         Password Pattern
424
         ======================
425
          "(?=.*\\d).*" 
426
                          - must contains at least one digit from 0-9
427
          "(?=.*\\w).*" 
428
                          - must contains at lease one character from 0-9, a-z or A-Z
429
          "(?=.*[A-Z]).*"         
430
                          - must contains at lease one UPPER case characters
431
          "(?=.*[a-z]).*"                 
432
                          - must contains at lease one lower case characters
433
          "(?=.*\\d)(?=.*[a-zA-Z]).*" 
434
                          - must contains at least one digit from 0-9 and at lease one character from 0-9, a-z or A-Z
435
          "(?=.*[!@#$%^&*()_+<>?]).*"  
436
                          - must contains one special symbols in the list "!@#$%^&*()_+<>?"
437
          "(?=.*\\d)(?=.*[A-Z]).*"                                  
438
                          - must contains one digit from 0-9 and one UPPER case characters
439
          "(?=.*\\d)(?=.*[a-z]).*"                                  
440
                          - must contains one digit from 0-9 and one lower case characters
441
          "(?=.*\\d)(?=.*[a-zA-Z]).*"                                  
442
                          - must contains one digit from 0-9, one lower case characters and one UPPER case characters
443
          "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).*"                                  
444
                          - must contains one digit from 0-9, one lower case characters, one UPPER case characters and one special symbols in the list "!@#$%^&*()_+<>?"
445
          "(?=.*[a-z])(?=.*[A-Z]).{8,16}"                                  
446
                          - must contains one lower case characters and one UPPER case characters
447
          "(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).*"                                  
448
                          - must contains one lower case characters, one UPPER case characters and one special symbols in the list "!@#$%^&*()_+<>?"
449
        </pre>
450
        ========================================================================
451
        <pre>
452
          "(?=.*\\d).{8,}" 
453
                          - must contains at least one digit from 0-9 and length at least 8 characters
454
          "(?=.*\\w).{8,}" 
455
                          - must contains at lease one character from 0-9, a-z or A-Z and length at least 8 characters
456
          "(?=.*[A-Z]).{8,}"         
457
                          - must contains at lease one UPPER case characters and length at least 8 characters
458
          "(?=.*[a-z]).{8,}"                 
459
                          - must contains at lease one lower case characters and length at least 8 characters
460
          "(?=.*[!@#$%^&*()_+<>?]).{8,}"  
461
                          - must contains one special symbols in the list "!@#$%^&*()_+<>?" and length at least 8 characters
462
          "(?=.*\\d)(?=.*[A-Z]).{8,}"                                  
463
                          - must contains one digit from 0-9, one UPPER case characters and length at least 8 characters
464
          "(?=.*\\d)(?=.*[a-z]).{8,}"                                  
465
                          - must contains one digit from 0-9, one lower case characters and length at least 8 characters
466
          "(?=.*\\d)(?=.*[a-zA-Z]).{8,}"                                  
467
                          - must contains one digit from 0-9, one lower case characters, one UPPER case characters and length at least 8 characters
468
          "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).{8,}"                                  
469
                          - must contains one digit from 0-9, one lower case characters, one UPPER case characters, one special symbols in the list "!@#$%^&*()_+<>?" and length at least 8 characters
470
          "(?=.*[a-z])(?=.*[A-Z]).{8,16}"                                  
471
                          - must contains one lower case characters, one UPPER case characters and length at least 8 characters
472
          "(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).{8,}"                                  
473
                          - must contains one lower case characters, one UPPER case characters, one special symbols in the list "!@#$%^&*()_+<>?" and length at least 8 characters
474
        </pre>
475
        ========================================================================
476
        <pre>
477
          "(?=.*\\d).{8,16}" 
478
                          - must contains at least one digit from 0-9 and length at least 8 characters and maximum of 16
479
          "(?=.*\\w).{8,16}" 
480
                          - must contains at lease one character from 0-9, a-z or A-Z and length at least 8 characters and maximum of 16
481
          "(?=.*[A-Z]).{8,16}"         
482
                          - must contains at lease one UPPER case characters and length at least 8 characters and maximum of 16
483
          "(?=.*[a-z]).{8,16}"                 
484
                          - must contains at lease one lower case characters and length at least 8 characters and maximum of 16
485
          "(?=.*[!@#$%^&*()_+<>?]).{8,16}"  
486
                          - must contains one special symbols in the list "!@#$%^&*()_+<>?" and length at least 8 characters and maximum of 16
487
          "(?=.*\\d)(?=.*[A-Z]).{8,16}"                                  
488
                          - must contains one digit from 0-9, one UPPER case characters and length at least 8 characters and maximum of 16
489
          "(?=.*\\d)(?=.*[a-z]).{8,16}"                                  
490
                          - must contains one digit from 0-9, one lower case characters and length at least 8 characters and maximum of 16
491
          "(?=.*\\d)(?=.*[a-zA-Z]).{8,16}"                                  
492
                          - must contains one digit from 0-9, one lower case characters, one UPPER case characters and length at least 8 characters and maximum of 16
493
          "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).{8,16}"                                  
494
                          - must contains one digit from 0-9, one lower case characters, one UPPER case characters, one special symbols in the list "!@#$%^&*()_+<>?" and length at least 8 characters and maximum of 16
495
          "(?=.*[a-z])(?=.*[A-Z]).{8,16}"                                  
496
                          - must contains one lower case characters, one UPPER case characters and length at least 8 characters and maximum of 16
497
          "(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+<>?]).{8,16}"                                  
498
                          - must contains one lower case characters, one UPPER case characters, one special symbols in the list "!@#$%^&*()_+<>?" and length at least 8 characters and maximum of 16
499
        </pre>
500
        *<pre>
501
         ======================
502
         Email Pattern
503
         ======================
504
                "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
505
        </pre>
506
        <pre>
507
        ===========================
508
        Acceptable patter
509
        ===========================
510
        "^[a-zA-Z0-9!@#$%^&*()_+<>?]{0,}$"
511
                - Accept a-z, A-Z, 0-9 and !@#$%^&*()_+<>? characters
512
        "^[a-zA-Z0-9]{0,}$"
513
            - Accept a-z, A-Z and 0-9
514
        </pre>
515
    * 
516
   * @param dataToValidate Data for validation
517
   * @param patternStr The java regular expression pattern
518
   * @see http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
519
   * @return true valid password, false invalid password
520
   */
521
        public boolean patternValidator(final String dataToValidate, final String patternStr) {
522
                
523
                 Matcher matcher;
524
                 Pattern pattern = Pattern.compile(patternStr);
525
                 matcher = pattern.matcher(dataToValidate);
526
                 
527
                 boolean macth= matcher.matches();
528
                 
529
                 if (!macth) {
530
                         logger.error("ValidatePassword: Pattern not match! "+"Data="+dataToValidate+" Pattern to match="+patternStr);
531
                 }
532
                 
533
                 return macth;
534
        }
535
        
536
        /**
537
         * 
538
         * @return true if user is not active for N period of time; otherwise false
539
         */
540
        public boolean isUserDormant() 
541
        {
542
                //Root and Admin is exempted from dormant period
543
                if (userBean.getUserType() == Constants.UTYPE_STATE_ROOT || userBean.getUserType() == Constants.UTYPE_STATE_ADMIN) 
544
                {
545
                        logger.info("Admin Dormant Check");
546
                        return false;
547
                }
548

    
549
                Date lastUseDate = userBean.getPdateLastUsed();
550
                logger.info("User Dormant Check");
551
                
552
                int numberOfDayNotActive = getDiffDateInDays(lastUseDate,  new Date());
553
                if (numberOfDayNotActive> getConfigBean ().getUserDormantPeriod()) 
554
                {
555
                        logger.info("User Dormant Found");
556
                        return true;
557
                }
558
                return false;
559
        }
560
        
561
        /**
562
         * Will compare the given 2 time object and calculate the time difference in number of days.
563
         *
564
         * @param earlierDate The earlier date
565
         * @param laterDate The later date
566
         * @return The time different between two dates in number of days. 
567
         */
568
        public static int getDiffDateInDays(Date earlierDate, Date laterDate)
569
        {
570
                 Calendar calendar1 = Calendar.getInstance();
571
                 Calendar calendar2 = Calendar.getInstance();
572
                 calendar1.setTime(earlierDate);
573
                 calendar2.setTime(laterDate);
574
                 long milliseconds1 = calendar1.getTimeInMillis();
575
                 long milliseconds2 = calendar2.getTimeInMillis();
576
                 long diff = milliseconds2 - milliseconds1;
577
                 long diffDays = diff / 86400000; //(24 * 60 * 60 * 1000);
578

    
579

    
580
                 return (int)diffDays;
581
        }
582
        
583
        public static void main(String [] args)        {
584
                PasswordController pass = new PasswordController();
585
//                String cipherText1 = pass.SHA1("wakakaka", "aaaa0000");
586
                String cipherText256 = pass.SHA256("cust03", "aaaa1111");
587
                System.out.println(pass.patternValidator("aaaa7777","(?=.*\\w).{8,12}"));
588
//                System.out.println(cipherText1);
589
//                System.out.println("------------");
590
                System.out.println(cipherText256);
591
        }
592

    
593
}