use of org.keycloak.events.EventBuilder in project keycloak by keycloak.
the class DeleteAccount method processAction.
@Override
public void processAction(RequiredActionContext context) {
KeycloakSession session = context.getSession();
EventBuilder eventBuilder = context.getEvent();
KeycloakContext keycloakContext = session.getContext();
RealmModel realm = keycloakContext.getRealm();
UserModel user = keycloakContext.getAuthenticationSession().getAuthenticatedUser();
try {
if (!clientHasDeleteAccountRole(context)) {
throw new ForbiddenException();
}
boolean removed = new UserManager(session).removeUser(realm, user);
if (removed) {
eventBuilder.event(EventType.DELETE_ACCOUNT).client(keycloakContext.getClient()).user(user).detail(Details.USERNAME, user.getUsername()).success();
cleanSession(context, RequiredActionContext.KcActionStatus.SUCCESS);
context.challenge(context.form().setAttribute("messageHeader", "").setInfo("userDeletedSuccessfully").createForm("info.ftl"));
} else {
eventBuilder.event(EventType.DELETE_ACCOUNT).client(keycloakContext.getClient()).user(user).detail(Details.USERNAME, user.getUsername()).error("User could not be deleted");
cleanSession(context, RequiredActionContext.KcActionStatus.ERROR);
context.failure();
}
} catch (ForbiddenException forbidden) {
logger.error("account client does not have the required roles for user deletion");
eventBuilder.event(EventType.DELETE_ACCOUNT_ERROR).client(keycloakContext.getClient()).user(keycloakContext.getAuthenticationSession().getAuthenticatedUser()).detail(Details.REASON, "does not have the required roles for user deletion").error(Errors.USER_DELETE_ERROR);
// deletingAccountForbidden
context.challenge(context.form().setAttribute(TRIGGERED_FROM_AIA, isCurrentActionTriggeredFromAIA(context)).setError(Messages.DELETE_ACCOUNT_LACK_PRIVILEDGES).createForm("delete-account-confirm.ftl"));
} catch (Exception exception) {
logger.error("unexpected error happened during account deletion", exception);
eventBuilder.event(EventType.DELETE_ACCOUNT_ERROR).client(keycloakContext.getClient()).user(keycloakContext.getAuthenticationSession().getAuthenticatedUser()).detail(Details.REASON, exception.getMessage()).error(Errors.USER_DELETE_ERROR);
context.challenge(context.form().setError(Messages.DELETE_ACCOUNT_ERROR).createForm("delete-account-confirm.ftl"));
}
}
use of org.keycloak.events.EventBuilder in project keycloak by keycloak.
the class UpdatePassword method processAction.
@Override
public void processAction(RequiredActionContext context) {
EventBuilder event = context.getEvent();
AuthenticationSessionModel authSession = context.getAuthenticationSession();
RealmModel realm = context.getRealm();
UserModel user = context.getUser();
KeycloakSession session = context.getSession();
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
event.event(EventType.UPDATE_PASSWORD);
String passwordNew = formData.getFirst("password-new");
String passwordConfirm = formData.getFirst("password-confirm");
EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR).client(authSession.getClient()).user(authSession.getAuthenticatedUser());
if (Validation.isBlank(passwordNew)) {
Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).addError(new FormMessage(Validation.FIELD_PASSWORD, Messages.MISSING_PASSWORD)).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
context.challenge(challenge);
errorEvent.error(Errors.PASSWORD_MISSING);
return;
} else if (!passwordNew.equals(passwordConfirm)) {
Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).addError(new FormMessage(Validation.FIELD_PASSWORD_CONFIRM, Messages.NOTMATCH_PASSWORD)).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
context.challenge(challenge);
errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
return;
}
if (getId().equals(authSession.getClientNote(Constants.KC_ACTION_EXECUTING)) && "on".equals(formData.getFirst("logout-sessions"))) {
session.sessions().getUserSessionsStream(realm, user).filter(s -> !Objects.equals(s.getId(), authSession.getParentSession().getId())).collect(// collect to avoid concurrent modification as backchannelLogout removes the user sessions.
Collectors.toList()).forEach(s -> AuthenticationManager.backchannelLogout(session, realm, s, session.getContext().getUri(), context.getConnection(), context.getHttpRequest().getHttpHeaders(), true));
}
try {
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew, false));
context.success();
} catch (ModelException me) {
errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).setError(me.getMessage(), me.getParameters()).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
context.challenge(challenge);
return;
} catch (Exception ape) {
errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
Response challenge = context.form().setAttribute("username", authSession.getAuthenticatedUser().getUsername()).setError(ape.getMessage()).createResponse(UserModel.RequiredAction.UPDATE_PASSWORD);
context.challenge(challenge);
return;
}
}
use of org.keycloak.events.EventBuilder in project keycloak by keycloak.
the class IdpEmailVerificationAuthenticator method sendVerifyEmail.
private void sendVerifyEmail(KeycloakSession session, AuthenticationFlowContext context, UserModel existingUser, BrokeredIdentityContext brokerContext) throws UriBuilderException, IllegalArgumentException {
RealmModel realm = session.getContext().getRealm();
UriInfo uriInfo = session.getContext().getUri();
AuthenticationSessionModel authSession = context.getAuthenticationSession();
int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(IdpVerifyAccountLinkActionToken.TOKEN_TYPE);
int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;
EventBuilder event = context.getEvent().clone().event(EventType.SEND_IDENTITY_PROVIDER_LINK).user(existingUser).detail(Details.USERNAME, existingUser.getUsername()).detail(Details.EMAIL, existingUser.getEmail()).detail(Details.CODE_ID, authSession.getParentSession().getId()).removeDetail(Details.AUTH_METHOD).removeDetail(Details.AUTH_TYPE);
String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
IdpVerifyAccountLinkActionToken token = new IdpVerifyAccountLinkActionToken(existingUser.getId(), existingUser.getEmail(), absoluteExpirationInSecs, authSessionEncodedId, brokerContext.getUsername(), brokerContext.getIdpConfig().getAlias(), authSession.getClient().getClientId());
UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo), authSession.getClient().getClientId(), authSession.getTabId());
String link = builder.queryParam(Constants.EXECUTION, context.getExecution().getId()).build(realm.getName()).toString();
long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);
try {
context.getSession().getProvider(EmailTemplateProvider.class).setRealm(realm).setAuthenticationSession(authSession).setUser(existingUser).setAttribute(EmailTemplateProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext).sendConfirmIdentityBrokerLink(link, expirationInMinutes);
event.success();
} catch (EmailException e) {
event.error(Errors.EMAIL_SEND_FAILED);
ServicesLogger.LOGGER.confirmBrokerEmailFailed(e);
Response challenge = context.form().setError(Messages.EMAIL_SENT_ERROR).createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
return;
}
showEmailSentPage(context, brokerContext);
}
use of org.keycloak.events.EventBuilder in project keycloak by keycloak.
the class ConsoleVerifyEmail method sendVerifyEmail.
private Response sendVerifyEmail(RequiredActionContext context) throws UriBuilderException, IllegalArgumentException {
KeycloakSession session = context.getSession();
UserModel user = context.getUser();
AuthenticationSessionModel authSession = context.getAuthenticationSession();
EventBuilder event = context.getEvent().clone().event(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, user.getEmail());
String code = SecretGenerator.getInstance().randomString(8);
authSession.setAuthNote(Constants.VERIFY_EMAIL_CODE, code);
RealmModel realm = session.getContext().getRealm();
Map<String, Object> attributes = new HashMap<>();
attributes.put("code", code);
try {
session.getProvider(EmailTemplateProvider.class).setAuthenticationSession(authSession).setRealm(realm).setUser(user).send("emailVerificationSubject", "email-verification-with-code.ftl", attributes);
event.success();
} catch (EmailException e) {
logger.error("Failed to send verification email", e);
event.error(Errors.EMAIL_SEND_FAILED);
}
return challenge(context).text(context.form().getMessage("console-verify-email", user.getEmail()));
}
use of org.keycloak.events.EventBuilder in project keycloak by keycloak.
the class ConsoleVerifyEmail method processAction.
@Override
public void processAction(RequiredActionContext context) {
EventBuilder event = context.getEvent().clone().event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, context.getUser().getEmail());
String code = context.getAuthenticationSession().getAuthNote(Constants.VERIFY_EMAIL_CODE);
if (code == null) {
requiredActionChallenge(context);
return;
}
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
String emailCode = formData.getFirst(EMAIL_CODE);
if (!code.equals(emailCode)) {
context.challenge(challenge(context).message(Messages.INVALID_CODE));
event.error(Errors.INVALID_CODE);
return;
}
event.success();
context.success();
}
Aggregations