ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm);
if (accessCode == null) {
event.error(Errors.INVALID_CODE);
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Unknown code, please login again through your application.");
}
ClientSessionModel clientSession = accessCode.getClientSession();
String username = formData.getFirst("username");
ClientModel client = clientSession.getClient();
if (client == null) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Unknown login requester.");
}
if (!client.isEnabled()) {
return Flows.forwardToSecurityFailurePage(session, realm, uriInfo,
"Login requester not enabled.");
}
event.client(client.getClientId())
.detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
.detail(Details.RESPONSE_TYPE, "code")
.detail(Details.AUTH_METHOD, "form")
.detail(Details.USERNAME, username);
UserModel user = session.users().getUserByUsername(username, realm);
if (user == null && username.contains("@")) {
user = session.users().getUserByEmail(username, realm);
}
if (user == null) {
event.error(Errors.USER_NOT_FOUND);
} else {
UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false);
event.session(userSession);
TokenManager.attachClientSession(userSession, clientSession);
accessCode.setAction(ClientSessionModel.Action.RECOVER_PASSWORD);
try {
UriBuilder builder = Urls.loginPasswordResetBuilder(uriInfo.getBaseUri());
builder.queryParam("key", accessCode.getCode());
String link = builder.build(realm.getName()).toString();
long expiration = TimeUnit.SECONDS.toMinutes(realm.getAccessCodeLifespanUserAction());
this.session.getProvider(EmailProvider.class).setRealm(realm).setUser(user).sendPasswordReset(link, expiration);
event.user(user).detail(Details.EMAIL, user.getEmail()).detail(Details.CODE_ID, clientSession.getId()).success();
} catch (EmailException e) {
logger.error("Failed to send password reset email", e);
return Flows.forms(this.session, realm, client, uriInfo).setError("emailSendError")
.setClientSessionCode(accessCode.getCode())
.createErrorPage();