Search in sources :

Example 1 with MessageFormatterMethod

use of org.keycloak.theme.beans.MessageFormatterMethod in project keycloak by keycloak.

the class FreeMarkerLoginFormsProvider method handleThemeResources.

/**
 * Load message bundle and place it into <code>msg</code> template attribute. Also load Theme properties and place them into <code>properties</code> template attribute.
 *
 * @param theme actual Theme to load bundle from
 * @param locale to load bundle for
 * @return message bundle for other use
 */
protected Properties handleThemeResources(Theme theme, Locale locale) {
    Properties messagesBundle = new Properties();
    try {
        messagesBundle.putAll(theme.getMessages(locale));
        messagesBundle.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));
        attributes.put("msg", new MessageFormatterMethod(locale, messagesBundle));
        attributes.put("advancedMsg", new AdvancedMessageFormatterMethod(locale, messagesBundle));
    } catch (IOException e) {
        logger.warn("Failed to load messages", e);
        messagesBundle = new Properties();
    }
    try {
        attributes.put("properties", theme.getProperties());
    } catch (IOException e) {
        logger.warn("Failed to load properties", e);
    }
    return messagesBundle;
}
Also used : AdvancedMessageFormatterMethod(org.keycloak.theme.beans.AdvancedMessageFormatterMethod) IOException(java.io.IOException) Properties(java.util.Properties) AdvancedMessageFormatterMethod(org.keycloak.theme.beans.AdvancedMessageFormatterMethod) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod)

Example 2 with MessageFormatterMethod

use of org.keycloak.theme.beans.MessageFormatterMethod in project keycloak by keycloak.

the class FreeMarkerEmailTemplateProvider method processTemplate.

protected EmailTemplate processTemplate(String subjectKey, List<Object> subjectAttributes, String template, Map<String, Object> attributes) throws EmailException {
    try {
        Theme theme = getTheme();
        Locale locale = session.getContext().resolveLocale(user);
        attributes.put("locale", locale);
        Properties rb = new Properties();
        rb.putAll(theme.getMessages(locale));
        rb.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));
        attributes.put("msg", new MessageFormatterMethod(locale, rb));
        attributes.put("properties", theme.getProperties());
        String subject = new MessageFormat(rb.getProperty(subjectKey, subjectKey), locale).format(subjectAttributes.toArray());
        String textTemplate = String.format("text/%s", template);
        String textBody;
        try {
            textBody = freeMarker.processTemplate(attributes, textTemplate, theme);
        } catch (final FreeMarkerException e) {
            throw new EmailException("Failed to template plain text email.", e);
        }
        String htmlTemplate = String.format("html/%s", template);
        String htmlBody;
        try {
            htmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme);
        } catch (final FreeMarkerException e) {
            throw new EmailException("Failed to template html email.", e);
        }
        return new EmailTemplate(subject, textBody, htmlBody);
    } catch (Exception e) {
        throw new EmailException("Failed to template email", e);
    }
}
Also used : Locale(java.util.Locale) MessageFormat(java.text.MessageFormat) EmailException(org.keycloak.email.EmailException) Theme(org.keycloak.theme.Theme) FreeMarkerException(org.keycloak.theme.FreeMarkerException) Properties(java.util.Properties) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod) EmailException(org.keycloak.email.EmailException) IOException(java.io.IOException) FreeMarkerException(org.keycloak.theme.FreeMarkerException)

Example 3 with MessageFormatterMethod

use of org.keycloak.theme.beans.MessageFormatterMethod in project keycloak by keycloak.

the class FreeMarkerAccountProvider method handleThemeResources.

/**
 * Load message bundle and place it into <code>msg</code> template attribute. Also load Theme properties and place them into <code>properties</code> template attribute.
 *
 * @param theme actual Theme to load bundle from
 * @param locale to load bundle for
 * @param attributes template attributes to add resources to
 * @return message bundle for other use
 */
