Java Code Examples for org.keycloak.models.UserModel#getEmail()

The following examples show how to use org.keycloak.models.UserModel#getEmail() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DynamicIdpRedirectAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
protected String determineTargetIdpViaUserEmail(UserModel user, AuthenticationFlowContext context) {

        String email = user.getEmail();
        if (email == null) {
            return null;
        }

        String mappingString = getConfigValueOrDefault(context.getAuthenticatorConfig(), EMAIL_TO_IDP_MAPPING_CONFIG_PROPERTY, "", String::valueOf);
        String[] mappings = mappingString.split(";");
        for (String mapping : mappings) {
            String[] emailSuffixPatternToIdpId = mapping.split("/");
            String emailSuffixPattern = emailSuffixPatternToIdpId[0];
            String idpId = emailSuffixPatternToIdpId[1];

            if (email.matches(emailSuffixPattern)) {
                return idpId;
            }
        }

        return null;
    }
 
Example 2
Source File: CachedUser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public CachedUser(Long revision, RealmModel realm, UserModel user, int notBefore) {
    super(revision, user.getId());
    this.realm = realm.getId();
    this.username = user.getUsername();
    this.createdTimestamp = user.getCreatedTimestamp();
    this.email = user.getEmail();
    this.emailVerified = user.isEmailVerified();
    this.enabled = user.isEnabled();
    this.federationLink = user.getFederationLink();
    this.serviceAccountClientLink = user.getServiceAccountClientLink();
    this.notBefore = notBefore;
    this.requiredActions = new DefaultLazyLoader<>(UserModel::getRequiredActions, Collections::emptySet);
    this.attributes = new DefaultLazyLoader<>(userModel -> new MultivaluedHashMap<>(userModel.getAttributes()), MultivaluedHashMap::new);
    this.roleMappings = new DefaultLazyLoader<>(userModel -> userModel.getRoleMappings().stream().map(RoleModel::getId).collect(Collectors.toSet()), Collections::emptySet);
    this.groups = new DefaultLazyLoader<>(userModel -> userModel.getGroups().stream().map(GroupModel::getId).collect(Collectors.toCollection(LinkedHashSet::new)), LinkedHashSet::new);
}
 
Example 3
Source File: RealmAdminResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("testSMTPConnection")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
public Response testSMTPConnection(Map<String, String> settings) throws Exception {
    try {
        UserModel user = auth.adminAuth().getUser();
        if (user.getEmail() == null) {
            return ErrorResponse.error("Logged in user does not have an e-mail.", Response.Status.INTERNAL_SERVER_ERROR);
        }
        if (ComponentRepresentation.SECRET_VALUE.equals(settings.get("password"))) {
            settings.put("password", realm.getSmtpConfig().get("password"));
        }
        session.getProvider(EmailTemplateProvider.class).sendSmtpTestEmail(settings, user);
    } catch (Exception e) {
        e.printStackTrace();
        logger.errorf("Failed to send email \n %s", e.getCause());
        return ErrorResponse.error("Failed to send email", Response.Status.INTERNAL_SERVER_ERROR);
    }

    return Response.noContent().build();
}
 
Example 4
Source File: EmailEventListenerProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(Event event) {
    if (includedEvents.contains(event.getType())) {
        if (event.getRealmId() != null && event.getUserId() != null) {
            RealmModel realm = model.getRealm(event.getRealmId());
            UserModel user = session.users().getUserById(event.getUserId(), realm);
            if (user != null && user.getEmail() != null && user.isEmailVerified()) {
                try {
                    emailTemplateProvider.setRealm(realm).setUser(user).sendEvent(event);
                } catch (EmailException e) {
                    log.error("Failed to send type mail", e);
                }
            }
        }
    }
}
 
Example 5
Source File: Sssd.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o == null) return false;

    UserModel userModel = (UserModel) o;
    if (firstName != null && !firstName.equals(userModel.getFirstName())) {
        return false;
    }
    if (lastName != null && !lastName.equals(userModel.getLastName())) {
        return false;
    }
    if (email != null) {
        return email.equals(userModel.getEmail());
    }
    if (email != userModel.getEmail()) {
        return false;
    }
    return true;
}
 
Example 6
Source File: LoginNotifyEmailAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    UserModel user = context.getUser();

    long currentLoginTime = System.currentTimeMillis();
    long lastLoginTime = detectLastLoginTimeForUser(user, currentLoginTime);

    try {
        if (user.getEmail() != null) {
            String timeSinceLastEmail = getConfigSettingOrDefault(context, TIME_SINCE_LAST_LOGIN, null);
            if (timeSinceLastEmail != null) {
                Duration duration = Duration.parse(timeSinceLastEmail);
                Instant lastLogin = Instant.ofEpochMilli(lastLoginTime);
                Instant currentLogin = Instant.ofEpochMilli(currentLoginTime);
                if (lastLogin.plus(duration).isBefore(currentLogin)) {
                    log.infof("Sending login notification email after longer absence. userId=%s", user.getUsername());
                    sendLoginNotificationEmail(context, user);
                }
            }
        }
    } catch (Exception ex) {
        log.warnf("Could not send login notification email after longer absence. userId=%s", user.getId(), ex);
    } finally {
        updateLastLoginTimeForUser(user, currentLoginTime);
        context.success();
    }
}
 
Example 7
Source File: MigrateTo1_4_0.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void migrateUsers(KeycloakSession session, RealmModel realm) {
    List<UserModel> users = session.userLocalStorage().getUsers(realm, false);
    for (UserModel user : users) {
        String email = user.getEmail();
        email = KeycloakModelUtils.toLowerCaseSafe(email);
        if (email != null && !email.equals(user.getEmail())) {
            user.setEmail(email);
            UserCache userCache = session.userCache();
            if (userCache != null) {
                userCache.evict(realm, user);
            }
        }
    }
}
 
Example 8
Source File: TestCacheUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void cacheRealmWithEverything(KeycloakSession session, String realmName) {
    RealmModel realm  = session.realms().getRealmByName(realmName);

    for (ClientModel client : realm.getClients()) {
        realm.getClientById(client.getId());
        realm.getClientByClientId(client.getClientId());

        cacheRoles(session, realm, client);
    }

    cacheRoles(session, realm, realm);

    for (GroupModel group : realm.getTopLevelGroups()) {
        cacheGroupRecursive(realm, group);
    }

    for (ClientScopeModel clientScope : realm.getClientScopes()) {
        realm.getClientScopeById(clientScope.getId());
    }

    for (UserModel user : session.users().getUsers(realm)) {
        session.users().getUserById(user.getId(), realm);
        if (user.getEmail() != null) {
            session.users().getUserByEmail(user.getEmail(), realm);
        }
        session.users().getUserByUsername(user.getUsername(), realm);

        session.users().getConsents(realm, user.getId());

        for (FederatedIdentityModel fedIdentity : session.users().getFederatedIdentities(user, realm)) {
            session.users().getUserByFederatedIdentity(fedIdentity, realm);
        }
    }
}
 
Example 9
Source File: DefaultEmailSenderProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected String retrieveEmailAddress(UserModel user) {
    return user.getEmail();
}
 
Example 10
Source File: PolicyEvaluationResponseBuilder.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static String getUserEmailOrUserName(UserModel user) {
    return (user.getEmail() != null ? user.getEmail() : user.getUsername());
}