Compare commits

...

40 Commits

Author SHA1 Message Date
8ff86b1e29 Update changelog v1.0.1 2021-05-01 14:12:41 +00:00
e1b8760ee3 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-05-01 16:10:57 +02:00
bd0d890b2c Fix: LoginOtp (and not otc) 2021-05-01 16:10:52 +02:00
2a2118d769 Update changelog v1.0.0 2021-05-01 13:52:33 +00:00
9839b64650 Bump version (changelog ignore) 2021-05-01 15:50:45 +02:00
2bf55e12f9 Guide for implementing a missing page (fix, changelog ignore) 2021-05-01 15:50:12 +02:00
2249fa9232 #4: Guide for implementing a missing page 2021-05-01 15:48:49 +02:00
f673a65304 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-05-01 14:56:01 +02:00
0163459ad6 Support OTP #4 2021-05-01 14:55:58 +02:00
b21123cc9d Update changelog v0.4.4 2021-04-29 21:33:33 +00:00
7800d125b2 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-04-29 23:31:12 +02:00
89ea648f18 Fix previous release 2021-04-29 23:31:05 +02:00
ab7ac3c2d0 Update changelog v0.4.3 2021-04-29 17:07:48 +00:00
b16319d962 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-04-29 19:02:16 +02:00
f8012d5dfb Bump version (changelog ignore) 2021-04-29 19:00:56 +02:00
45a2015597 Add infos about the plugin that defines authorizedMailDomains 2021-04-29 19:00:38 +02:00
524ab000be Update changelog v0.4.2 2021-04-29 16:47:44 +00:00
d73cfb8765 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-04-29 18:42:29 +02:00
8164f5373f Client side validation of allowed email domains 2021-04-29 18:42:14 +02:00
824b0c275e fmt (changelog ignore) 2021-04-21 20:45:03 +02:00
f8d83d7a37 Update README (changelog ignore) 2021-04-20 11:44:57 +02:00
b291526b13 Support email whitlisting 2021-04-15 12:20:08 +02:00
e1c310d383 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-04-12 23:46:29 +02:00
242777a8eb Restore kickstart video in the readme 2021-04-12 23:46:24 +02:00
10a6b70fe9 Update README.md 2021-04-12 19:27:54 +02:00
c829f5969c Update README.md 2021-04-12 18:51:16 +02:00
ba6a5047b1 Add note (changelog ignore) 2021-04-12 04:59:39 +02:00
852f48c05f update gif (changelog ignore) 2021-04-12 04:47:53 +02:00
c342f04a92 Update video (changelog ignore) 2021-04-12 04:21:18 +02:00
42eb8147c6 fmt (changelog ignore) 2021-04-12 02:29:24 +02:00
ebcdbd782f fmt (changelog ignore) 2021-04-12 02:28:22 +02:00
d2059e08d1 fmt (changelog ignore) 2021-04-12 02:25:48 +02:00
4f075882d5 Merge branch 'main' of https://github.com/garronej/keycloakify into main 2021-04-12 02:24:17 +02:00
044ec1a2da Important readme update 2021-04-12 02:24:11 +02:00
a49a32703d Update changelog v0.4.1 2021-04-11 16:24:36 +00:00
46ec832767 Quietly re-introduce --external-assets 2021-04-11 18:18:52 +02:00
fc858b3db6 Update screenshot (changelog ignore) 2021-04-11 01:21:01 +02:00
3cd8843157 Update screenshot in readme for therms and conditions (changelog ignore) 2021-04-10 20:20:26 +02:00
c9358ea8dd Merge branch 'main' of https://github.com/InseeFrLab/keycloakify into main 2021-04-09 04:02:30 +02:00
354a4db0f6 Give example of customization 2021-04-09 04:02:23 +02:00
17 changed files with 539 additions and 120 deletions

View File

@ -1,3 +1,34 @@
### **1.0.1** (2021-05-01)
- Fix: LoginOtp (and not otc)
# **1.0.0** (2021-05-01)
- #4: Guide for implementing a missing page
- Support OTP #4
### **0.4.4** (2021-04-29)
- Fix previous release
### **0.4.3** (2021-04-29)
- Add infos about the plugin that defines authorizedMailDomains
### **0.4.2** (2021-04-29)
- Client side validation of allowed email domains
- Support email whitlisting
- Restore kickstart video in the readme
- Update README.md
- Update README.md
- Important readme update
### **0.4.1** (2021-04-11)
- Quietly re-introduce --external-assets
- Give example of customization
## **0.4.0** (2021-04-09)
- Acual support of Therms of services

229
README.md
View File

