Skip to content
This repository has been archived by the owner on Feb 2, 2022. It is now read-only.

update code to be compatible with keycloak 16 #13

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,26 @@
*/

package org.keycloak.experimental.magic;
import java.util.HashMap;
import org.keycloak.email.freemarker.beans.ProfileBean;

import java.util.Map;
import java.util.Collections;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
import org.keycloak.common.util.KeycloakUriBuilder;
import org.keycloak.email.EmailException;
import org.keycloak.email.freemarker.FreeMarkerEmailTemplateProvider;
import org.keycloak.email.EmailSenderProvider;
import org.keycloak.email.EmailTemplateProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.theme.FreeMarkerUtil;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
Expand All @@ -40,39 +45,63 @@ public class MagicLinkFormAuthenticator extends AbstractUsernameFormAuthenticato
@Override
public void action(AuthenticationFlowContext context) {
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
String email = formData.getFirst("email");

UserModel user = context.getSession().users().getUserByEmail(email, context.getRealm());
if (user == null) {
// Register user
user = context.getSession().users().addUser(context.getRealm(), email);
user.setEnabled(true);
user.setEmail(email);

// Uncomment the following line to require user to update profile on first login
// user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
}

String key = KeycloakModelUtils.generateId();
context.getAuthenticationSession().setAuthNote("email-key", key);

String link = KeycloakUriBuilder.fromUri(context.getRefreshExecutionUrl()).queryParam("key", key).build().toString();
String body = "<a href=\"" + link + "\">Click to login</a>";
try {
context.getSession().getProvider(EmailSenderProvider.class).send(context.getRealm().getSmtpConfig(), user, "Login link", null, body);
} catch (EmailException e) {
e.printStackTrace();
}

context.setUser(user);
context.challenge(context.form().createForm("view-email.ftl"));
String email = formData.getFirst("email").trim();
System.out.println(email);
System.out.println(context.getRealm().getName());
String realmName = context.getRealm().getName() ;

// Uncomment this block if you want to filter //
// the keycloack access to a specific email domaine //

/*if (
(!email.endsWith("@gruion.com") && realmName.equals("gruion.com"))
){
context.challenge(context.form().createForm("view-error-domain.ftl"));
return;
}else{*/
UserModel user = context.getSession().users().getUserByEmail(email, context.getRealm());
if (user == null) {
// Register user
user = context.getSession().users().addUser(context.getRealm(), email);
user.setEnabled(true);
user.setEmail(email);

// Uncomment the following line to require user to update profile on first login
// user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
}

String key = KeycloakModelUtils.generateId();
context.getAuthenticationSession().setAuthNote("email-key", key);

String link = KeycloakUriBuilder.fromUri(context.getRefreshExecutionUrl()).queryParam("key", key).build().toString();
try {

Map<String, Object> attributes = new HashMap<>();
attributes.put("realmName", realmName);
attributes.put("link", link);
FreeMarkerEmailTemplateProvider emailTemplateProvider = new FreeMarkerEmailTemplateProvider(context.getSession(), new FreeMarkerUtil());
emailTemplateProvider.setRealm(context.getRealm());
emailTemplateProvider.setUser(user);
String subject = "Login to " + realmName;
emailTemplateProvider.send(subject,Collections.emptyList(), "email-magic-link.ftl", attributes);

} catch (Exception e) {
context.challenge(context.form().createForm("view-error.ftl"));
e.printStackTrace();
return;
}

context.setUser(user);
context.challenge(context.form().createForm("view-email.ftl"));

//}
}

@Override
public void authenticate(AuthenticationFlowContext context) {
String sessionKey = context.getAuthenticationSession().getAuthNote("email-key");
if (sessionKey != null) {
String requestKey = context.getHttpRequest().getUri().getQueryParameters().getFirst("key");
String requestKey = context.getUriInfo().getQueryParameters().getFirst("key");
if (requestKey != null) {
if (requestKey.equals(sessionKey)) {
context.success();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
TitleEmail=Welcome to {0}
FooterEmail=<div style="font-family:'Helvetica Neue',Arial,sans-serif;font-size:14px;line-height:20px;text-align:left;">Best regards,<br><br> Magic Link<br><a href="https://github.com/stianst/keycloak-containers-demo" style="color:#2F67F6">code source </a></div>
LogoEmail=https://www.keycloak.org/resources/favicon.ico
Loading