Skip to content

Commit 325711c

Browse files
4.8.17 user validation (#11)
* Added user validation * Added user validation only in action page * Added logs * Removed setting user to context before validation * Added logs * Added validation in sendOtp method and comparing the user objects in session against retrieved user model * Updated code * Removed unnecessary log statement * Updated error message * Updated error message --------- Co-authored-by: Sharath Prasad <sharaths.kashyap@gmail.com>
1 parent a0af164 commit 325711c

File tree

2 files changed

+25
-16
lines changed

2 files changed

+25
-16
lines changed

keycloak/sms-provider/src/main/java/org/sunbird/keycloak/login/PasswordAndOtpAuthenticator.java

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public void authenticate(AuthenticationFlowContext context) {
8383

8484
// Store the secret key as an authentication session note
8585
context.getAuthenticationSession().setAuthNote(Constants.SECRET_KEY, secretKey);
86-
86+
8787
LoginFormsProvider formsProvider = context.form();
8888
formsProvider.setAttribute(Constants.SECRET_KEY, secretKey);
8989
context.challenge(formsProvider.createForm(Constants.LOGIN_PAGE));
@@ -204,6 +204,11 @@ private void goErrorPage(AuthenticationFlowContext context, String message) {
204204
Response tempDisabledRes = formsProvider.setError(errMsg).createForm(Constants.LOGIN_PAGE);
205205
context.failureChallenge(AuthenticationFlowError.USER_TEMPORARILY_DISABLED, tempDisabledRes);
206206
break;
207+
case Errors.DIFFERENT_USER_AUTHENTICATED:
208+
errMsg = "Authentication Error! Please enter your credentials again.";
209+
Response diffUsersFoundRes = formsProvider.setError(errMsg).createForm(Constants.LOGIN_PAGE);
210+
context.failureChallenge(AuthenticationFlowError.USER_CONFLICT, diffUsersFoundRes);
211+
break;
207212
case Errors.EMAIL_IN_USE:
208213
case Errors.USERNAME_IN_USE:
209214
default:
@@ -286,17 +291,31 @@ private void sendOtp(AuthenticationFlowContext context, String redirectUri) {
286291
return;
287292
}
288293

289-
context.setUser(user);
294+
if (context.getUser() != null) {
295+
// Let's compare both the user's are same ?
296+
if (!user.getId().equalsIgnoreCase(context.getUser().getId())) {
297+
logger.error(String.format(
298+
"Received different user details for saved session. Saved userId: %s, New userId: %s. Returning error...",
299+
context.getUser().getId(), user.getId()));
300+
context.getEvent().getEvent().setError(Errors.DIFFERENT_USER_AUTHENTICATED);
301+
goErrorPage(context, "Authentication Error! Please enter your credentials again.");
302+
return;
303+
}
304+
}
290305

291306
// Generate Random Digit
292307
Map<String, String> attributes = generateOTP(context);
293308

294-
// Put the data into session, to be compared
295-
context.getAuthenticationSession().setAuthNote(Constants.ATTEMPTED_EMAIL_OR_MOBILE_NUMBER, emailOrMobile);
296-
context.getAuthenticationSession().setAuthNote(Details.REDIRECT_URI, redirectUri);
297-
298309
// Send the key into the User Mobile Phone
299310
if (sendOtpByEmailOrSms(context, emailOrMobile, attributes.get(Constants.SESSION_OTP_CODE))) {
311+
//SMS is sent successfully, let's save the details in session and return the necessary page.
312+
context.getAuthenticationSession().setAuthNote(Constants.SESSION_OTP_CODE, attributes.get(Constants.SESSION_OTP_CODE));
313+
context.getAuthenticationSession().setAuthNote(Constants.SESSION_OTP_EXPIRE_TIME, attributes.get(KeycloakSmsAuthenticatorConstants.CONF_PRP_SMS_CODE_TTL));
314+
context.getAuthenticationSession().setAuthNote(Constants.ATTEMPTED_EMAIL_OR_MOBILE_NUMBER, emailOrMobile);
315+
context.getAuthenticationSession().setAuthNote(Details.REDIRECT_URI, redirectUri);
316+
317+
logger.info("Saving user details in session with userId: " + user.getId());
318+
context.setUser(user);
300319
goPage(context, Constants.PAGE_INPUT_OTP, StringUtils.EMPTY, attributes);
301320
} else {
302321
goErrorPage(context, "Failed to send out SMS. Please contact Administrator.");
@@ -422,7 +441,6 @@ private Map<String, String> generateOTP(AuthenticationFlowContext context) {
422441
String code = KeycloakSmsAuthenticatorUtil.getSmsCode(nrOfDigits);
423442

424443
Long expireTime = (new Date()).getTime() + (ttl * 1000);
425-
storeSMSCode(context, code, expireTime);
426444
Map<String, String> attributes = new HashMap<String, String>();
427445
attributes.put(KeycloakSmsAuthenticatorConstants.CONF_PRP_SMS_CODE_TTL, String.valueOf(expireTime));
428446
attributes.put(Constants.SESSION_OTP_CODE, code);
@@ -479,21 +497,13 @@ private String isEmailOrMobileNumber(String emailOrMobile) {
479497
return StringUtils.EMPTY;
480498
}
481499

482-
private void storeSMSCode(AuthenticationFlowContext context, String code, Long expiringAt) {
483-
context.getAuthenticationSession().setAuthNote(Constants.SESSION_OTP_CODE, code);
484-
context.getAuthenticationSession().setAuthNote(Constants.SESSION_OTP_EXPIRE_TIME, String.valueOf(expiringAt));
485-
}
486-
487500
protected CODE_STATUS validateCode(AuthenticationFlowContext context) {
488501
CODE_STATUS result = CODE_STATUS.INVALID;
489502

490503
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
491504
String enteredCode = formData.getFirst(KeycloakSmsAuthenticatorConstants.ANSW_SMS_CODE);
492505

493506
String storedCode = context.getAuthenticationSession().getAuthNote(Constants.SESSION_OTP_CODE);
494-
logger.info("Form Data");
495-
logger.info("Form Data");
496-
logger.info(String.format("Entered Code: %s, Stored Code %s",enteredCode, storedCode));
497507
if (storedCode != null && enteredCode != null) {
498508
result = storedCode.equalsIgnoreCase(enteredCode) ? CODE_STATUS.VALID : CODE_STATUS.INVALID;
499509
}

keycloak/sms-provider/src/main/java/org/sunbird/keycloak/utils/SunbirdModelUtils.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ public static UserModel getUserByNameEmailOrPhone(AuthenticationFlowContext cont
3535
String username) {
3636
String numberRegex = "\\d+";
3737
KeycloakSession session = context.getSession();
38-
logger.info("SunbirdModelUtils@getUser " + username);
3938
if (username.matches(numberRegex)) {
4039
List<UserModel> userModels = session.users().searchForUserByUserAttribute(
4140
KeycloakSmsAuthenticatorConstants.ATTR_MOBILE, username, context.getRealm());

0 commit comments

Comments
 (0)