logger.debug("Checking authentication for user {}", username);
logger.debug("userResponse: {}",
captchaCaptureFilter.getUserCaptchaResponse());
boolean captchaEnabled = isCaptchaEnabled();
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
throw new CapAuthenticationException(
"No Username and/or Password Provided.", captchaEnabled);
} else if (captchaEnabled
&& StringUtils.isBlank(captchaCaptureFilter
.getUserCaptchaResponse())) {
throw new CapAuthenticationException("Captcha Response is Empty",
captchaEnabled);
} else {
Map<String, String> policy = passwordService.getPasswordPolicy();
boolean captchaPassed = true;
boolean forceChangePwd = isForceChangePwd(username);
Integer wrongCount = getWrountCount(username);
logger.debug("wrongCount-{}: {}", username, wrongCount);
// 密碼連錯 PWD_ACCOUNT_LOCK 次 lock user
if (wrongCount >= Integer.parseInt(policy
.get(PwdPloicyKeys.PWD_ACCOUNT_LOCK.toString()
.toLowerCase()))) {
accessControlService.lockUserByUserId(username);
throw new CapAuthenticationException("User locked.",
captchaEnabled);
}
// 驗證 captcha
if (captchaEnabled) {
String cpatchaData = captchaCaptureFilter.getRequest()
.getParameter("captcha");
CapSecurityCaptcha captcha = CapAppContext
.getBean(CapCaptchaServlet.DEF_RENDERER);
captchaPassed = CaptchaStatus.SUCCESS.equals(captcha
.valid(cpatchaData));
logger.debug("Is captcha valid: " + captchaPassed);
} else {
captchaPassed = true;
}
if (captchaPassed) {
resetCaptchaFields();
CapUserDetails user;
try {
user = (CapUserDetails) userService
.loadUserByUsername(username);
} catch (Exception e) {
throw new CapAuthenticationException(e.getMessage(),
captchaEnabled, forceChangePwd);
}
boolean currentPwdVerified = verifyPassword(username,
authentication.getCredentials().toString(),
user.getPassword());
if (currentPwdVerified) {
setWrountCount(username, 0);
String authedPwd = checkStatus(user, username, password,
policy, captchaEnabled, forceChangePwd);
// 登入成功
setForceChangePwd(username, false);
// 檢核是否要提醒使用者變更密碼
notifyPasswordChange(username, captchaEnabled,
forceChangePwd);
accessControlService.login(username);
return new UsernamePasswordAuthenticationToken(user,
authedPwd, user.getAuthorities());
} else {
setWrountCount(username, getWrountCount(username) + 1);
// 連錯 N 次,enable captcha
if (wrongCount >= Integer.parseInt(policy
.get(PwdPloicyKeys.PWD_CAPTCHA_ENABLE.toString()
.toLowerCase()))) {
setCaptchaEnabled(true);
}
throw new CapAuthenticationException("Invalid Password.",
isCaptchaEnabled(), forceChangePwd);
}
} else {
logger.debug("Captcha is invalid!");
resetCaptchaFields();
throw new CapAuthenticationException("Invalid Captcha.",
captchaEnabled, forceChangePwd);
}
}
}