Search in sources :

Example 1 with FreeMarkerUtil

use of org.keycloak.theme.FreeMarkerUtil in project keycloak by keycloak.

the class QuarkusWelcomeResource method createWelcomePage.

private Response createWelcomePage(String successMessage, String errorMessage) {
    try {
        Theme theme = getTheme();
        Map<String, Object> map = new HashMap<>();
        map.put("productName", Version.NAME);
        map.put("productNameFull", Version.NAME_FULL);
        map.put("properties", theme.getProperties());
        map.put("adminUrl", session.getContext().getUri(UrlType.ADMIN).getBaseUriBuilder().path("/admin/").build());
        map.put("resourcesPath", "resources/" + Version.RESOURCES_VERSION + "/" + theme.getType().toString().toLowerCase() + "/" + theme.getName());
        map.put("resourcesCommonPath", "resources/" + Version.RESOURCES_VERSION + "/common/keycloak");
        boolean bootstrap = shouldBootstrap();
        map.put("bootstrap", bootstrap);
        if (bootstrap) {
            boolean isLocal = isLocal();
            map.put("localUser", isLocal);
            String localAdminUrl = getLocalAdminUrl();
            map.put("localAdminUrl", localAdminUrl);
            map.put("adminUserCreationMessage", "or set the environment variables KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD before starting the server");
            if (isLocal) {
                String stateChecker = setCsrfCookie();
                map.put("stateChecker", stateChecker);
            }
        }
        if (successMessage != null) {
            map.put("successMessage", successMessage);
        }
        if (errorMessage != null) {
            map.put("errorMessage", errorMessage);
        }
        FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil();
        String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme);
        ResponseBuilder rb = Response.status(errorMessage == null ? Status.OK : Status.BAD_REQUEST).entity(result).cacheControl(CacheControlUtil.noCache());
        return rb.build();
    } catch (Exception e) {
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Theme(org.keycloak.theme.Theme) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ForbiddenException(org.keycloak.services.ForbiddenException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 2 with FreeMarkerUtil

use of org.keycloak.theme.FreeMarkerUtil in project keycloak by keycloak.

the class WelcomeResource method createWelcomePage.

private Response createWelcomePage(String successMessage, String errorMessage) {
    try {
        Theme theme = getTheme();
        Map<String, Object> map = new HashMap<>();
        map.put("productName", Version.NAME);
        map.put("productNameFull", Version.NAME_FULL);
        map.put("properties", theme.getProperties());
        map.put("adminUrl", session.getContext().getUri(UrlType.ADMIN).getBaseUriBuilder().path("/admin/").build());
        map.put("resourcesPath", "resources/" + Version.RESOURCES_VERSION + "/" + theme.getType().toString().toLowerCase() + "/" + theme.getName());
        map.put("resourcesCommonPath", "resources/" + Version.RESOURCES_VERSION + "/common/keycloak");
        boolean bootstrap = shouldBootstrap();
        map.put("bootstrap", bootstrap);
        if (bootstrap) {
            boolean isLocal = isLocal();
            map.put("localUser", isLocal);
            map.put("localAdminUrl", "http://localhost:8080/auth");
            map.put("adminUserCreationMessage", "or use the add-user-keycloak script");
            if (isLocal) {
                String stateChecker = setCsrfCookie();
                map.put("stateChecker", stateChecker);
            }
        }
        if (successMessage != null) {
            map.put("successMessage", successMessage);
        }
        if (errorMessage != null) {
            map.put("errorMessage", errorMessage);
        }
        FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil();
        String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme);
        ResponseBuilder rb = Response.status(errorMessage == null ? Status.OK : Status.BAD_REQUEST).entity(result).cacheControl(CacheControlUtil.noCache());
        return rb.build();
    } catch (Exception e) {
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Theme(org.keycloak.theme.Theme) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ForbiddenException(org.keycloak.services.ForbiddenException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 3 with FreeMarkerUtil

use of org.keycloak.theme.FreeMarkerUtil in project keycloak by keycloak.

the class AdminConsole method getMainPage.

/**
 * Main page of this realm's admin console
 *
 * @return
 * @throws URISyntaxException
 */
@GET
@NoCache
public Response getMainPage() throws IOException, FreeMarkerException {
    if (!session.getContext().getUri(UrlType.ADMIN).getRequestUri().getPath().endsWith("/")) {
        return Response.status(302).location(session.getContext().getUri(UrlType.ADMIN).getRequestUriBuilder().path("/").build()).build();
    } else {
        Theme theme = AdminRoot.getTheme(session, realm);
        Map<String, Object> map = new HashMap<>();
        URI adminBaseUri = session.getContext().getUri(UrlType.ADMIN).getBaseUri();
        String adminBaseUrl = adminBaseUri.toString();
        if (adminBaseUrl.endsWith("/")) {
            adminBaseUrl = adminBaseUrl.substring(0, adminBaseUrl.length() - 1);
        }
        URI authServerBaseUri = session.getContext().getUri(UrlType.FRONTEND).getBaseUri();
        String authServerBaseUrl = authServerBaseUri.toString();
        if (authServerBaseUrl.endsWith("/")) {
            authServerBaseUrl = authServerBaseUrl.substring(0, authServerBaseUrl.length() - 1);
        }
        map.put("authServerUrl", authServerBaseUrl);
        map.put("authUrl", adminBaseUrl);
        map.put("consoleBaseUrl", Urls.adminConsoleRoot(adminBaseUri, realm.getName()).getPath());
        map.put("resourceUrl", Urls.themeRoot(adminBaseUri).getPath() + "/admin/" + theme.getName());
        map.put("resourceCommonUrl", Urls.themeRoot(adminBaseUri).getPath() + "/common/keycloak");
        map.put("masterRealm", Config.getAdminRealm());
        map.put("resourceVersion", Version.RESOURCES_VERSION);
        map.put("loginRealm", realm.getName());
        map.put("properties", theme.getProperties());
        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);
        // Replace CSP if admin is hosted on different URL
        if (!adminBaseUri.equals(authServerBaseUri)) {
            session.getProvider(SecurityHeadersProvider.class).options().allowFrameSrc(UriUtils.getOrigin(authServerBaseUri));
        }
        return builder.build();
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpResponse(org.jboss.resteasy.spi.HttpResponse) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) HashMap(java.util.HashMap) Theme(org.keycloak.theme.Theme) URI(java.net.URI) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 4 with FreeMarkerUtil

use of org.keycloak.theme.FreeMarkerUtil 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 FreeMarkerUtil

use of org.keycloak.theme.FreeMarkerUtil in project keycloak by keycloak.

the class KeycloakErrorHandler method toResponse.

@Override
public Response toResponse(Throwable throwable) {
    KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);
    KeycloakTransaction tx = session.getTransactionManager();
    tx.setRollbackOnly();
    int statusCode = getStatusCode(throwable);
    if (statusCode >= 500 && statusCode <= 599) {
        logger.error(UNCAUGHT_SERVER_ERROR_TEXT, throwable);
    } else {
        logger.debugv(throwable, ERROR_RESPONSE_TEXT, statusCode);
    }
    if (!MediaTypeMatcher.isHtmlRequest(headers)) {
        OAuth2ErrorRepresentation error = new OAuth2ErrorRepresentation();
        error.setError(getErrorCode(throwable));
        return Response.status(statusCode).header(HttpHeaders.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE.toString()).entity(error).build();
    }
    try {
        RealmModel realm = resolveRealm(session);
        Theme theme = session.theme().getTheme(Theme.Type.LOGIN);
        Locale locale = session.getContext().resolveLocale(null);
        FreeMarkerUtil freeMarker = new FreeMarkerUtil();
        Map<String, Object> attributes = initAttributes(session, realm, theme, locale, statusCode);
        String templateName = "error.ftl";
        String content = freeMarker.processTemplate(attributes, templateName, theme);
        return Response.status(statusCode).type(MediaType.TEXT_HTML_UTF_8_TYPE).entity(content).build();
    } catch (Throwable t) {
        logger.error("Failed to create error page", t);
        return Response.serverError().build();
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) Locale(java.util.Locale) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) KeycloakSession(org.keycloak.models.KeycloakSession) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) Theme(org.keycloak.theme.Theme) KeycloakTransaction(org.keycloak.models.KeycloakTransaction)

Aggregations

FreeMarkerUtil (org.keycloak.theme.FreeMarkerUtil)5 Theme (org.keycloak.theme.Theme)5 HashMap (java.util.HashMap)4 IOException (java.io.IOException)3 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 UnknownHostException (java.net.UnknownHostException)2 Locale (java.util.Locale)2 GET (javax.ws.rs.GET)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 Response (javax.ws.rs.core.Response)2 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)2 NoCache (org.jboss.resteasy.annotations.cache.NoCache)2 KeycloakSession (org.keycloak.models.KeycloakSession)2 RealmModel (org.keycloak.models.RealmModel)2 ForbiddenException (org.keycloak.services.ForbiddenException)2 InputStream (java.io.InputStream)1 Map (java.util.Map)1 Properties (java.util.Properties)1 Scanner (java.util.Scanner)1