@ -2,7 +2,7 @@
<img src="https://user-images.githubusercontent.com/6702424/109387840-eba11f80-7903-11eb-9050-db1dad883f78.png">
</p>
<p align="center">
<i>🔏 Customize key cloak's pages as if they were part of your App 🔏</i>
<i>🔏 Create Keycloak themes using React 🔏</i>
<br>
<br>
<img src="https://github.com/garronej/keycloakify/workflows/ci/badge.svg?branch=develop">
@ -12,86 +12,121 @@
</p>
<p align="center">
<i>Ultimately this build tool Generates a Keycloak theme</i>
<i>Ultimately this build tool generates a Keycloak theme</i>
<img src="https://user-images.githubusercontent.com/6702424/110260457-a1c3d380-7fac-11eb-853a-80459b65626b.png">
</p>
# Motivations
The problem:
Keycloak provides [theme support](https://www.keycloak.org/docs/latest/server_development/#_themes) for web pages. This allows customizing the look and feel of end-user facing pages so they can be integrated with your applications.
It involves, however, a lot of raw JS/CSS/[FTL]() hacking, and bundling the theme is not exactly straightforward.
Beyond that, if you use Keycloak for a specific app you want your login page to be tightly integrated with it.
Ideally, you don't want the user to notice when he is being redirected away.
Trying to reproduce the look and feel of a specific app in another stack is not an easy task not to mention
the cheer amount of maintenance that it involves.
<p align="center">
<i>Without keycloakify:</i><br>
<i>Without keycloakify, users suffers from a harsh context switch, no fronted form pre-validation</i><br>
<img src="https://user-images.githubusercontent.com/6702424/108838381-dbbbcf80-75d3-11eb-8ae8-db41563ef9db.gif">
</p>
When we redirected to Keycloak the user suffers from a harsh context switch.
Keycloak does offer a way to customize theses pages but it requires a lot of raw HTML/CSS hacking
to reproduce the look and feel of a specific app. Not mentioning the maintenance cost of such an endeavour.
Wouldn't it be great if we could just design the login and register pages as if they where part of our app?
Here is `yarn add keycloakify` for you 🍸
Wouldn't it be great if we could just design the login and register pages as if they were part of our app?
Here is `keycloakify` for you 🍸
<p align="center">
<i>With keycloakify:</i><br>
<img src="https://github.com/InseeFrLab/keycloakify/releases/download/v0.3.8/keycloakify_after.gif">
</p>
<i> <a href="https://datalab.sspcloud.fr">With keycloakify:</a> </i>
<br>
<img src="https://user-images.githubusercontent.com/6702424/114332075-c5e37900-9b45-11eb-910b-48a05b3d90d9.gif">
</p>
*NOTE: No autocomplete here just because it was an incognito window.*
If you already have a Keycloak custom theme, it can be easily ported to Keycloakify.
---
**TL;DR**: [Here](https://github.com/garronej/keycloakify-demo-app) is a Hello World React project with Keycloakify set up.
- [Motivations](#motivations)
- [How to use](#how-to-use)
- [Setting up the build tool](#setting-up-the-build-tool)
- [Developing your login and register pages in your React app](#developing-your-login-and-register-pages-in-your-react-app)
- [Just changing the look](#just-changing-the-look)
- [Changing just the look of the default Keycloak theme](#changing-just-the-look-of-the-default-keycloak-theme)
- [Changing the look **and** feel](#changing-the-look-and-feel)
- [Hot reload](#hot-reload)
- [Terms and conditions](#terms-and-conditions)
- [Enable loading in a blink of an eye of login pages ⚡ (--external-assets)](#enable-loading-in-a-blink-of-an-eye-of-login-pages----external-assets)
- [Support for Terms and conditions](#support-for-terms-and-conditions)
- [Some pages still have the default theme. Why?](#some-pages-still-have-the-default-theme-why)
- [GitHub Actions](#github-actions)
- [Requirements](#requirements)
- [Limitations](#limitations)
- [`process.env.PUBLIC_URL` not supported.](#processenvpublic_url-not-supported)
- [`@font-face` importing fonts from the `src/` dir](#font-face-importing-fonts-from-thesrc-dir)
- [Example of setup that **won't** work](#example-of-setup-that-wont-work)
- [Workarounds](#workarounds)
- [Possible workarounds](#possible-workarounds)
- [Implement context persistence (optional)](#implement-context-persistence-optional)
- [API Reference](#api-reference)
- [The build tool](#the-build-tool)
- [Kickstart video](#kickstart-video)
- [Email domain whitelist](#email-domain-whitelist)
# How to use
**TL;DR**: [Here](https://github.com/garronej/keycloakify-demo-app) is a Hello World React project with Keycloakify set up.
## Setting up the build tool
```bash
yarn add keycloakify
```
[`package.json`](https://github.com/garronej/keycloakify-demo-app/blob/main/package.json)
```json
"homepage": "https://URL.OF/YOUR-APP"
"dependencies": {
"keycloakify": "^0.0.10"
},
"scripts": {
"keycloak": "yarn build && build-keycloak-theme",
},
}
```
`"homepage"` must be specified only if the url path is not `/`
(Onl `/YOUR-APP` matters `URL.OF` don't have to be the actual domain)
It is mandatory that you specify the url where your app will be available
using the `homepage` field.
```bash
yarn keycloak # generates keycloak-theme.jar
```
Once you've edited your `package.json` you can install your new
dependency with `yarn install` and build the keycloak theme with
`yarn keycloak`.
On the console will be printed all the instructions about how to load the generated theme in Keycloak
Once the build is complete instructions about how to load
the theme into Keycloak are printed in the console.
### Changing just the look of the default Keycloak theme
## Developing your login and register pages in your React app
The first approach is to only customize the style of the default Keycloak login by providing
your own class names.
### Just changing the look
The first approach is to only arr/replace the default class names by your
own.
If you have created a new React project specifically to create a Keycloak theme and nothing else then
your index should look something like:
`src/index.tsx`
```tsx
import { App } from "./<wherever>/App";
import {
KcApp,
defaultKcProps,
kcContext
} from "keycloakify";
import { css } from "tss-react";
const myClassName = css({ "color": "red" });
reactDom.render(
<KcApp
kcContext={kcContext}
{...{
...defaultKcProps,
"kcHeaderWrapperClass": myClassName
}}
/>
document.getElementById("root")
);
```
If you share a unique project for your app and the Keycloak theme, your index should look
more like this:
`src/index.tsx`
```tsx
import { App } from "./<wherever>/App";
import {
KcApp,
@ -118,23 +153,43 @@ reactDom.render(
);
```
<i>result:</i>
<p align="center">
<img src="https://user-images.githubusercontent.com/6702424/110261408-688d6280-7fb0-11eb-9822-7003d268b459.png">
<i>result:</i></br>
<img src="https://user-images.githubusercontent.com/6702424/114326299-6892fc00-9b34-11eb-8d75-85696e55458f.png">
</p>
Example of a customization using only CSS: [here](https://github.com/InseeFrLab/onyxia-ui/blob/012639d62327a9a56be80c46e32c32c9497b82db/src/app/components/KcApp.tsx)
(the [index.tsx](https://github.com/InseeFrLab/onyxia-ui/blob/012639d62327a9a56be80c46e32c32c9497b82db/src/app/index.tsx#L89-L94) )
and the result you can expect:
<p align="center">
<i> <a href="https://datalab.sspcloud.fr">Customization using only CSS:</a> </i>
<br>
<img src="https://github.com/InseeFrLab/keycloakify/releases/download/v0.3.8/keycloakify_after.gif">
</p>
### Changing the look **and** feel
If you want to really re-implement the pages the best approach is to
create you own version of the [`<KcApp />`](https://github.com/garronej/keycloakify/blob/develop/src/lib/components/KcApp.tsx).
If you want to really re-implement the pages, the best approach is to
create your own version of the [`<KcApp />`](https://github.com/garronej/keycloakify/blob/develop/src/lib/components/KcApp.tsx).
Copy/past some of [the components](https://github.com/garronej/keycloakify/tree/develop/src/lib/components) provided by this module and start hacking around.
You can find an example of such customization [here](https://github.com/InseeFrLab/onyxia-ui/tree/master/src/app/components/KcApp).
And you can test the result in production by trying the login register page of [Onyxia](https://datalab.sspcloud.fr)
WARNING: If you chose to go this way use:
```json
"dependencies": {
"keycloakify": "~X.Y.Z"
}
```
in your `package.json` instead of `^X.Y.Z`. A minor release might break your app.
### Hot reload
By default, in order to see your changes you will have to wait for
`yarn build` to complete which can takes sevrall minute.
Rebuild the theme each time you make a change to see the result is not practical.
If you want to test your login screens outside of Keycloak, in [storybook](https://storybook.js.org/)
for example you can use `kcContextMocks`.
@ -146,7 +201,6 @@ import {
} from "keycloakify";
reactDom.render(
kcContext !== undefined ?
<KcApp
kcContext={kcContextMocks.kcLoginContext}
{...defaultKcProps}
@ -155,26 +209,48 @@ reactDom.render(
);
```
then `yarn start` ...
Then `yarn start`, you will see your login page.
Checkout [this concrete example](https://github.com/garronej/keycloakify-demo-app/blob/main/src/index.tsx)
## Enable loading in a blink of an eye of login pages ⚡ (--external-assets)
*NOTE: keycloak-react-theming was renamed keycloakify since this video was recorded*
[![kickstart_video](https://user-images.githubusercontent.com/6702424/108877866-f146ee80-75ff-11eb-8120-003b3c5f6dd8.png)](https://youtu.be/xTz0Rj7i2v8)
By default the theme generated is standalone. Meaning that when your users
reach the login pages all scripts, images and stylesheet are downloaded from the Keycloak server.
If you are specifically building a theme to integrate with an app or a website that allows users
to first browse unauthenticated before logging in, you will get a significant
performance boost if you jump through those hoops:
# Terms and conditions
- Provide the url of your app in the `homepage` field of package.json. [ex](https://github.com/garronej/keycloakify-demo-app/blob/7847cc70ef374ab26a6cc7953461cf25603e9a6d/package.json#L2)
- Build the theme using `npx build-keycloak-theme --external-assets` [ex](https://github.com/garronej/keycloakify-demo-app/blob/7847cc70ef374ab26a6cc7953461cf25603e9a6d/.github/workflows/ci.yaml#L21)
- Enable [long-term assets caching](https://create-react-app.dev/docs/production-build/#static-file-caching) on the server hosting your app.
- Make sure not to build your app and the keycloak theme separately
and remember to update the Keycloak theme every time you update your app.
- Be mindful that if your app is down your login pages are down as well.
Checkout a complete setup [here](https://github.com/garronej/keycloakify-demo-app#about-keycloakify)
# Support for Terms and conditions
[Many organizations have a requirement that when a new user logs in for the first time, they need to agree to the terms and conditions of the website.](https://www.keycloak.org/docs/4.8/server_admin/#terms-and-conditions).
First you need to enable the required action on the Keycloak server admin console:
![image](https://user-images.githubusercontent.com/6702424/114114637-87e61b00-98e1-11eb-9da9-1ca6c13d5d2e.png)
![image](https://user-images.githubusercontent.com/6702424/114280501-dad2e600-9a39-11eb-9c39-a225572dd38a.png)
Then to load your own therms of services using [like this](https://github.com/garronej/keycloakify-demo-app/blob/8168c928a66605f2464f9bd28a4dc85fb0a231f9/src/index.tsx#L42-L66).
# Some pages still have the default theme. Why?
This project only support the most common user facing pages of Keycloak login.
[Here is](https://user-images.githubusercontent.com/6702424/116784128-d4f97f00-aa92-11eb-92c9-b024c2521aa3.png) the complete list of pages.
And [here](https://github.com/InseeFrLab/keycloakify/tree/main/src/lib/components) are the pages currently implemented by this module.
If you need to customize pages that are not supported yet you can submit an issue about it and wait for me get it implemented.
If you can't wait, PR are welcome! [Here](https://github.com/InseeFrLab/keycloakify/commit/0163459ad6b1ad0afcc34fae5f3cc28dbcf8b4a7) is the commit that adds support
for the `login-otp.ftl` page. You can use it as a model for implementing other pages.
# GitHub Actions
![image](https://user-images.githubusercontent.com/6702424/110708305-c44b2c00-81fa-11eb-8152-eeaaac0883d6.png)
![image](https://user-images.githubusercontent.com/6702424/114286938-47aea600-9a63-11eb-936e-17159e8826e8.png)
[Here is a demo repo](https://github.com/garronej/keycloakify-demo-app) to show how to automate
the building and publishing of the theme (the .jar file).
@ -186,41 +262,43 @@ Tested with the following Keycloak versions:
- [12.0.4](https://hub.docker.com/layers/jboss/keycloak/12.0.4/images/sha256-67e0c88e69bd0c7aef972c40bdeb558a974013a28b3668ca790ed63a04d70584?context=explore)
This tool will be maintained to stay compatible with Keycloak v11 and up, however, the default pages you will get
(before you customize it) will always be the ones of the Keycloak v11.
(before you customize it) will always be the ones of Keycloak v11.
This tools assumes you are bundling your app with Webpack (tested with 4.44.2) .
This tool assumes you are bundling your app with Webpack (tested with 4.44.2) .
It assumes there is a `build/` directory at the root of your react project directory containing a `index.html` file
and a `build/static/` directory generated by webpack.
**All this is defaults with [`create-react-app`](https://create-react-app.dev)** (tested with 4.0.3=)
- For building the theme: `mvn` (Maven) must be installed
- For development (testing the theme in a local container ): `rm`, `mkdir`, `wget`, `unzip` are assumed to be available
and `docker` up and running.
NOTE: This build tool has only be tested on MacOS.
**All this is defaults with [`create-react-app`](https://create-react-app.dev)** (tested with 4.0.3)
- For building the theme: `mvn` (Maven) must be installed (but you can build the theme in the CI)
- For testing the theme in a local Keycloak container (which is not mandatory for development):
`rm`, `mkdir`, `wget`, `unzip` are assumed to be available and `docker` up and running.
# Limitations
## `process.env.PUBLIC_URL` not supported.
You won't be able to [import things from your public directory in your JavaScript code](https://create-react-app.dev/docs/using-the-public-folder/#adding-assets-outside-of-the-module-system). (This isn't recommended anyway).
You won't be able to [import things from your public directory **in your JavaScript code**](https://create-react-app.dev/docs/using-the-public-folder/#adding-assets-outside-of-the-module-system).
(This isn't recommended anyway).
## `@font-face` importing fonts from the `src/` dir
If you are building the theme with [--external-assets](#enable-loading-in-a-blink-of-a-eye-of-login-pages-)
this limitation doesn't apply, you can import fonts however you see fit.
### Example of setup that **won't** work
- We have a `fonts/` directory in `src/`
- We import the font like this [`src: url("/fonts/my-font.woff2") format("woff2");`(https://github.com/garronej/keycloakify-demo-app/blob/07d54a3012ef354ee12b1374c6f7ad1cb125d56b/src/fonts.scss#L4) in a `.scss` a file.
- We import the font like this [`src: url("/fonts/my-font.woff2") format("woff2");`](https://github.com/garronej/keycloakify-demo-app/blob/07d54a3012ef354ee12b1374c6f7ad1cb125d56b/src/fonts.scss#L4) in a `.scss` a file.
### Workarounds
### Possible workarounds
If it is possible, use Google Fonts or any other font provider.
If you want to host your font recommended approach is to move your fonts into the `public`
- Use [`--external-assets`](#enable-loading-in-a-blink-of-a-eye-of-login-pages-).
- If it is possible, use Google Fonts or any other font provider.
- If you want to host your font recommended approach is to move your fonts into the `public`
directory and to place your `@font-face` statements in the `public/index.html`.
Example [here](https://github.com/InseeFrLab/onyxia-ui/blob/0e3a04610cfe872ca71dad59e05ced8f785dee4b/public/index.html#L6-L51).
You can also [use your explicit url](https://github.com/garronej/keycloakify-demo-app/blob/2de8a9eb6f5de9c94f9cd3991faad0377e63268c/src/fonts.scss#L16) but don't forget [`Access-Control-Allow-Origin`](https://github.com/garronej/keycloakify-demo-app/blob/2de8a9eb6f5de9c94f9cd3991faad0377e63268c/nginx.conf#L17-L19).
- You can also [use non relative url](https://github.com/garronej/keycloakify-demo-app/blob/2de8a9eb6f5de9c94f9cd3991faad0377e63268c/src/fonts.scss#L16) but don't forget [`Access-Control-Allow-Origin`](https://github.com/garronej/keycloakify-demo-app/blob/2de8a9eb6f5de9c94f9cd3991faad0377e63268c/nginx.conf#L17-L19).
# Implement context persistence (optional)
@ -281,11 +359,12 @@ If you really want to go the extra miles and avoid having the white
flash of the blank html before the js bundle have been evaluated
[here is a snippet](https://github.com/InseeFrLab/onyxia-ui/blob/a77eb502870cfe6878edd0d956c646d28746d053/public/index.html#L5-L54) that you can place in your `public/index.html` if you are using `powerhooks/useGlobalState`.
# API Reference
# Kickstart video
## The build tool
*NOTE: keycloak-react-theming was renamed keycloakify since this video was recorded*
[![kickstart_video](https://user-images.githubusercontent.com/6702424/108877866-f146ee80-75ff-11eb-8120-003b3c5f6dd8.png)](https://youtu.be/xTz0Rj7i2v8)
Part of the lib that runs with node, at build time.
# Email domain whitelist
- `npx build-keycloak-theme`: Builds the theme, the CWD is assumed to be the root of your react project.
- `npx download-sample-keycloak-themes`: Downloads the keycloak default themes (for development purposes)
If you want to restrict the emails domain that can register, you can use [this plugin](https://github.com/micedre/keycloak-mail-whitelisting)
and `kcRegisterContext["authorizedMailDomains"]` to validate on.

View File

@ -1,6 +1,6 @@
{
"name": "keycloakify",
"version": "0.4.0",
"version": "1.0.1",
"description": "Keycloak theme generator for Reacts app",
"repository": {
"type": "git",

View File

@ -9,11 +9,13 @@ import {
import fs from "fs";
import { join as pathJoin } from "path";
import { objectKeys } from "evt/tools/typeSafety/objectKeys";
import { ftlValuesGlobalName } from "../ftlValuesGlobalName";
export const pageIds = [
"login.ftl", "register.ftl", "info.ftl",
"error.ftl", "login-reset-password.ftl",
"login-verify-email.ftl", "terms.ftl"
"login-verify-email.ftl", "terms.ftl",
"login-otp.ftl"
] as const;
export type PageId = typeof pageIds[number];
@ -37,22 +39,22 @@ function loadFtlFile(ftlFileBasename: PageId | "common.ftl") {
export function generateFtlFilesCodeFactory(
params: {
ftlValuesGlobalName: string;
cssGlobalsToDefine: Record<string, string>;
indexHtmlCode: string;
urlPathname: string;
urlOrigin: undefined | string;
}
) {
const { ftlValuesGlobalName, cssGlobalsToDefine, indexHtmlCode, urlPathname } = params;
const { cssGlobalsToDefine, indexHtmlCode, urlPathname, urlOrigin } = params;
const $ = cheerio.load(indexHtmlCode);
$("script:not([src])").each((...[, element]) => {
const { fixedJsCode } = replaceImportsFromStaticInJsCode({
ftlValuesGlobalName,
"jsCode": $(element).html()!
"jsCode": $(element).html()!,
urlOrigin
});
$(element).text(fixedJsCode);
@ -63,7 +65,8 @@ export function generateFtlFilesCodeFactory(
const { fixedCssCode } = replaceImportsInInlineCssCode({
"cssCode": $(element).html()!,
"urlPathname": params.urlPathname
"urlPathname": params.urlPathname,
urlOrigin
});
$(element).text(fixedCssCode);
@ -84,10 +87,12 @@ export function generateFtlFilesCodeFactory(
$(element).attr(
attrName,
href.replace(
new RegExp(`^${urlPathname.replace(/\//g, "\\/")}`),
"${url.resourcesPath}/build/"
)
urlOrigin !== undefined ?
href.replace(/^\//, `${urlOrigin}/`) :
href.replace(
new RegExp(`^${urlPathname.replace(/\//g, "\\/")}`),
"${url.resourcesPath}/build/"
)
);
})

View File

@ -0,0 +1,37 @@
<script>const _=
{
"otpLogin": {
"userOtpCredentials": (function(){
var out = [];
<#attempt>
<#list otpLogin.userOtpCredentials as otpCredential>
out.push({
"id": (function (){
<#attempt>
return "${otpCredential.id}";
<#recover>
</#attempt>
})(),
"userLabel": (function (){
<#attempt>
return "${otpCredential.userLabel}";
<#recover>
</#attempt>
})()
});
</#list>
<#recover>
</#attempt>
return out;
})()
}
}
</script>

View File

@ -147,6 +147,43 @@
<#recover>
</#attempt>
})()
})(),
"authorizedMailDomains": (function (){
<#attempt>
return "${authorizedMailDomains!''}" || undefined;
<#recover>
</#attempt>
})(),
"authorizedMailDomains": (function(){
var out = undefined;
<#attempt>
<#if authorizedMailDomains??>
out = [];
<#attempt>
<#list authorizedMailDomains as authorizedMailDomain>
out.push((function (){
<#attempt>
return "${authorizedMailDomain}";
<#recover>
</#attempt>
})());
</#list>
<#recover>
</#attempt>
</#if>
<#recover>
</#attempt>
return out;
})(),
}
</script>

View File

@ -32,7 +32,7 @@ export function generateJavaStackFiles(
return (!homepage ?
fallbackGroupId :
url.parse(homepage).host?.split(".").reverse().join(".") ?? fallbackGroupId
url.parse(homepage).host?.replace(/:[0-9]+$/,"")?.split(".").reverse().join(".") ?? fallbackGroupId
) + ".keycloak";
})();

View File

@ -10,7 +10,6 @@ import { generateFtlFilesCodeFactory, pageIds } from "./generateFtl";
import { builtinThemesUrl } from "../install-builtin-keycloak-themes";
import { downloadAndUnzip } from "../tools/downloadAndUnzip";
import * as child_process from "child_process";
import { ftlValuesGlobalName } from "./ftlValuesGlobalName";
import { resourcesCommonPath, resourcesPath, subDirOfPublicDirBasename } from "../../lib/kcContextMocks/urlResourcesPath";
import { isInside } from "../tools/isInside";
@ -21,22 +20,28 @@ export function generateKeycloakThemeResources(
reactAppBuildDirPath: string;
keycloakThemeBuildingDirPath: string;
urlPathname: string;
//If urlOrigin is not undefined then it means --externals-assets
urlOrigin: undefined | string;
}
) {
const { themeName, reactAppBuildDirPath, keycloakThemeBuildingDirPath, urlPathname } = params;
const { themeName, reactAppBuildDirPath, keycloakThemeBuildingDirPath, urlPathname, urlOrigin } = params;
const themeDirPath = pathJoin(keycloakThemeBuildingDirPath, "src", "main", "resources", "theme", themeName, "login");
let allCssGlobalsToDefine: Record<string, string> = {};
transformCodebase({
"destDirPath": pathJoin(themeDirPath, "resources", "build"),
"destDirPath":
urlOrigin === undefined ?
pathJoin(themeDirPath, "resources", "build") :
reactAppBuildDirPath,
"srcDirPath": reactAppBuildDirPath,
"transformSourceCode": ({ filePath, sourceCode }) => {
//NOTE: Prevent cycles, excludes the folder we generated for debug in public/
if (
urlOrigin === undefined &&
isInside({
"dirPath": pathJoin(reactAppBuildDirPath, subDirOfPublicDirBasename),
filePath
@ -45,8 +50,7 @@ export function generateKeycloakThemeResources(
return undefined;
}
if (/\.css?$/i.test(filePath)) {
if (urlOrigin === undefined && /\.css?$/i.test(filePath)) {
const { cssGlobalsToDefine, fixedCssCode } = replaceImportsInCssCode(
{ "cssCode": sourceCode.toString("utf8") }
@ -61,36 +65,39 @@ export function generateKeycloakThemeResources(
}
if (/\.js?$/i.test(filePath)) {
const { fixedJsCode } = replaceImportsFromStaticInJsCode({
"jsCode": sourceCode.toString("utf8"),
ftlValuesGlobalName
urlOrigin
});
return { "modifiedSourceCode": Buffer.from(fixedJsCode, "utf8") };
}
return { "modifiedSourceCode": sourceCode };
return urlOrigin === undefined ?
{ "modifiedSourceCode": sourceCode } :
undefined;
}
});
const { generateFtlFilesCode } = generateFtlFilesCodeFactory({
"cssGlobalsToDefine": allCssGlobalsToDefine,
ftlValuesGlobalName,
"indexHtmlCode": fs.readFileSync(
pathJoin(reactAppBuildDirPath, "index.html")
).toString("utf8"),
urlPathname
urlPathname,
urlOrigin
});
pageIds.forEach(pageId => {
const { ftlCode } = generateFtlFilesCode({ pageId });
fs.mkdirSync(themeDirPath, { "recursive": true });
fs.writeFileSync(
pathJoin(themeDirPath, pageId),
Buffer.from(ftlCode, "utf8")

View File

@ -11,6 +11,8 @@ import { URL } from "url";
const reactProjectDirPath = process.cwd();
const doUseExternalAssets = process.argv[2]?.toLowerCase() === "--external-assets";
const parsedPackageJson: ParsedPackageJson = require(pathJoin(reactProjectDirPath, "package.json"));
export const keycloakThemeBuildingDirPath = pathJoin(reactProjectDirPath, "build_keycloak");
@ -24,7 +26,7 @@ if (require.main === module) {
keycloakThemeBuildingDirPath,
"reactAppBuildDirPath": pathJoin(reactProjectDirPath, "build"),
"themeName": parsedPackageJson.name,
"urlPathname": (() => {
...(() => {
const url = (() => {
@ -36,10 +38,23 @@ if (require.main === module) {
})();
return url === undefined ?
"/" :
url.pathname.replace(/([^/])$/, "$1/");
return {
"urlPathname":
url === undefined ?
"/" :
url.pathname.replace(/([^/])$/, "$1/"),
"urlOrigin": !doUseExternalAssets ? undefined : (() => {
if (url === undefined) {
console.error("ERROR: You must specify 'homepage' in your package.json");
process.exit(-1);
}
return url.origin;
})()
};
})()
});

View File

@ -1,18 +1,22 @@
import * as crypto from "crypto";
import { ftlValuesGlobalName } from "./ftlValuesGlobalName";
export function replaceImportsFromStaticInJsCode(
params: {
ftlValuesGlobalName: string;
jsCode: string;
urlOrigin: undefined | string;
}
): { fixedJsCode: string; } {
const { jsCode, ftlValuesGlobalName } = params;
const { jsCode, urlOrigin } = params;
const fixedJsCode = jsCode.replace(
/[a-z]+\.[a-z]+\+"static\//g,
`window.${ftlValuesGlobalName}.url.resourcesPath + "/build/static/`
/([a-z]+\.[a-z]+)\+"static\//g,
(...[, group]) =>
urlOrigin === undefined ?
`window.${ftlValuesGlobalName}.url.resourcesPath + "/build/static/` :
`("${ftlValuesGlobalName}" in window ? "${urlOrigin}" : "") + ${group} + "static/`
);
return { fixedJsCode };
@ -23,16 +27,19 @@ export function replaceImportsInInlineCssCode(
params: {
cssCode: string;
urlPathname: string;
urlOrigin: undefined | string;
}
): { fixedCssCode: string; } {
const { cssCode, urlPathname } = params;
const { cssCode, urlPathname, urlOrigin } = params;
const fixedCssCode = cssCode.replace(
urlPathname === "/" ?
/url\(\/([^/][^)]+)\)/g :
new RegExp(`url\\(${urlPathname}([^)]+)\\)`, "g"),
(...[, group]) => `url(${"${url.resourcesPath}/build/" + group})`
(...[, group]) => `url(${urlOrigin === undefined ?
"${url.resourcesPath}/build/" + group :
params.urlOrigin + urlPathname + group})`
);
return { fixedCssCode };

View File

@ -9,6 +9,7 @@ import { Error } from "./Error";
import { LoginResetPassword } from "./LoginResetPassword";
import { LoginVerifyEmail } from "./LoginVerifyEmail";
import { Terms } from "./Terms";
import { LoginOtp } from "./LoginOtp";
export const KcApp = memo(({ kcContext, ...props }: { kcContext: KcContext; } & KcProps ) => {
switch (kcContext.pageId) {
@ -19,5 +20,6 @@ export const KcApp = memo(({ kcContext, ...props }: { kcContext: KcContext; } &
case "login-reset-password.ftl": return <LoginResetPassword {...{ kcContext, ...props }} />;
case "login-verify-email.ftl": return <LoginVerifyEmail {...{ kcContext, ...props }} />;
case "terms.ftl": return <Terms {...{ kcContext, ...props }}/>;
case "login-otp.ftl": return <LoginOtp {...{ kcContext, ...props }}/>;
}
});

View File

@ -0,0 +1,145 @@
import { useEffect, memo } from "react";
import { Template } from "./Template";
import type { KcProps } from "./KcProps";
import type { KcContext } from "../KcContext";
import { useKcMessage } from "../i18n/useKcMessage";
import { appendHead } from "../tools/appendHead";
import { join as pathJoin } from "path";
import { cx } from "tss-react";
export const LoginOtp = memo(({ kcContext, ...props }: { kcContext: KcContext.LoginOtp; } & KcProps) => {
const { otpLogin, url } = kcContext;
const { msg, msgStr } = useKcMessage();
useEffect(
() => {
let isCleanedUp = false;
appendHead({
"type": "javascript",
"src": pathJoin(
kcContext.url.resourcesCommonPath,
"node_modules/jquery/dist/jquery.min.js"
)
}).then(() => {
if (isCleanedUp) return;
evaluateInlineScript();
});
return () => { isCleanedUp = true };
},
[]
);
return (
<Template
{...{ kcContext, ...props }}
headerNode={msg("doLogIn")}
formNode={
<form
id="kc-otp-login-form"
className={cx(props.kcFormClass)}
action={url.loginAction}
method="post"
>
{
otpLogin.userOtpCredentials.length > 1 &&
<div className={cx(props.kcFormGroupClass)}>
<div className={cx(props.kcInputWrapperClass)}>
{
otpLogin.userOtpCredentials.map(otpCredential =>
<div className={cx(props.kcSelectOTPListClass)}>
<input type="hidden" value="${otpCredential.id}" />
<div className={cx(props.kcSelectOTPListItemClass)}>
<span className={cx(props.kcAuthenticatorOtpCircleClass)} />
<h2 className={cx(props.kcSelectOTPItemHeadingClass)}>
{otpCredential.userLabel}
</h2>
</div>
</div>
)
}
</div>
</div>
}
<div className={cx(props.kcFormGroupClass)}>
<div className={cx(props.kcLabelWrapperClass)}>
<label htmlFor="otp" className={cx(props.kcLabelClass)}>
{msg("loginOtpOneTime")}
</label>
</div>
<div className={cx(props.kcInputWrapperClass)}>
<input
id="otp"
name="otp"
autoComplete="off"
type="text"
className={cx(props.kcInputClass)}
autoFocus
/>
</div>
</div>
<div className={cx(props.kcFormGroupClass)}>
<div id="kc-form-options" className={cx(props.kcFormOptionsClass)}>
<div className={cx(props.kcFormOptionsWrapperClass)} />
</div>
<div id="kc-form-buttons" className={cx(props.kcFormButtonsClass)}>
<input
className={cx(
props.kcButtonClass,
props.kcButtonPrimaryClass,
props.kcButtonBlockClass,
props.kcButtonLargeClass
)}
name="login"
id="kc-login"
type="submit"
value={msgStr("doLogIn")}
/>
</div>
</div>
</form >
}
/>
);
});
declare const $: any;
function evaluateInlineScript() {
$(document).ready(function () {
// Card Single Select
$('.card-pf-view-single-select').click(function (this: any) {
if ($(this).hasClass('active')) { $(this).removeClass('active'); $(this).children().removeAttr('name'); }
else {
$('.card-pf-view-single-select').removeClass('active');
$('.card-pf-view-single-select').children().removeAttr('name');
$(this).addClass('active'); $(this).children().attr('name', 'selectedCredentialId');
}
});
var defaultCred = $('.card-pf-view-single-select')[0];
if (defaultCred) {
defaultCred.click();
}
});
}

View File

@ -17,7 +17,7 @@ type ExtractAfterStartingWith<Prefix extends string, StrEnum> =
export type KcContext =
KcContext.Login | KcContext.Register | KcContext.Info |
KcContext.Error | KcContext.LoginResetPassword | KcContext.LoginVerifyEmail |
KcContext.Terms;
KcContext.Terms | KcContext.LoginOtp;
export declare namespace KcContext {
@ -124,6 +124,11 @@ export declare namespace KcContext {
passwordRequired: boolean;
recaptchaRequired: boolean;
recaptchaSiteKey?: string;
/**
* Defined when you use the keycloak-mail-whitelisting keycloak plugin
* (https://github.com/micedre/keycloak-mail-whitelisting)
*/
authorizedMailDomains?: string[];
};
export type Info = Common & {
@ -160,6 +165,13 @@ export declare namespace KcContext {
pageId: "terms.ftl";
};
export type LoginOtp = Common & {
pageId: "login-otp.ftl";
otpLogin: {
userOtpCredentials: { id: string; userLabel: string; }[];
}
};
}
doExtends<KcContext["pageId"], PageId>();

View File

@ -153,7 +153,7 @@ export const kcRegisterContext: KcContext.Register = {
"registrationAction": "http://localhost:8080/auth/realms/myrealm/login-actions/registration?session_code=gwZdUeO7pbYpFTRxiIxRg_QtzMbtFTKrNu6XW_f8asM&execution=12146ce0-b139-4bbd-b25b-0eccfee6577e&client_id=account&tab_id=uS8lYfebLa0"
},
"messagesPerField": {
"printIfExists": (...[,x]) => x
"printIfExists": (...[, x]) => x
},
"scripts": [],
"isAppInitiatedAction": false,
@ -162,10 +162,17 @@ export const kcRegisterContext: KcContext.Register = {
"formData": {}
},
"passwordRequired": true,
"recaptchaRequired": false
"recaptchaRequired": false,
"authorizedMailDomains": [
"example.com",
"another-example.com",
"*.yet-another-example.com",
"*.example.com",
"hello-world.com"
]
};
export const kcInfoContext: KcContext.Info ={
export const kcInfoContext: KcContext.Info = {
...kcCommonContext,
"pageId": "info.ftl",
"messageHeader": "<Message header>",
@ -188,7 +195,7 @@ export const kcErrorContext: KcContext.Error = {
export const kcLoginResetPasswordContext: KcContext.LoginResetPassword = {
...kcCommonContext,
"pageId": "login-reset-password.ftl",
"realm":{
"realm": {
...kcCommonContext.realm,
"loginWithEmailAllowed": false
}
@ -204,3 +211,20 @@ export const kcTermsContext: KcContext.Terms = {
"pageId": "terms.ftl"
};
export const kcLoginOtpContext: KcContext.LoginOtp = {
...kcCommonContext,
"pageId": "login-otp.ftl",
"otpLogin": {
"userOtpCredentials": [
{
"id": "id1",
"userLabel": "label1"
},
{
"id": "id2",
"userLabel": "label2"
}
]
}
};

View File

@ -12,6 +12,7 @@ generateKeycloakThemeResources({
"themeName": "keycloakify-demo-app",
"reactAppBuildDirPath": pathJoin(sampleReactProjectDirPath, "build"),
"keycloakThemeBuildingDirPath": pathJoin(sampleReactProjectDirPath, "build_keycloak_theme"),
"urlPathname": "/keycloakify-demo-app/"
"urlPathname": "/keycloakify-demo-app/",
"urlOrigin": undefined
});

View File

@ -13,6 +13,7 @@ setupSampleReactProject();
const binDirPath= pathJoin(getProjectRoot(), "dist", "bin");
st.execSyncTrace(
//`node ${pathJoin(binDirPath, "build-keycloak-theme")} --external-assets`,
`node ${pathJoin(binDirPath, "build-keycloak-theme")}`,
{ "cwd": sampleReactProjectDirPath }
);
@ -21,4 +22,3 @@ st.execSyncTrace(
`node ${pathJoin(binDirPath, "install-builtin-keycloak-themes")}`,
{ "cwd": sampleReactProjectDirPath }
);

View File

@ -6,23 +6,40 @@ import { 
} from "../bin/build-keycloak-theme/replaceImportFromStatic";
const { fixedJsCode } = replaceImportsFromStaticInJsCode({
"ftlValuesGlobalName": "keycloakFtlValues",
"jsCode": `
function f() {
return a.p + "static/js/" + ({}[e] || e) + "." + {
return a.p+"static/js/" + ({}[e] || e) + "." + {
3: "0664cdc0"
}[e] + ".chunk.js"
}
function f2() {
return a.p +"static/js/" + ({}[e] || e) + "." + {
return a.p+"static/js/" + ({}[e] || e) + "." + {
3: "0664cdc0"
}[e] + ".chunk.js"
}
`
`,
"urlOrigin": undefined
});
console.log({ fixedJsCode });
const { fixedJsCode: fixedJsCodeExternal } = replaceImportsFromStaticInJsCode({
"jsCode": `
function f() {
return a.p+"static/js/" + ({}[e] || e) + "." + {
3: "0664cdc0"
}[e] + ".chunk.js"
}
function f2() {
return a.p+"static/js/" + ({}[e] || e) + "." + {
3: "0664cdc0"
}[e] + ".chunk.js"
}
`,
"urlOrigin": "https://www.example.com"
});
console.log({ fixedJsCode, fixedJsCodeExternal });
const { fixedCssCode, cssGlobalsToDefine } = replaceImportsInCssCode({
"cssCode": `