protected Properties handleThemeResources(Theme theme, Locale locale, Map<String, Object> attributes) {
    Properties messagesBundle = new Properties();
    try {
        messagesBundle.putAll(theme.getMessages(locale));
        messagesBundle.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));
        attributes.put("msg", new MessageFormatterMethod(locale, messagesBundle));
    } catch (IOException e) {
        logger.warn("Failed to load messages", e);
        messagesBundle = new Properties();
    }
    try {
        attributes.put("properties", theme.getProperties());
    } catch (IOException e) {
        logger.warn("Failed to load properties", e);
    }
    return messagesBundle;
}
Also used : IOException(java.io.IOException) Properties(java.util.Properties) AdvancedMessageFormatterMethod(org.keycloak.theme.beans.AdvancedMessageFormatterMethod) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod)

Example 4 with MessageFormatterMethod

use of org.keycloak.theme.beans.MessageFormatterMethod in project keycloak by keycloak.

the class AccountConsole method getMainPage.

@GET
@NoCache
public Response getMainPage() throws IOException, FreeMarkerException {
    UriInfo uriInfo = session.getContext().getUri(UrlType.FRONTEND);
    URI accountBaseUrl = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(realm.getName()).path(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).path("/").build(realm);
    if (!session.getContext().getUri().getRequestUri().getPath().endsWith("/")) {
        UriBuilder redirectUri = session.getContext().getUri().getRequestUriBuilder().uri(accountBaseUrl);
        return Response.status(302).location(redirectUri.build()).build();
    } else {
        Map<String, Object> map = new HashMap<>();
        URI adminBaseUri = session.getContext().getUri(UrlType.ADMIN).getBaseUri();
        URI authUrl = uriInfo.getBaseUri();
        map.put("authUrl", authUrl.getPath().endsWith("/") ? authUrl : authUrl + "/");
        map.put("baseUrl", accountBaseUrl);
        map.put("realm", realm);
        map.put("resourceUrl", Urls.themeRoot(authUrl).getPath() + "/" + Constants.ACCOUNT_MANAGEMENT_CLIENT_ID + "/" + theme.getName());
        map.put("resourceCommonUrl", Urls.themeRoot(adminBaseUri).getPath() + "/common/keycloak");
        map.put("resourceVersion", Version.RESOURCES_VERSION);
        String[] referrer = getReferrer();
        if (referrer != null) {
            map.put("referrer", referrer[0]);
            map.put("referrerName", referrer[1]);
            map.put("referrer_uri", referrer[2]);
        }
        UserModel user = null;
        if (auth != null)
            user = auth.getUser();
        Locale locale = session.getContext().resolveLocale(user);
        map.put("locale", locale.toLanguageTag());
        Properties messages = theme.getMessages(locale);
        messages.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));
        map.put("msg", new MessageFormatterMethod(locale, messages));
        map.put("msgJSON", messagesToJsonString(messages));
        map.put("supportedLocales", supportedLocales(messages));
        map.put("properties", theme.getProperties());
        map.put("theme", (Function<String, String>) file -> {
            try {
                final InputStream resource = theme.getResourceAsStream(file);
                return new Scanner(resource, "UTF-8").useDelimiter("\\A").next();
            } catch (IOException e) {
                throw new RuntimeException("could not load file", e);
            }
        });
        EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
        map.put("isEventsEnabled", eventStore != null && realm.isEventsEnabled());
        map.put("isAuthorizationEnabled", Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION));
        boolean isTotpConfigured = false;
        boolean deleteAccountAllowed = false;
        if (user != null) {
            isTotpConfigured = session.userCredentialManager().isConfiguredFor(realm, user, realm.getOTPPolicy().getType());
            RoleModel deleteAccountRole = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.DELETE_ACCOUNT);
            deleteAccountAllowed = deleteAccountRole != null && user.hasRole(deleteAccountRole) && realm.getRequiredActionProviderByAlias(DeleteAccount.PROVIDER_ID).isEnabled();
        }
        map.put("isTotpConfigured", isTotpConfigured);
        map.put("deleteAccountAllowed", deleteAccountAllowed);
        FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil();
        String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme);
        Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result);
        return builder.build();
    }
}
Also used : Locale(java.util.Locale) ClientModel(org.keycloak.models.ClientModel) Theme(org.keycloak.theme.Theme) RedirectUtils(org.keycloak.protocol.oidc.utils.RedirectUtils) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) EventStoreProvider(org.keycloak.events.EventStoreProvider) Constants(org.keycloak.models.Constants) Path(javax.ws.rs.Path) Scanner(java.util.Scanner) HashMap(java.util.HashMap) Version(org.keycloak.common.Version) Function(java.util.function.Function) ResolveRelative(org.keycloak.services.util.ResolveRelative) UserModel(org.keycloak.models.UserModel) Matcher(java.util.regex.Matcher) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Validation(org.keycloak.services.validation.Validation) Locale(java.util.Locale) AppAuthManager(org.keycloak.services.managers.AppAuthManager) Map(java.util.Map) Json(javax.json.Json) Auth(org.keycloak.services.managers.Auth) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) UrlType(org.keycloak.urls.UrlType) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Properties(java.util.Properties) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) IOException(java.io.IOException) DeleteAccount(org.keycloak.authentication.requiredactions.DeleteAccount) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) Collectors(java.util.stream.Collectors) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod) AccountRoles(org.keycloak.models.AccountRoles) MediaType(org.keycloak.utils.MediaType) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) Urls(org.keycloak.services.Urls) Pattern(java.util.regex.Pattern) UriInfo(javax.ws.rs.core.UriInfo) FreeMarkerException(org.keycloak.theme.FreeMarkerException) JsonObjectBuilder(javax.json.JsonObjectBuilder) InputStream(java.io.InputStream) Scanner(java.util.Scanner) HashMap(java.util.HashMap) InputStream(java.io.InputStream) RoleModel(org.keycloak.models.RoleModel) IOException(java.io.IOException) Properties(java.util.Properties) URI(java.net.URI) UserModel(org.keycloak.models.UserModel) Response(javax.ws.rs.core.Response) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) UriBuilder(javax.ws.rs.core.UriBuilder) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod) UriInfo(javax.ws.rs.core.UriInfo) EventStoreProvider(org.keycloak.events.EventStoreProvider) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 5 with MessageFormatterMethod

use of org.keycloak.theme.beans.MessageFormatterMethod in project keycloak by keycloak.

the class KeycloakErrorHandler method initAttributes.

private Map<String, Object> initAttributes(KeycloakSession session, RealmModel realm, Theme theme, Locale locale, int statusCode) throws IOException {
    Map<String, Object> attributes = new HashMap<>();
    Properties messagesBundle = theme.getMessages(locale);
    attributes.put("statusCode", statusCode);
    attributes.put("realm", realm);
    attributes.put("url", new UrlBean(realm, theme, session.getContext().getUri().getBaseUri(), null));
    attributes.put("locale", new LocaleBean(realm, locale, session.getContext().getUri().getBaseUriBuilder(), messagesBundle));
    String errorKey = statusCode == 404 ? Messages.PAGE_NOT_FOUND : Messages.INTERNAL_SERVER_ERROR;
    String errorMessage = messagesBundle.getProperty(errorKey);
    attributes.put("message", new MessageBean(errorMessage, MessageType.ERROR));
    try {
        attributes.put("msg", new MessageFormatterMethod(locale, theme.getMessages(locale)));
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        attributes.put("properties", theme.getProperties());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return attributes;
}
Also used : MessageBean(org.keycloak.theme.beans.MessageBean) UrlBean(org.keycloak.forms.login.freemarker.model.UrlBean) HashMap(java.util.HashMap) IOException(java.io.IOException) Properties(java.util.Properties) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod) LocaleBean(org.keycloak.theme.beans.LocaleBean)

Aggregations

IOException (java.io.IOException)5 Properties (java.util.Properties)5 MessageFormatterMethod (org.keycloak.theme.beans.MessageFormatterMethod)5 HashMap (java.util.HashMap)2 Locale (java.util.Locale)2 InputStream (java.io.InputStream)1 URI (java.net.URI)1 MessageFormat (java.text.MessageFormat)1 Map (java.util.Map)1 Scanner (java.util.Scanner)1 Function (java.util.function.Function)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 Collectors (java.util.stream.Collectors)1 Json (javax.json.Json)1 JsonObjectBuilder (javax.json.JsonObjectBuilder)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Context (javax.ws.rs.core.Context)1 Response (javax.ws.rs.core.Response)1