Compare commits
112 Commits
Author | SHA1 | Date | |
---|---|---|---|
b93ec20119 | |||
ce04646576 | |||
9282dfe491 | |||
fca6280bcc | |||
cdeb575ec6 | |||
271dbe4fb7 | |||
9a0337114d | |||
2d28f4eb55 | |||
f673927e16 | |||
52896b82a9 | |||
9d53ecb0cd | |||
aec3ac32e5 | |||
f150f1568e | |||
309189c55d | |||
f68c54cd3a | |||
c21cd14ac2 | |||
275d7f0072 | |||
58c8306cf4 | |||
f782b684ad | |||
092b2a5f52 | |||
42b2d40ad6 | |||
3f6fe6cfc0 | |||
1abf542a74 | |||
c4720ca03d | |||
4316878cce | |||
c180d75a83 | |||
4a040b32c0 | |||
ea330a1eef | |||
2451ba0a77 | |||
2c276a56e5 | |||
708030b8b5 | |||
d5fc0582bc | |||
f9dce82c83 | |||
e82602f994 | |||
1d36395e5a | |||
8f8857bc22 | |||
226247b3b6 | |||
b2ea5014f3 | |||
48bc416aa7 | |||
386e7203b2 | |||
9bdb224631 | |||
dd36aacbee | |||
6b57b1c720 | |||
9e9e6d41ff | |||
5140389502 | |||
fc6328131f | |||
9de0083ca6 | |||
f5231b840d | |||
afb6596c4b | |||
dde9afef92 | |||
6595e9c3cb | |||
c0e3b5fe06 | |||
6b8f3bbc51 | |||
9a5a021e64 | |||
14c05fec8c | |||
eaf7a455cd | |||
55bb21f3ee | |||
f123bc0912 | |||
572eb7b1c0 | |||
2befaff8a8 | |||
437a9ce2d3 | |||
1b967b250a | |||
e221f39e07 | |||
21a8838a24 | |||
fad91ccae0 | |||
825914aa4b | |||
a8246d12ee | |||
abb8bf2ebb | |||
7e7071305f | |||
cc8b2e72c1 | |||
a3d6ee44a1 | |||
ac99e2f41f | |||
bf1839c061 | |||
fd5c132a40 | |||
4dfa268eb3 | |||
332ca084f5 | |||
01cbb8680a | |||
bbdaaf30bc | |||
0550b9ff8b | |||
b1a4c5cca5 | |||
785080e14a | |||
3c7e093a3c | |||
89be9f3a86 | |||
6f2ffa7861 | |||
7091f283f2 | |||
2d28003451 | |||
f0ba7d3c0d | |||
cd5f346895 | |||
66cd5aef0c | |||
6f8ec53e8b | |||
622504ff72 | |||
c9d47c483c | |||
07098b89a5 | |||
c583b83cbb | |||
1670e1fe42 | |||
de8809608c | |||
0e194ee045 | |||
4205f6ecbe | |||
4d90ec60e2 | |||
d126a6563b | |||
aecb6ae79c | |||
a65c826717 | |||
66c3705f2b | |||
d18ebb45f8 | |||
d8e01f2c5d | |||
4abbaa3841 | |||
42a463b348 | |||
8e15cf1d45 | |||
2468b4108e | |||
528b1bb607 | |||
b4449bb289 | |||
737e00b490 |
8
.github/workflows/ci.yaml
vendored
8
.github/workflows/ci.yaml
vendored
@ -14,7 +14,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v2.3.4
|
||||
- uses: actions/setup-node@v2.1.3
|
||||
- uses: bahmutov/npm-install@v1
|
||||
- uses: bahmutov/npm-install@v1.8.15
|
||||
- name: If this step fails run 'yarn format' then commit again.
|
||||
run: |
|
||||
PACKAGE_MANAGER=npm
|
||||
@ -25,6 +25,8 @@ jobs:
|
||||
test:
|
||||
runs-on: macos-10.15
|
||||
needs: test_formatting
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
strategy:
|
||||
matrix:
|
||||
node: [ '15', '14' ]
|
||||
@ -39,7 +41,7 @@ jobs:
|
||||
- uses: actions/setup-node@v2.1.3
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
- uses: bahmutov/npm-install@v1
|
||||
- uses: bahmutov/npm-install@v1.8.15
|
||||
- if: steps.step1.outputs.npm_or_yarn == 'yarn'
|
||||
run: |
|
||||
yarn build
|
||||
@ -121,7 +123,7 @@ jobs:
|
||||
with:
|
||||
node-version: '15'
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- uses: bahmutov/npm-install@v1
|
||||
- uses: bahmutov/npm-install@v1.8.15
|
||||
- run: |
|
||||
PACKAGE_MANAGER=npm
|
||||
if [ -f "./yarn.lock" ]; then
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -47,4 +47,5 @@ jspm_packages
|
||||
|
||||
.idea
|
||||
|
||||
/keycloak_theme_email
|
||||
/keycloak_email
|
||||
/build_keycloak
|
121
CHANGELOG.md
121
CHANGELOG.md
@ -1,3 +1,124 @@
|
||||
## **5.6.0** (2022-06-28)
|
||||
|
||||
- Merge pull request #127 from aidangilmore/add-totp-support
|
||||
|
||||
feat: add login-config-totp.ftl page
|
||||
- Fix unknown algorithm name lookup in LoginConfigTotp
|
||||
- Add totp config support
|
||||
|
||||
## **5.5.0** (2022-06-28)
|
||||
|
||||
- Make it possible to redirect to login by repacing the url (should be default in most case)
|
||||
|
||||
### **5.4.7** (2022-06-19)
|
||||
|
||||
- #121
|
||||
- fmt
|
||||
- Create CONTRIBUTING.md
|
||||
- Enable users to link keycloak in their own app
|
||||
|
||||
### **5.4.6** (2022-06-16)
|
||||
|
||||
- Use keycloak 18.0.1 i18n resources #120
|
||||
|
||||
### **5.4.5** (2022-06-14)
|
||||
|
||||
- Merge pull request #119 from dro-sh/fix-locale-on-useFormValidationSlice
|
||||
|
||||
pass locale to getGetErrors to get correct messages
|
||||
- pass locale to getGetErrors to get correct messages
|
||||
|
||||
### **5.4.4** (2022-06-05)
|
||||
|
||||
|
||||
|
||||
### **5.4.3** (2022-06-01)
|
||||
|
||||
|
||||
|
||||
### **5.4.2** (2022-06-01)
|
||||
|
||||
- Prevent rate limite in CI by authenticating
|
||||
|
||||
### **5.4.1** (2022-06-01)
|
||||
|
||||
|
||||
|
||||
## **5.4.0** (2022-05-23)
|
||||
|
||||
- #109
|
||||
|
||||
### **5.3.2** (2022-05-04)
|
||||
|
||||
- Merge pull request #101 from Romcol/bugfix/99
|
||||
|
||||
Issue #99 - Make replace less greedy in remplaceImportFromStatic
|
||||
- [IMP] Issue #99 - Make replace less greedy in remplaceImportFromStatic
|
||||
|
||||
### **5.3.1** (2022-04-29)
|
||||
|
||||
- Comment out missleading informations
|
||||
|
||||
## **5.3.0** (2022-04-28)
|
||||
|
||||
- Rename keycloak_theme_email to keycloak_email (it's shorter)
|
||||
|
||||
## **5.2.0** (2022-04-27)
|
||||
|
||||
- Export KcApp
|
||||
|
||||
## **5.1.0** (2022-04-27)
|
||||
|
||||
- Export kcLanguageTags
|
||||
|
||||
# **5.0.0** (2022-04-27)
|
||||
|
||||
- i18n rebuild from the ground up
|
||||
|
||||
## **4.10.0** (2022-04-26)
|
||||
|
||||
- Merge pull request #92 from Tasyp/add-login-idp-link-email
|
||||
|
||||
feat: add login-idp-link-email page
|
||||
- feat: add mock data for login-idp-link-email page
|
||||
- feat: supply broker context with context
|
||||
|
||||
## **4.9.0** (2022-04-25)
|
||||
|
||||
- Test by default with kc 18. Update instructions to use quay.io/keycloak/keycloak instead of jboss/keycloak #93
|
||||
|
||||
### **4.8.7** (2022-04-25)
|
||||
|
||||
- Update instructions to test on Keycloak 18 https://github.com/keycloak/keycloak-web/issues/306 #93
|
||||
- Move the documentation form the readme to docs.keycloakify.dev
|
||||
- Update README.md
|
||||
- Update demo video
|
||||
|
||||
### **4.8.6** (2022-04-22)
|
||||
|
||||
- always offer to download v11.0.3
|
||||
|
||||
### **4.8.5** (2022-04-22)
|
||||
|
||||
- #91
|
||||
|
||||
### **4.8.4** (2022-04-22)
|
||||
|
||||
- #90
|
||||
|
||||
### **4.8.3** (2022-04-20)
|
||||
|
||||
|
||||
|
||||
### **4.8.2** (2022-04-20)
|
||||
|
||||
- Tell pepoles they can test with different keycloak version
|
||||
|
||||
### **4.8.1** (2022-04-20)
|
||||
|
||||
- Add missing shebang
|
||||
- Add video demo for npx download-builtin-keycloak-theme
|
||||
|
||||
## **4.8.0** (2022-04-20)
|
||||
|
||||
- Document email template customization feature #9
|
||||
|
3
CONTRIBUTING.md
Normal file
3
CONTRIBUTING.md
Normal file
@ -0,0 +1,3 @@
|
||||
Looking to contribute? Thank you! PR are more than welcome.
|
||||
|
||||
Please refers to [this documentation page](https://docs.keycloakify.dev/contributing) that will help you get started.
|
500
README.md
500
README.md
@ -12,7 +12,7 @@
|
||||
<img src="https://img.shields.io/bundlephobia/minzip/keycloakify">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/keycloakify">
|
||||
<img src="https://img.shields.io/npm/dw/keycloakify">
|
||||
<img src="https://img.shields.io/npm/dm/keycloakify">
|
||||
</a>
|
||||
<a href="https://github.com/garronej/keycloakify/blob/main/LICENSE">
|
||||
<img src="https://img.shields.io/npm/l/keycloakify">
|
||||
@ -23,486 +23,42 @@
|
||||
<a href="https://github.com/thomasdarimont/awesome-keycloak">
|
||||
<img src="https://awesome.re/mentioned-badge.svg"/>
|
||||
</a>
|
||||
<p align="center">
|
||||
<a href="https://www.keycloakify.dev">Home</a>
|
||||
-
|
||||
<a href="https://docs.keycloakify.dev">Documentation</a>
|
||||
</p>
|
||||
|
||||
> New with v4.7.4: **M1 Mac** support (for testing locally with a dockerized Keycloak).
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<i>Ultimately this build tool generates a Keycloak theme</i>
|
||||
<i>Ultimately this build tool generates a Keycloak theme <a href="https://www.keycloakify.dev">Learn more</a></i>
|
||||
<img src="https://user-images.githubusercontent.com/6702424/110260457-a1c3d380-7fac-11eb-853a-80459b65626b.png">
|
||||
</p>
|
||||
|
||||
# Motivations
|
||||
|
||||
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, users suffers from a harsh context switch, no fronted form pre-validation</i><br>
|
||||
<img src="https://user-images.githubusercontent.com/6702424/134997335-a28b4a57-0884-47ec-9341-a0e49f835c4d.gif">
|
||||
</p>
|
||||
|
||||
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> <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>
|
||||
|
||||
**TL;DR**: [Here](https://github.com/garronej/keycloakify-demo-app) is a Hello World React project with Keycloakify set up.
|
||||
|
||||
If you already have a Keycloak custom theme, it can be easily ported to Keycloakify.
|
||||
|
||||
---
|
||||
|
||||
- [Motivations](#motivations)
|
||||
- [Requirements](#requirements)
|
||||
- [My framework doesn’t seem to be supported, what can I do?](#my-framework-doesnt-seem-to-be-supported-what-can-i-do)
|
||||
- [How to use](#how-to-use)
|
||||
- [Setting up the build tool](#setting-up-the-build-tool)
|
||||
- [Changing just the look of the default Keycloak theme](#changing-just-the-look-of-the-default-keycloak-theme)
|
||||
- [Advanced pages configuration](#advanced-pages-configuration)
|
||||
- [Hot reload](#hot-reload)
|
||||
- [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)
|
||||
- [Email template customization.](#email-template-customization)
|
||||
- [User profile and frontend form validation](#user-profile-and-frontend-form-validation)
|
||||
- [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)
|
||||
- [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-the-src-dir)
|
||||
- [Example of setup that **won't** work](#example-of-setup-that-wont-work)
|
||||
- [Possible workarounds](#possible-workarounds)
|
||||
- [Implement context persistence (optional)](#implement-context-persistence-optional)
|
||||
- [Kickstart video](#kickstart-video)
|
||||
- [FTL errors related to `ftl_object_to_js_code_declaring_an_object` in Keycloak logs.](#ftl-errors-related-to-ftl_object_to_js_code_declaring_an_object-in-keycloak-logs)
|
||||
- [Adding custom message (to `i18n/useKcMessage.tsx`)](#adding-custom-message-to-i18nusekcmessagetsx)
|
||||
- [Downloading builtin theme resource files](#downloading-builtin-theme-resource-files)
|
||||
- [Email domain whitelist](#email-domain-whitelist)
|
||||
- [Changelog highlights](#changelog-highlights)
|
||||
- [v4.7.4](#v474)
|
||||
- [v4.7.2](#v472)
|
||||
- [v4.7.0](#v470)
|
||||
- [v4.6.0](#v460)
|
||||
- [v4.5.3](#v453)
|
||||
- [v4.3.0](#v430)
|
||||
- [v4](#v4)
|
||||
- [v3](#v3)
|
||||
- [v2.5](#v25)
|
||||
- [v2](#v2)
|
||||
|
||||
# Requirements
|
||||
|
||||
On Windows OS you'll have to use [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10). More info [here](https://github.com/InseeFrLab/keycloakify/issues/54#issuecomment-984834217)
|
||||
|
||||
Tested with the following Keycloak versions:
|
||||
|
||||
- [11.0.3](https://hub.docker.com/layers/jboss/keycloak/11.0.3/images/sha256-4438f1e51c1369371cb807dffa526e1208086b3ebb9cab009830a178de949782?context=explore)
|
||||
- [12.0.4](https://hub.docker.com/layers/jboss/keycloak/12.0.4/images/sha256-67e0c88e69bd0c7aef972c40bdeb558a974013a28b3668ca790ed63a04d70584?context=explore)
|
||||
- [15.0.2](https://hub.docker.com/layers/jboss/keycloak/15.0.2/images/sha256-d8ed1ee5df42a178c341f924377da75db49eab08ea9f058ff39a8ed7ee05ec93?context=explore)
|
||||
- [16.1.0](https://hub.docker.com/layers/jboss/keycloak/16.1.0/images/sha256-6ecb9492224c6cfbb55d43f64a5ab634145d8cc1eba14eae8c37e3afde89546e?context=explore)
|
||||
- 17.0.1
|
||||
|
||||
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 Keycloak v11.
|
||||
|
||||
This tool assumes you are bundling your app with Webpack (tested with the versions that ships with CRA v4.44.2 and v5.0.0) .
|
||||
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.
|
||||
For more information see [this issue](https://github.com/InseeFrLab/keycloakify/issues/5#issuecomment-832296432)
|
||||
|
||||
**All this is defaults with [`create-react-app`](https://create-react-app.dev)** (tested with 5.0.0, 4.0.3)
|
||||
|
||||
- `mvn` ([Maven](https://maven.apache.org/)), `rm`, `mkdir`, `curl`, `unzip` are assumed to be available.
|
||||
- `docker` must be up and running when running `start_keycloak_testing_container.sh` (Instructions provided after running `yarn keycloak`).
|
||||
|
||||
## My framework doesn’t seem to be supported, what can I do?
|
||||
|
||||
Currently Keycloakify is only compatible with SPA React apps.
|
||||
It doesn’t mean that you can't use Keycloakify if you are using Next.js, Express or any other
|
||||
framework that involves a server but your Keycloak theme will need to be a standalone project.
|
||||
Find specific instructions about how to get started [**here**](https://github.com/garronej/keycloakify-demo-app#keycloak-theme-only).
|
||||
|
||||
To share your styles between your main app and your login pages you will need to externalize your design system by making it a
|
||||
separate module. Checkout [ts_ci](https://github.com/garronej/ts_ci), it can help with that (example with [our design system](https://github.com/InseeFrLab/onyxia-ui)).
|
||||
|
||||
# How to use
|
||||
|
||||
## Setting up the build tool
|
||||
|
||||
```bash
|
||||
yarn add keycloakify @emotion/react
|
||||
```
|
||||
|
||||
[`package.json`](https://github.com/garronej/keycloakify-demo-app/blob/main/package.json)
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"keycloak": "yarn build && build-keycloak-theme",
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
yarn keycloak # generates keycloak-theme.jar
|
||||
```
|
||||
|
||||
On the console will be printed all the instructions about how to load the generated theme in Keycloak
|
||||
|
||||
### Changing just the look of the default Keycloak theme
|
||||
|
||||
The first approach is to only customize the style of the default Keycloak login by providing
|
||||
your own class names.
|
||||
|
||||
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, getKcContext } from "keycloakify";
|
||||
import { css } from "tss-react/@emotion/css";
|
||||
|
||||
const { kcContext } = getKcContext();
|
||||
|
||||
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, defaultKcProps, getKcContext } from "keycloakify";
|
||||
import { css } from "tss-react/@emotion/css";
|
||||
|
||||
const { kcContext } = getKcContext();
|
||||
|
||||
const myClassName = css({ "color": "red" });
|
||||
|
||||
reactDom.render(
|
||||
// Unless the app is currently being served by Keycloak
|
||||
// kcContext is undefined.
|
||||
kcContext !== undefined ? (
|
||||
<KcApp
|
||||
kcContext={kcContext}
|
||||
{...{
|
||||
...defaultKcProps,
|
||||
"kcHeaderWrapperClass": myClassName,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<App />
|
||||
), // Your actual app
|
||||
document.getElementById("root"),
|
||||
);
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<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-web/blob/012639d62327a9a56be80c46e32c32c9497b82db/src/app/components/KcApp.tsx)
|
||||
(the [index.tsx](https://github.com/InseeFrLab/onyxia-web/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>
|
||||
|
||||
### Advanced pages configuration
|
||||
|
||||
If you want to go beyond only customizing the CSS you can re-implement some of the
|
||||
pages or even add new ones.
|
||||
|
||||
If you want to go this way checkout the demo setup provided [here](https://github.com/garronej/keycloakify-demo-app/tree/look_and_feel).
|
||||
If you prefer a real life example you can checkout [onyxia-web's source](https://github.com/InseeFrLab/onyxia-web/tree/main/src/ui/components/KcApp).
|
||||
The web app is in production [here](https://datalab.sspcloud.fr).
|
||||
|
||||
Main takeaways are:
|
||||
|
||||
- You must declare your custom pages in the package.json. [example](https://github.com/garronej/keycloakify-demo-app/blob/4eb2a9f63e9823e653b2d439495bda55e5ecc134/package.json#L17-L22)
|
||||
- (TS only) You must declare theses page in the type argument of the getter
|
||||
function for the `kcContext` in order to have the correct typings. [example](https://github.com/garronej/keycloakify-demo-app/blob/4eb2a9f63e9823e653b2d439495bda55e5ecc134/src/KcApp/kcContext.ts#L16-L21)
|
||||
- (TS only) If you use Keycloak plugins that defines non standard `.ftl` values
|
||||
(Like for example [this plugin](https://github.com/micedre/keycloak-mail-whitelisting)
|
||||
that define `authorizedMailDomains` in `register.ftl`) you should
|
||||
declare theses value to get the type. [example](https://github.com/garronej/keycloakify-demo-app/blob/4eb2a9f63e9823e653b2d439495bda55e5ecc134/src/KcApp/kcContext.ts#L6-L13)
|
||||
- You should provide sample data for all the non standard value if you want to be able
|
||||
to debug the page outside of keycloak. [example](https://github.com/garronej/keycloakify-demo-app/blob/4eb2a9f63e9823e653b2d439495bda55e5ecc134/src/KcApp/kcContext.ts#L28-L43)
|
||||
|
||||
WARNING: If you chose to go this way use:
|
||||
|
||||
```json
|
||||
"dependencies": {
|
||||
"keycloakify": "~X.Y.Z"
|
||||
}
|
||||
```
|
||||
|
||||
### Hot reload
|
||||
|
||||
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 you can mock a given `kcContext`:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
KcApp,
|
||||
defaultKcProps,
|
||||
getKcContext
|
||||
} from "keycloakify";
|
||||
|
||||
const { kcContext } = getKcContext({
|
||||
"mockPageId": "login.ftl"
|
||||
});
|
||||
|
||||
reactDom.render(
|
||||
<KcApp
|
||||
kcContext={kcContextMocks.kcLoginContext}
|
||||
{...defaultKcProps}
|
||||
/>
|
||||
document.getElementById("root")
|
||||
);
|
||||
```
|
||||
|
||||
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)
|
||||
|
||||
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:
|
||||
|
||||
- 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) or in a `public/CNAME` file. [ex](https://github.com/garronej/keycloakify-demo-app/blob/main/public/CNAME).
|
||||
- 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)
|
||||
|
||||
# Email template customization.
|
||||
|
||||
_Introduced in [v4.8.0](https://github.com/InseeFrLab/keycloakify/releases/tag/v4.8.0)_
|
||||
|
||||
It is now possible to customize the emails sent to your users to confirm their email address ect.
|
||||
Just run `npx create-keycloak-theme-email-directory`, it will create a `keycloak_theme_email` directory
|
||||
at the root of your project.
|
||||
This directory should be tracked by Git (`yarn add -A`)
|
||||
You can start hacking the default template.
|
||||
When `npx build-keycloak-theme` (`yarn keycloak`) is run. If the directory `keycloak_theme_email` exists
|
||||
at the root of your project, it will be bundled into your `.jar` file and you will be able to select
|
||||
it [in the Keycloak administration pages](https://user-images.githubusercontent.com/6702424/164299589-75f8008b-b24e-4836-ad6b-72149bb55621.png).
|
||||
|
||||
# User profile and frontend form validation
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/InseeFrLab/keycloakify/releases/download/v0.0.1/keycloakify_fontend_validation.mp4">
|
||||
<img src="https://user-images.githubusercontent.com/6702424/138880146-6fef3280-c4a5-46d2-bbb3-8b9598c057a5.gif">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
NOTE: In reality the regexp used in this gif doesn't work server side, the regexp pattern should be `^[^@]@gmail\.com$` 😬.
|
||||
|
||||
User Profile is a Keycloak feature that enables to
|
||||
[define, from the admin console](https://user-images.githubusercontent.com/6702424/136872461-1f5b64ef-d2ef-4c6b-bb8d-07d4729552b3.png),
|
||||
what information you want to collect on your users in the register page and to validate inputs
|
||||
[**on the frontend**, in realtime](https://github.com/InseeFrLab/keycloakify/blob/6dca6a93d8cfe634ee4d8574ad0c091641220092/src/lib/getKcContext/KcContextBase.ts#L225-L261)!
|
||||
|
||||
NOTE: User profile is only available in Keycloak 15 and it's a beta feature that
|
||||
[needs to be enabled when launching keycloak](https://github.com/InseeFrLab/keycloakify/blob/59f106bf9e210b63b190826da2bf5f75fc8b7644/src/bin/build-keycloak-theme/build-keycloak-theme.ts#L116-L117)
|
||||
and [enabled in the console](https://user-images.githubusercontent.com/6702424/136874428-b071d614-c7f7-440d-9b2e-670faadc0871.png).
|
||||
|
||||
Keycloakify, in [`register-user-profile.ftl`](https://github.com/InseeFrLab/keycloakify/blob/main/src/lib/components/RegisterUserProfile.tsx),
|
||||
provides frontend validation out of the box.
|
||||
|
||||
For implementing your own `register-user-profile.ftl` page, you can use [`import { useFormValidationSlice } from "keycloakify";`](https://github.com/InseeFrLab/keycloakify/blob/main/src/lib/useFormValidationSlice.tsx).
|
||||
Find usage example [`here`](https://github.com/InseeFrLab/keycloakify/blob/d3a07edfcb3739e30032dc96fc2a55944dfc3387/src/lib/components/RegisterUserProfile.tsx#L79-L112).
|
||||
|
||||
As for right now [it's not possible to define a pattern for the password](https://keycloak.discourse.group/t/make-password-policies-available-to-freemarker/11632)
|
||||
from the admin console. You can however pass validators for it to the `useFormValidationSlice` function.
|
||||
|
||||
# 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:
|
||||

|
||||
|
||||
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 out of the box the most common user facing pages of Keycloak login.
|
||||
[Here](https://user-images.githubusercontent.com/6702424/116787906-227fe700-aaa7-11eb-92ee-22e7673717c2.png) is the complete list of pages (you get them after running `yarn test`)
|
||||
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 or if you need to implement some non standard `.ftl` pages please refer to [Advanced pages configuration](#advanced-pages-configuration).
|
||||
|
||||
# GitHub Actions
|
||||
|
||||

|
||||
|
||||
[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).
|
||||
|
||||
# Limitations
|
||||
|
||||
## `process.env.PUBLIC_URL` not supported.
|
||||
|
||||
You won't be able to [import things from your public directory **in your JavaScript code** (it's supported in `public/index.html`)](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.
|
||||
|
||||
### Possible workarounds
|
||||
|
||||
- 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/garronej/keycloakify-demo-app/blob/9aa2dbaec28a7786d6b2983c9a59d393dec1b2d6/public/index.html#L27-L73)
|
||||
(and the font are [here](https://github.com/garronej/keycloakify-demo-app/tree/main/public/fonts/WorkSans)).
|
||||
- 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)
|
||||
|
||||
If, before logging in, a user has selected a specific language
|
||||
you don't want it to be reset to default when the user gets redirected to
|
||||
the login or register pages.
|
||||
|
||||
Same goes for the dark mode, you don't want, if the user had it enabled
|
||||
to show the login page with light themes.
|
||||
|
||||
The problem is that you are probably using `localStorage` to persist theses values across
|
||||
reload but, as the Keycloak pages are not served on the same domain that the rest of your
|
||||
app you won't be able to carry over states using `localStorage`.
|
||||
|
||||
The only reliable solution is to inject parameters into the URL before
|
||||
redirecting to Keycloak. We integrate with
|
||||
[`keycloak-js`](https://github.com/keycloak/keycloak-documentation/blob/master/securing_apps/topics/oidc/javascript-adapter.adoc),
|
||||
by providing you a way to tell `keycloak-js` that you would like to inject
|
||||
some search parameters before redirecting.
|
||||
|
||||
The method also works with [`@react-keycloak/web`](https://www.npmjs.com/package/@react-keycloak/web) (use the `initOptions`).
|
||||
|
||||
You can implement your own mechanism to pass the states in the URL and
|
||||
restore it on the other side but we recommend using `powerhooks/useGlobalState`
|
||||
from the library [`powerhooks`](https://www.powerhooks.dev) that provide an elegant
|
||||
way to handle states such as `isDarkModeEnabled` or `selectedLanguage`.
|
||||
|
||||
Let's modify [the example](https://github.com/keycloak/keycloak-documentation/blob/master/securing_apps/topics/oidc/javascript-adapter.adoc) from the official `keycloak-js` documentation to
|
||||
enables the states of `useGlobalStates` to be injected in the URL before redirecting.
|
||||
Note that the states are automatically restored on the other side by `powerhooks`
|
||||
|
||||
```typescript
|
||||
import keycloak_js from "keycloak-js";
|
||||
import { injectGlobalStatesInSearchParams } from "powerhooks/useGlobalState";
|
||||
import { createKeycloakAdapter } from "keycloakify";
|
||||
|
||||
//...
|
||||
|
||||
const keycloakInstance = keycloak_js({
|
||||
"url": "http://keycloak-server/auth",
|
||||
"realm": "myrealm",
|
||||
"clientId": "myapp",
|
||||
});
|
||||
|
||||
keycloakInstance.init({
|
||||
"onLoad": "check-sso",
|
||||
"silentCheckSsoRedirectUri": window.location.origin + "/silent-check-sso.html",
|
||||
"adapter": createKeycloakAdapter({
|
||||
"transformUrlBeforeRedirect": injectGlobalStatesInSearchParams,
|
||||
keycloakInstance,
|
||||
}),
|
||||
});
|
||||
|
||||
//...
|
||||
```
|
||||
|
||||
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-web/blob/e1c1f309aaa3d5f860df39ba0b75cce89c88a9de/public/index.html#L117-L166) that you can place in your `public/index.html` if you are using `powerhooks/useGlobalState`.
|
||||
|
||||
# Kickstart video
|
||||
|
||||
_NOTE: keycloak-react-theming was renamed keycloakify since this video was recorded_
|
||||
[](https://youtu.be/xTz0Rj7i2v8)
|
||||
|
||||
# FTL errors related to `ftl_object_to_js_code_declaring_an_object` in Keycloak logs.
|
||||
|
||||
If you ever encounter one of these errors:
|
||||
|
||||
```log
|
||||
FTL stack trace ("~" means nesting-related):
|
||||
- Failed at: #local value = object[key] [in template "login.ftl" in macro "ftl_object_to_js_code_declaring_an_object" at line 70, column 21]
|
||||
- Reached through: @compress [in template "login.ftl" in macro "ftl_object_to_js_code_declaring_an_object" at line 36, column 5]
|
||||
- Reached through: @ftl_object_to_js_code_declaring_an_object object=value depth=(dep... [in template "login.ftl" in macro "ftl_object_to_js_code_declaring_an_object" at line 81, column 27]
|
||||
- Reached through: @compress [in template "login.ftl" in macro "ftl_object_to_js_code_declaring_an_object" at line 36, column 5]
|
||||
- Reached through: @ftl_object_to_js_code_declaring_an_object object=(.data_model) de... [in template "login.ftl" at line 163, column 43]
|
||||
```
|
||||
|
||||
It's just noise, they can be safely ignored.
|
||||
You can, however, and are encouraged to, report any that you would spot.
|
||||
Just open an issue about it and I will release a patched version of Keycloakify in the better delays.
|
||||
|
||||
# Adding custom message (to `i18n/useKcMessage.tsx`)
|
||||
|
||||
You can reproduce [this approach](https://github.com/garronej/keycloakify-demo-app/blob/main/src/kcMessagesExtension.ts)
|
||||
( don't forget to [evaluate the code](https://github.com/garronej/keycloakify-demo-app/blob/0a6d349dba89a5702f98ba48bca6c76ac7265e1f/src/index.tsx#L15) ).
|
||||
This approach is a bit hacky as it doesn't provide type safety but it works.
|
||||
|
||||
# Downloading builtin theme resource files
|
||||
|
||||
Running `npx download-builtin-keycloak-theme` will let you download the themes that comes by default with
|
||||
a Keycloak version of your choosing.
|
||||
|
||||
# Email domain whitelist
|
||||
|
||||
NOTE: This have been kind of deprecated by [user attribute](#user-profile-and-frontend-form-validation) you could
|
||||
use a pattern [like this one](https://github.com/InseeFrLab/onyxia-web/blob/f1206e0329b3b8d401ca7bffa95ca9c213cb190a/src/app/components/KcApp/kcContext.ts#L106) to whitelist email domains.
|
||||
|
||||
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.
|
||||
|
||||
# Changelog highlights
|
||||
|
||||
## v5.6.0
|
||||
|
||||
Add support for `login-config-totp.ftl` page [#127](https://github.com/InseeFrLab/keycloakify/pull/127).
|
||||
|
||||
## v5.3.0
|
||||
|
||||
Rename `keycloak_theme_email` to `keycloak_email`.
|
||||
If you already had a `keycloak_theme_email` you should rename it `keycloak_email`.
|
||||
|
||||
## v5.0.0
|
||||
|
||||
New i18n system. Import of terms and services have changed. [See example](https://github.com/garronej/keycloakify-demo-app/blob/a5b6a50f24bc25e082931f5ad9ebf47492acd12a/src/index.tsx#L46-L63).
|
||||
|
||||
## v4.10.0
|
||||
|
||||
Add `login-idp-link-email.ftl` page [See PR](https://github.com/InseeFrLab/keycloakify/pull/92).
|
||||
|
||||
## v4.8.0
|
||||
|
||||
[Email template customization.](#email-template-customization)
|
||||
|
||||
## v4.7.4
|
||||
|
||||
**M1 Mac** support (for testing locally with a dockerized Keycloak).
|
||||
|
20
package.json
20
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "keycloakify",
|
||||
"version": "4.8.0",
|
||||
"version": "5.6.0",
|
||||
"description": "Keycloak theme generator for Reacts app",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -22,7 +22,7 @@
|
||||
},
|
||||
"bin": {
|
||||
"build-keycloak-theme": "dist/bin/build-keycloak-theme/index.js",
|
||||
"create-keycloak-theme-email-directory": "dist/bin/create-keycloak-theme-email-directory.js",
|
||||
"create-keycloak-email-directory": "dist/bin/create-keycloak-email-directory.js",
|
||||
"download-builtin-keycloak-theme": "dist/bin/download-builtin-keycloak-theme.js"
|
||||
},
|
||||
"lint-staged": {
|
||||
@ -57,18 +57,19 @@
|
||||
"homepage": "https://github.com/garronej/keycloakify",
|
||||
"peerDependencies": {
|
||||
"@emotion/react": "^11.4.1",
|
||||
"react": "^16.8.0 || ^17.0.0"
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@emotion/react": "^11.4.1",
|
||||
"@types/memoizee": "^0.4.7",
|
||||
"@types/node": "^17.0.25",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react": "18.0.9",
|
||||
"copyfiles": "^2.4.1",
|
||||
"husky": "^4.3.8",
|
||||
"lint-staged": "^11.0.0",
|
||||
"prettier": "^2.3.0",
|
||||
"properties-parser": "^0.3.1",
|
||||
"react": "^17.0.1",
|
||||
"react": "18.1.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.2.3"
|
||||
},
|
||||
@ -76,13 +77,14 @@
|
||||
"@octokit/rest": "^18.12.0",
|
||||
"cheerio": "^1.0.0-rc.5",
|
||||
"cli-select": "^1.1.2",
|
||||
"evt": "2.0.0-beta.39",
|
||||
"evt": "2.0.0-beta.44",
|
||||
"memoizee": "^0.4.15",
|
||||
"minimal-polyfills": "^2.2.1",
|
||||
"path-browserify": "^1.0.1",
|
||||
"powerhooks": "^0.14.0",
|
||||
"powerhooks": "^0.20.1",
|
||||
"react-markdown": "^5.0.3",
|
||||
"scripting-tools": "^0.19.13",
|
||||
"tsafe": "^0.9.0",
|
||||
"tss-react": "^3.5.2"
|
||||
"tsafe": "^0.10.0",
|
||||
"tss-react": "^3.7.0"
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ const doUseExternalAssets = process.argv[2]?.toLowerCase() === "--external-asset
|
||||
const parsedPackageJson: ParsedPackageJson = require(pathJoin(reactProjectDirPath, "package.json"));
|
||||
|
||||
export const keycloakThemeBuildingDirPath = pathJoin(reactProjectDirPath, "build_keycloak");
|
||||
export const keycloakThemeEmailDirPath = pathJoin(keycloakThemeBuildingDirPath, "..", "keycloak_theme_email");
|
||||
export const keycloakThemeEmailDirPath = pathJoin(keycloakThemeBuildingDirPath, "..", "keycloak_email");
|
||||
|
||||
function sanitizeThemeName(name: string) {
|
||||
return name
|
||||
@ -91,20 +91,23 @@ export function main() {
|
||||
"cwd": keycloakThemeBuildingDirPath,
|
||||
});
|
||||
|
||||
//We want, however to test in a container running the latest Keycloak version
|
||||
const containerKeycloakVersion = "18.0.0";
|
||||
|
||||
generateStartKeycloakTestingContainer({
|
||||
keycloakThemeBuildingDirPath,
|
||||
themeName,
|
||||
//We want, however to test in a container running the latest Keycloak version
|
||||
"keycloakVersion": "17.0.1",
|
||||
"keycloakVersion": containerKeycloakVersion,
|
||||
});
|
||||
|
||||
console.log(
|
||||
[
|
||||
"",
|
||||
`✅ Your keycloak theme has been generated and bundled into ./${pathRelative(reactProjectDirPath, jarFilePath)} 🚀`,
|
||||
`It is to be placed in "/opt/jboss/keycloak/standalone/deployments" in the container running a jboss/keycloak Docker image.`,
|
||||
`It is to be placed in "/opt/keycloak/providers" in the container running a quay.io/keycloak/keycloak Docker image.`,
|
||||
"",
|
||||
"Using Helm (https://github.com/codecentric/helm-charts), edit to reflect:",
|
||||
//TODO: Restore when we find a good Helm chart for Keycloak.
|
||||
//"Using Helm (https://github.com/codecentric/helm-charts), edit to reflect:",
|
||||
"",
|
||||
"value.yaml: ",
|
||||
" extraInitContainers: |",
|
||||
@ -122,7 +125,7 @@ export function main() {
|
||||
" ",
|
||||
" extraVolumeMounts: |",
|
||||
" - name: extensions",
|
||||
" mountPath: /opt/jboss/keycloak/standalone/deployments",
|
||||
" mountPath: /opt/keycloak/providers",
|
||||
" extraEnv: |",
|
||||
" - name: KEYCLOAK_USER",
|
||||
" value: admin",
|
||||
@ -132,14 +135,16 @@ export function main() {
|
||||
" value: -Dkeycloak.profile=preview",
|
||||
"",
|
||||
"",
|
||||
"To test your theme locally, with hot reloading, you can spin up a Keycloak container image with the theme loaded by running:",
|
||||
`To test your theme locally you can spin up a Keycloak ${containerKeycloakVersion} container image with the theme pre loaded by running:`,
|
||||
"",
|
||||
`👉 $ ./${pathRelative(reactProjectDirPath, pathJoin(keycloakThemeBuildingDirPath, generateStartKeycloakTestingContainer.basename))} 👈`,
|
||||
"",
|
||||
"Test with different Keycloak versions by editing the .sh file. see available versions here: https://quay.io/repository/keycloak/keycloak?tab=tags",
|
||||
"",
|
||||
"Once your container is up and running: ",
|
||||
"- Log into the admin console 👉 http://localhost:8080/admin username: admin, password: admin 👈",
|
||||
'- Create a realm named "myrealm"',
|
||||
'- Create a client with id "myclient" and root url: "https://www.keycloak.org/app/"',
|
||||
'- Create a client with ID: "myclient", "Root URL": "https://www.keycloak.org/app/" and "Valid redirect URIs": "https://www.keycloak.org/app/*"',
|
||||
`- Select Login Theme: ${themeName} (don't forget to save at the bottom of the page)`,
|
||||
`- Go to 👉 https://www.keycloak.org/app/ 👈 Click "Save" then "Sign in". You should see your login page`,
|
||||
"",
|
||||
|
@ -122,10 +122,13 @@ ${ftl_object_to_js_code_declaring_an_object(.data_model, [])?no_esc};
|
||||
key == "updateProfileCtx" &&
|
||||
are_same_path(path, [])
|
||||
) || (
|
||||
<#-- https://github.com/InseeFrLab/keycloakify/pull/65#issuecomment-991896344 -->
|
||||
<#-- https://github.com/InseeFrLab/keycloakify/pull/65#issuecomment-991896344 (reports with saml-post-form.ftl) -->
|
||||
<#-- https://github.com/InseeFrLab/keycloakify/issues/91#issue-1212319466 (reports with error.ftl and Kc18) -->
|
||||
<#-- https://github.com/InseeFrLab/keycloakify/issues/109#issuecomment-1134610163 -->
|
||||
key == "loginAction" &&
|
||||
are_same_path(path, ["url"]) &&
|
||||
pageId == "saml-post-form.ftl"
|
||||
["saml-post-form.ftl", "error.ftl", "info.ftl"]?seq_contains(pageId) &&
|
||||
!(auth?has_content && auth.showTryAnotherWayLink())
|
||||
) || (
|
||||
["contextData", "idpConfig", "idp", "authenticationSession"]?seq_contains(key) &&
|
||||
are_same_path(path, ["brokerContext"]) &&
|
||||
@ -151,7 +154,7 @@ ${ftl_object_to_js_code_declaring_an_object(.data_model, [])?no_esc};
|
||||
</#attempt>
|
||||
|
||||
</#if>
|
||||
|
||||
|
||||
<#attempt>
|
||||
<#if !object[key]??>
|
||||
<#continue>
|
||||
@ -199,6 +202,31 @@ ${ftl_object_to_js_code_declaring_an_object(.data_model, [])?no_esc};
|
||||
</#attempt>
|
||||
|
||||
<#if isMethod>
|
||||
|
||||
<#if are_same_path(path, ["auth", "showUsername"])>
|
||||
<#attempt>
|
||||
<#return auth.showUsername()?c>
|
||||
<#recover>
|
||||
<#return "ABORT: Couldn't evaluate auth.showUsername()">
|
||||
</#attempt>
|
||||
</#if>
|
||||
|
||||
<#if are_same_path(path, ["auth", "showResetCredentials"])>
|
||||
<#attempt>
|
||||
<#return auth.showResetCredentials()?c>
|
||||
<#recover>
|
||||
<#return "ABORT: Couldn't evaluate auth.showResetCredentials()">
|
||||
</#attempt>
|
||||
</#if>
|
||||
|
||||
<#if are_same_path(path, ["auth", "showTryAnotherWayLink"])>
|
||||
<#attempt>
|
||||
<#return auth.showTryAnotherWayLink()?c>
|
||||
<#recover>
|
||||
<#return "ABORT: Couldn't evaluate auth.showTryAnotherWayLink()">
|
||||
</#attempt>
|
||||
</#if>
|
||||
|
||||
<#return "ABORT: It's a method">
|
||||
</#if>
|
||||
|
||||
|
@ -18,7 +18,9 @@ export const pageIds = [
|
||||
"login-update-profile.ftl",
|
||||
"login-update-password.ftl",
|
||||
"login-idp-link-confirm.ftl",
|
||||
"login-idp-link-email.ftl",
|
||||
"login-page-expired.ftl",
|
||||
"login-config-totp.ftl",
|
||||
] as const;
|
||||
|
||||
export type PageId = typeof pageIds[number];
|
||||
|
@ -88,7 +88,7 @@ export function generateKeycloakThemeResources(params: {
|
||||
console.log(
|
||||
[
|
||||
`Not bundling email template because ${pathBasename(keycloakThemeEmailDirPath)} does not exist`,
|
||||
`To start customizing the email template, run: 👉 npx create-keycloak-theme-email-directory 👈`,
|
||||
`To start customizing the email template, run: 👉 npx create-keycloak-email-directory 👈`,
|
||||
].join("\n"),
|
||||
);
|
||||
doBundleEmailTemplate = false;
|
||||
|
@ -17,12 +17,12 @@ export function replaceImportsFromStaticInJsCode(params: { jsCode: string; urlOr
|
||||
const { jsCode, urlOrigin } = params;
|
||||
|
||||
const fixedJsCode = jsCode
|
||||
.replace(/([a-z]+\.[a-z]+)\+"static\//g, (...[, group]) =>
|
||||
.replace(/([a-zA-Z]+\.[a-zA-Z]+)\+"static\//g, (...[, group]) =>
|
||||
urlOrigin === undefined
|
||||
? `window.${ftlValuesGlobalName}.url.resourcesPath + "/build/static/`
|
||||
: `("${ftlValuesGlobalName}" in window ? "${urlOrigin}" : "") + ${group} + "static/`,
|
||||
)
|
||||
.replace(/".chunk.css",([a-z])+=([a-z]+\.[a-z]+)\+([a-z]+),/, (...[, group1, group2, group3]) =>
|
||||
.replace(/".chunk.css",([a-zA-Z])+=([a-zA-Z]+\.[a-zA-Z]+)\+([a-zA-Z]+),/, (...[, group1, group2, group3]) =>
|
||||
urlOrigin === undefined
|
||||
? `".chunk.css",${group1} = window.${ftlValuesGlobalName}.url.resourcesPath + "/build/" + ${group3},`
|
||||
: `".chunk.css",${group1} = ("${ftlValuesGlobalName}" in window ? "${urlOrigin}" : "") + ${group2} + ${group3},`,
|
||||
|
@ -1,3 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { downloadBuiltinKeycloakTheme } from "./download-builtin-keycloak-theme";
|
||||
import { keycloakThemeEmailDirPath } from "./build-keycloak-theme";
|
||||
import { join as pathJoin, basename as pathBasename } from "path";
|
@ -9,7 +9,7 @@ import { rm_rf, rm_r } from "./tools/rm";
|
||||
//@ts-ignore
|
||||
const propertiesParser = require("properties-parser");
|
||||
|
||||
for (const keycloakVersion of ["11.0.3", "15.0.2", "16.1.0"]) {
|
||||
for (const keycloakVersion of ["11.0.3", "15.0.2", "18.0.1"]) {
|
||||
console.log({ keycloakVersion });
|
||||
|
||||
const tmpDirPath = pathJoin(getProjectRoot(), "tmp_xImOef9dOd44");
|
||||
|
@ -60,7 +60,7 @@ const execYarnLink = (params: { targetModuleName?: string; cwd: string }) => {
|
||||
});
|
||||
};
|
||||
|
||||
const testAppNames = ["keycloakify-demo-app"] as const;
|
||||
const testAppNames = [process.argv[2] ?? "keycloakify-demo-app"] as const;
|
||||
|
||||
const getTestAppPath = (testAppName: typeof testAppNames[number]) => pathJoin(keycloakifyDirPath, "..", testAppName);
|
||||
|
||||
|
@ -19,12 +19,15 @@ export async function promptKeycloakVersion() {
|
||||
|
||||
console.log("Initialize the directory with email template from which keycloak version?");
|
||||
|
||||
const tags = await getLatestsSemVersionedTag({
|
||||
"count": 15,
|
||||
"doIgnoreBeta": true,
|
||||
"owner": "keycloak",
|
||||
"repo": "keycloak",
|
||||
}).then(arr => arr.map(({ tag }) => tag));
|
||||
const tags = [
|
||||
...(await getLatestsSemVersionedTag({
|
||||
"count": 10,
|
||||
"doIgnoreBeta": true,
|
||||
"owner": "keycloak",
|
||||
"repo": "keycloak",
|
||||
}).then(arr => arr.map(({ tag }) => tag))),
|
||||
"11.0.3",
|
||||
];
|
||||
|
||||
if (process.env["GITHUB_ACTIONS"] === "true") {
|
||||
return { "keycloakVersion": tags[0] };
|
||||
|
@ -1,7 +0,0 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
export function createOctokit(params: { github_token: string }) {
|
||||
const { github_token } = params;
|
||||
|
||||
return new Octokit({ ...(github_token !== "" ? { "auth": github_token } : {}) });
|
||||
}
|
@ -2,10 +2,10 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
|
||||
export const Error = memo(({ kcContext, ...props }: { kcContext: KcContextBase.Error } & KcProps) => {
|
||||
const { msg } = useKcMessage();
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
const { message, client } = kcContext;
|
||||
|
||||
|
@ -3,10 +3,10 @@ import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import { assert } from "../tools/assert";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
|
||||
export const Info = memo(({ kcContext, ...props }: { kcContext: KcContextBase.Info } & KcProps) => {
|
||||
const { msg } = useKcMessage();
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
assert(kcContext.message !== undefined);
|
||||
|
||||
|
@ -14,6 +14,8 @@ import { LoginUpdatePassword } from "./LoginUpdatePassword";
|
||||
import { LoginUpdateProfile } from "./LoginUpdateProfile";
|
||||
import { LoginIdpLinkConfirm } from "./LoginIdpLinkConfirm";
|
||||
import { LoginPageExpired } from "./LoginPageExpired";
|
||||
import { LoginIdpLinkEmail } from "./LoginIdpLinkEmail";
|
||||
import { LoginConfigTotp } from "./LoginConfigTotp";
|
||||
|
||||
export const KcApp = memo(({ kcContext, ...props }: { kcContext: KcContextBase } & KcProps) => {
|
||||
switch (kcContext.pageId) {
|
||||
@ -41,7 +43,11 @@ export const KcApp = memo(({ kcContext, ...props }: { kcContext: KcContextBase }
|
||||
return <LoginUpdateProfile {...{ kcContext, ...props }} />;
|
||||
case "login-idp-link-confirm.ftl":
|
||||
return <LoginIdpLinkConfirm {...{ kcContext, ...props }} />;
|
||||
case "login-idp-link-email.ftl":
|
||||
return <LoginIdpLinkEmail {...{ kcContext, ...props }} />;
|
||||
case "login-page-expired.ftl":
|
||||
return <LoginPageExpired {...{ kcContext, ...props }} />;
|
||||
case "login-config-totp.ftl":
|
||||
return <LoginConfigTotp {...{ kcContext, ...props }} />;
|
||||
}
|
||||
});
|
||||
|
@ -2,7 +2,7 @@ import { useState, memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
import { useConstCallback } from "powerhooks/useConstCallback";
|
||||
import type { FormEventHandler } from "react";
|
||||
@ -10,7 +10,7 @@ import type { FormEventHandler } from "react";
|
||||
export const Login = memo(({ kcContext, ...props }: { kcContext: KcContextBase.Login } & KcProps) => {
|
||||
const { social, realm, url, usernameEditDisabled, login, auth, registrationDisabled } = kcContext;
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
|
183
src/lib/components/LoginConfigTotp.tsx
Normal file
183
src/lib/components/LoginConfigTotp.tsx
Normal file
@ -0,0 +1,183 @@
|
||||
import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
|
||||
export const LoginConfigTotp = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginConfigTotp } & KcProps) => {
|
||||
const { url, isAppInitiatedAction, totp, mode, messagesPerField } = kcContext;
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
const algToKeyUriAlg: Record<KcContextBase.LoginConfigTotp["totp"]["policy"]["algorithm"], string> = {
|
||||
HmacSHA1: "SHA1",
|
||||
HmacSHA256: "SHA256",
|
||||
HmacSHA512: "SHA512",
|
||||
};
|
||||
|
||||
return (
|
||||
<Template
|
||||
{...{ kcContext, ...props }}
|
||||
doFetchDefaultThemeResources={true}
|
||||
headerNode={msg("loginTotpTitle")}
|
||||
formNode={
|
||||
<>
|
||||
<ol id="kc-totp-settings">
|
||||
<li>
|
||||
<p>{msg("loginTotpStep1")}</p>
|
||||
|
||||
<ul id="kc-totp-supported-apps">
|
||||
{totp.policy.supportedApplications.map(app => (
|
||||
<li>{app}</li>
|
||||
))}
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
{mode && mode == "manual" ? (
|
||||
<>
|
||||
<li>
|
||||
<p>{msg("loginTotpManualStep2")}</p>
|
||||
<p>
|
||||
<span id="kc-totp-secret-key">{totp.totpSecretEncoded}</span>
|
||||
</p>
|
||||
<p>
|
||||
<a href={totp.qrUrl} id="mode-barcode">
|
||||
{msg("loginTotpScanBarcode")}
|
||||
</a>
|
||||
</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>{msg("loginTotpManualStep3")}</p>
|
||||
<p>
|
||||
<ul>
|
||||
<li id="kc-totp-type">
|
||||
{msg("loginTotpType")}: {msg(`loginTotp.${totp.policy.type}`)}
|
||||
</li>
|
||||
<li id="kc-totp-algorithm">
|
||||
{msg("loginTotpAlgorithm")}: {algToKeyUriAlg?.[totp.policy.algorithm] ?? totp.policy.algorithm}
|
||||
</li>
|
||||
<li id="kc-totp-digits">
|
||||
{msg("loginTotpDigits")}: {totp.policy.digits}
|
||||
</li>
|
||||
{totp.policy.type === "totp" ? (
|
||||
<li id="kc-totp-period">
|
||||
{msg("loginTotpInterval")}: {totp.policy.period}
|
||||
</li>
|
||||
) : (
|
||||
<li id="kc-totp-counter">
|
||||
{msg("loginTotpCounter")}: {totp.policy.initialCounter}
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</p>
|
||||
</li>
|
||||
</>
|
||||
) : (
|
||||
<li>
|
||||
<p>{msg("loginTotpStep2")}</p>
|
||||
<img id="kc-totp-secret-qr-code" src={`data:image/png;base64, ${totp.totpSecretQrCode}`} alt="Figure: Barcode" />
|
||||
<br />
|
||||
<p>
|
||||
<a href={totp.manualUrl} id="mode-manual">
|
||||
{msg("loginTotpUnableToScan")}
|
||||
</a>
|
||||
</p>
|
||||
</li>
|
||||
)}
|
||||
<li>
|
||||
<p>{msg("loginTotpStep3")}</p>
|
||||
<p>{msg("loginTotpStep3DeviceName")}</p>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<form action={url.loginAction} className={cx(props.kcFormClass)} id="kc-totp-settings-form" method="post">
|
||||
<div className={cx(props.kcFormGroupClass)}>
|
||||
<div className={cx(props.kcInputWrapperClass)}>
|
||||
<label htmlFor="totp" className={cx(props.kcLabelClass)}>
|
||||
{msg("authenticatorCode")}
|
||||
</label>{" "}
|
||||
<span className="required">*</span>
|
||||
</div>
|
||||
<div className={cx(props.kcInputWrapperClass)}>
|
||||
<input
|
||||
type="text"
|
||||
id="totp"
|
||||
name="totp"
|
||||
autoComplete="off"
|
||||
className={cx(props.kcInputClass)}
|
||||
aria-invalid={messagesPerField.existsError("totp")}
|
||||
/>
|
||||
|
||||
{messagesPerField.existsError("totp") && (
|
||||
<span id="input-error-otp-code" className={cx(props.kcInputErrorMessageClass)} aria-live="polite">
|
||||
{messagesPerField.get("totp")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<input type="hidden" id="totpSecret" name="totpSecret" value={totp.totpSecret} />
|
||||
{mode && <input type="hidden" id="mode" value={mode} />}
|
||||
</div>
|
||||
|
||||
<div className={cx(props.kcFormGroupClass)}>
|
||||
<div className={cx(props.kcInputWrapperClass)}>
|
||||
<label htmlFor="userLabel" className={cx(props.kcLabelClass)}>
|
||||
{msg("loginTotpDeviceName")}
|
||||
</label>{" "}
|
||||
{totp.otpCredentials.length >= 1 && <span className="required">*</span>}
|
||||
</div>
|
||||
<div className={cx(props.kcInputWrapperClass)}>
|
||||
<input
|
||||
type="text"
|
||||
id="userLabel"
|
||||
name="userLabel"
|
||||
autoComplete="off"
|
||||
className={cx(props.kcInputClass)}
|
||||
aria-invalid={messagesPerField.existsError("userLabel")}
|
||||
/>
|
||||
{messagesPerField.existsError("userLabel") && (
|
||||
<span id="input-error-otp-label" className={cx(props.kcInputErrorMessageClass)} aria-live="polite">
|
||||
{messagesPerField.get("userLabel")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isAppInitiatedAction ? (
|
||||
<>
|
||||
<input
|
||||
type="submit"
|
||||
className={cx(props.kcButtonClass, props.kcButtonPrimaryClass, props.kcButtonLargeClass)}
|
||||
id="saveTOTPBtn"
|
||||
value={msgStr("doSubmit")}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className={cx(
|
||||
props.kcButtonClass,
|
||||
props.kcButtonDefaultClass,
|
||||
props.kcButtonLargeClass,
|
||||
props.kcButtonLargeClass,
|
||||
)}
|
||||
id="cancelTOTPBtn"
|
||||
name="cancel-aia"
|
||||
value="true"
|
||||
>
|
||||
${msg("doCancel")}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<input
|
||||
type="submit"
|
||||
className={cx(props.kcButtonClass, props.kcButtonPrimaryClass, props.kcButtonLargeClass)}
|
||||
id="saveTOTPBtn"
|
||||
value={msgStr("doSubmit")}
|
||||
/>
|
||||
)}
|
||||
</form>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
});
|
@ -2,13 +2,13 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
|
||||
export const LoginIdpLinkConfirm = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginIdpLinkConfirm } & KcProps) => {
|
||||
const { url, idpAlias } = kcContext;
|
||||
|
||||
const { msg } = useKcMessage();
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
|
32
src/lib/components/LoginIdpLinkEmail.tsx
Normal file
32
src/lib/components/LoginIdpLinkEmail.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { getMsg } from "../i18n";
|
||||
|
||||
export const LoginIdpLinkEmail = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginIdpLinkEmail } & KcProps) => {
|
||||
const { url, realm, brokerContext, idpAlias } = kcContext;
|
||||
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
return (
|
||||
<Template
|
||||
{...{ kcContext, ...props }}
|
||||
doFetchDefaultThemeResources={true}
|
||||
headerNode={msg("emailLinkIdpTitle", idpAlias)}
|
||||
formNode={
|
||||
<>
|
||||
<p id="instruction1" className="instruction">
|
||||
{msg("emailLinkIdp1", idpAlias, brokerContext.username, realm.displayName)}
|
||||
</p>
|
||||
<p id="instruction2" className="instruction">
|
||||
{msg("emailLinkIdp2")} <a href={url.loginAction}>{msg("doClickHere")}</a> {msg("emailLinkIdp3")}
|
||||
</p>
|
||||
<p id="instruction3" className="instruction">
|
||||
{msg("emailLinkIdp4")} <a href={url.loginAction}>{msg("doClickHere")}</a> {msg("emailLinkIdp5")}
|
||||
</p>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
});
|
@ -2,7 +2,7 @@ import { useEffect, memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { headInsert } from "../tools/headInsert";
|
||||
import { pathJoin } from "../tools/pathJoin";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
@ -12,7 +12,7 @@ export const LoginOtp = memo(({ kcContext, ...props }: { kcContext: KcContextBas
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
useEffect(() => {
|
||||
let isCleanedUp = false;
|
||||
|
@ -2,12 +2,12 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
|
||||
export const LoginPageExpired = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginPageExpired } & KcProps) => {
|
||||
const { url } = kcContext;
|
||||
|
||||
const { msg } = useKcMessage();
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
return (
|
||||
<Template
|
||||
|
@ -2,13 +2,13 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
|
||||
export const LoginResetPassword = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginResetPassword } & KcProps) => {
|
||||
const { url, realm, auth } = kcContext;
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
|
@ -2,13 +2,13 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
|
||||
export const LoginUpdatePassword = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginUpdatePassword } & KcProps) => {
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { url, messagesPerField, isAppInitiatedAction, username } = kcContext;
|
||||
|
||||
|
@ -2,13 +2,13 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
|
||||
export const LoginUpdateProfile = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginUpdateProfile } & KcProps) => {
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { url, user, messagesPerField, isAppInitiatedAction } = kcContext;
|
||||
|
||||
|
@ -2,10 +2,10 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
|
||||
export const LoginVerifyEmail = memo(({ kcContext, ...props }: { kcContext: KcContextBase.LoginVerifyEmail } & KcProps) => {
|
||||
const { msg } = useKcMessage();
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
const { url } = kcContext;
|
||||
|
||||
|
@ -2,13 +2,13 @@ import { memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
|
||||
export const Register = memo(({ kcContext, ...props }: { kcContext: KcContextBase.Register } & KcProps) => {
|
||||
const { url, messagesPerField, register, realm, passwordRequired, recaptchaRequired, recaptchaSiteKey } = kcContext;
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
|
@ -2,7 +2,7 @@ import { useMemo, memo, useEffect, useState, Fragment } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase, Attribute } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
import type { ReactComponent } from "../tools/ReactComponent";
|
||||
import { useCallbackFactory } from "powerhooks/useCallbackFactory";
|
||||
@ -11,7 +11,7 @@ import { useFormValidationSlice } from "../useFormValidationSlice";
|
||||
export const RegisterUserProfile = memo(({ kcContext, ...props_ }: { kcContext: KcContextBase.RegisterUserProfile } & KcProps) => {
|
||||
const { url, messagesPerField, recaptchaRequired, recaptchaSiteKey } = kcContext;
|
||||
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { cx, css } = useCssAndCx();
|
||||
|
||||
@ -74,7 +74,7 @@ type UserProfileFormFieldsProps = { kcContext: KcContextBase.RegisterUserProfile
|
||||
const UserProfileFormFields = memo(({ kcContext, onIsFormSubmittableValueChange, ...props }: UserProfileFormFieldsProps) => {
|
||||
const { cx, css } = useCssAndCx();
|
||||
|
||||
const { advancedMsg } = useKcMessage();
|
||||
const { advancedMsg } = getMsg(kcContext);
|
||||
|
||||
const {
|
||||
formValidationState: { fieldStateByAttributeName, isFormSubmittable },
|
||||
|
@ -1,12 +1,9 @@
|
||||
import { useReducer, useEffect, memo } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { useKcLanguageTag } from "../i18n/useKcLanguageTag";
|
||||
import { getMsg, getCurrentKcLanguageTag, changeLocale, getTagLabel } from "../i18n";
|
||||
import type { KcLanguageTag } from "../i18n";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { assert } from "../tools/assert";
|
||||
import type { KcLanguageTag } from "../i18n/KcLanguageTag";
|
||||
import { getBestMatchAmongKcLanguageTag } from "../i18n/KcLanguageTag";
|
||||
import { getKcLanguageTagLabel } from "../i18n/KcLanguageTag";
|
||||
import { useCallbackFactory } from "powerhooks/useCallbackFactory";
|
||||
import { headInsert } from "../tools/headInsert";
|
||||
import { pathJoin } from "../tools/pathJoin";
|
||||
@ -51,36 +48,19 @@ export const Template = memo((props: TemplateProps) => {
|
||||
console.log("Rendering this page with react using keycloakify");
|
||||
}, []);
|
||||
|
||||
const { msg } = useKcMessage();
|
||||
const { msg } = getMsg(kcContext);
|
||||
|
||||
const { kcLanguageTag, setKcLanguageTag } = useKcLanguageTag();
|
||||
|
||||
const onChangeLanguageClickFactory = useCallbackFactory(([languageTag]: [KcLanguageTag]) => setKcLanguageTag(languageTag));
|
||||
const onChangeLanguageClickFactory = useCallbackFactory(([kcLanguageTag]: [KcLanguageTag]) =>
|
||||
changeLocale({
|
||||
kcContext,
|
||||
kcLanguageTag,
|
||||
}),
|
||||
);
|
||||
|
||||
const onTryAnotherWayClick = useConstCallback(() => (document.forms["kc-select-try-another-way-form" as never].submit(), false));
|
||||
|
||||
const { realm, locale, auth, url, message, isAppInitiatedAction } = kcContext;
|
||||
|
||||
useEffect(() => {
|
||||
if (!realm.internationalizationEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
assert(locale !== undefined);
|
||||
|
||||
const kcContext_kcLanguageTag = getBestMatchAmongKcLanguageTag(locale.current);
|
||||
|
||||
if (["error.ftl", "info.ftl", "login-page-expired.ftl"].indexOf(kcContext.pageId) >= 0) {
|
||||
setKcLanguageTag(kcContext_kcLanguageTag);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (kcLanguageTag !== kcContext_kcLanguageTag) {
|
||||
window.location.href = locale.supported.find(({ languageTag }) => languageTag === kcLanguageTag)!.url;
|
||||
}
|
||||
}, [kcLanguageTag]);
|
||||
|
||||
const [isExtraCssLoaded, setExtraCssLoaded] = useReducer(() => true, false);
|
||||
|
||||
useEffect(() => {
|
||||
@ -158,13 +138,13 @@ export const Template = memo((props: TemplateProps) => {
|
||||
<div id="kc-locale-wrapper" className={cx(props.kcLocaleWrapperClass)}>
|
||||
<div className="kc-dropdown" id="kc-locale-dropdown">
|
||||
<a href="#" id="kc-current-locale-link">
|
||||
{getKcLanguageTagLabel(kcLanguageTag)}
|
||||
{getTagLabel({ "kcLanguageTag": getCurrentKcLanguageTag(kcContext), kcContext })}
|
||||
</a>
|
||||
<ul>
|
||||
{locale.supported.map(({ languageTag }) => (
|
||||
<li key={languageTag} className="kc-dropdown-item">
|
||||
<a href="#" onClick={onChangeLanguageClickFactory(languageTag)}>
|
||||
{getKcLanguageTagLabel(languageTag)}
|
||||
{getTagLabel({ "kcLanguageTag": languageTag, kcContext })}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
|
@ -1,12 +1,33 @@
|
||||
import { memo } from "react";
|
||||
import { useReducer, useEffect, memo } from "react";
|
||||
import { Template } from "./Template";
|
||||
import type { KcProps } from "./KcProps";
|
||||
import type { KcContextBase } from "../getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "../i18n/useKcMessage";
|
||||
import { getMsg } from "../i18n";
|
||||
import { useCssAndCx } from "tss-react";
|
||||
import { kcMessages, getCurrentKcLanguageTag } from "../i18n";
|
||||
import type { KcLanguageTag } from "../i18n";
|
||||
|
||||
/** Allow to avoid bundling the terms and download it on demand*/
|
||||
export function useDownloadTerms(params: {
|
||||
kcContext: KcContextBase;
|
||||
downloadTermMarkdown: (params: { currentKcLanguageTag: KcLanguageTag }) => Promise<string>;
|
||||
}) {
|
||||
const { kcContext, downloadTermMarkdown } = params;
|
||||
|
||||
const [, forceUpdate] = useReducer(x => x + 1, 0);
|
||||
|
||||
useEffect(() => {
|
||||
const currentKcLanguageTag = getCurrentKcLanguageTag(kcContext);
|
||||
|
||||
downloadTermMarkdown({ currentKcLanguageTag }).then(thermMarkdown => {
|
||||
kcMessages[currentKcLanguageTag].termsText = thermMarkdown;
|
||||
forceUpdate();
|
||||
});
|
||||
}, []);
|
||||
}
|
||||
|
||||
export const Terms = memo(({ kcContext, ...props }: { kcContext: KcContextBase.Terms } & KcProps) => {
|
||||
const { msg, msgStr } = useKcMessage();
|
||||
const { msg, msgStr } = getMsg(kcContext);
|
||||
|
||||
const { cx } = useCssAndCx();
|
||||
|
||||
|
@ -1,9 +1,8 @@
|
||||
import type { PageId } from "../../bin/build-keycloak-theme/generateFtl";
|
||||
import type { KcLanguageTag } from "../i18n/KcLanguageTag";
|
||||
import type { KcLanguageTag } from "../i18n";
|
||||
import { assert } from "tsafe/assert";
|
||||
import type { Equals } from "tsafe";
|
||||
import type { MessageKey } from "../i18n/useKcMessage";
|
||||
import type { LanguageLabel } from "../i18n/KcLanguageTag";
|
||||
import type { MessageKey } from "../i18n";
|
||||
|
||||
type ExtractAfterStartingWith<Prefix extends string, StrEnum> = StrEnum extends `${Prefix}${infer U}` ? U : never;
|
||||
|
||||
@ -24,7 +23,9 @@ export type KcContextBase =
|
||||
| KcContextBase.LoginUpdatePassword
|
||||
| KcContextBase.LoginUpdateProfile
|
||||
| KcContextBase.LoginIdpLinkConfirm
|
||||
| KcContextBase.LoginPageExpired;
|
||||
| KcContextBase.LoginIdpLinkEmail
|
||||
| KcContextBase.LoginPageExpired
|
||||
| KcContextBase.LoginConfigTotp;
|
||||
|
||||
export declare namespace KcContextBase {
|
||||
export type Common = {
|
||||
@ -46,18 +47,15 @@ export declare namespace KcContextBase {
|
||||
locale?: {
|
||||
supported: {
|
||||
url: string;
|
||||
label: string;
|
||||
languageTag: KcLanguageTag;
|
||||
/** Is determined by languageTag. Ex: languageTag === "en" => label === "English"
|
||||
* or getLanguageLabel(languageTag) === label
|
||||
*/
|
||||
//label: LanguageLabel;
|
||||
}[];
|
||||
current: LanguageLabel;
|
||||
currentLanguageTag: KcLanguageTag;
|
||||
};
|
||||
auth?: {
|
||||
showUsername: boolean;
|
||||
showResetCredentials: boolean;
|
||||
showTryAnotherWayLink: boolean;
|
||||
showUsername?: boolean;
|
||||
showResetCredentials?: boolean;
|
||||
showTryAnotherWayLink?: boolean;
|
||||
attemptedUsername?: string;
|
||||
};
|
||||
scripts: string[];
|
||||
@ -215,9 +213,45 @@ export declare namespace KcContextBase {
|
||||
idpAlias: string;
|
||||
};
|
||||
|
||||
export type LoginIdpLinkEmail = Common & {
|
||||
pageId: "login-idp-link-email.ftl";
|
||||
brokerContext: {
|
||||
username: string;
|
||||
};
|
||||
idpAlias: string;
|
||||
};
|
||||
|
||||
export type LoginPageExpired = Common & {
|
||||
pageId: "login-page-expired.ftl";
|
||||
};
|
||||
|
||||
export type LoginConfigTotp = Common & {
|
||||
pageId: "login-config-totp.ftl";
|
||||
mode?: "qr" | "manual" | undefined | null;
|
||||
totp: {
|
||||
totpSecretEncoded: string;
|
||||
qrUrl: string;
|
||||
policy: {
|
||||
supportedApplications: string[];
|
||||
algorithm: "HmacSHA1" | "HmacSHA256" | "HmacSHA512";
|
||||
digits: number;
|
||||
lookAheadWindow: number;
|
||||
} & (
|
||||
| {
|
||||
type: "totp";
|
||||
period: number;
|
||||
}
|
||||
| {
|
||||
type: "hotp";
|
||||
initialCounter: number;
|
||||
}
|
||||
);
|
||||
totpSecretQrCode: string;
|
||||
manualUrl: string;
|
||||
totpSecret: string;
|
||||
otpCredentials: { id: string; userLabel: string }[];
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export type Attribute = {
|
||||
|
@ -1,7 +1,5 @@
|
||||
import "minimal-polyfills/Object.fromEntries";
|
||||
import type { KcContextBase, Attribute } from "../KcContextBase";
|
||||
import { getEvtKcLanguage } from "../../i18n/useKcLanguageTag";
|
||||
import { getKcLanguageTagLabel } from "../../i18n/KcLanguageTag";
|
||||
//NOTE: Aside because we want to be able to import them from node
|
||||
import { resourcesCommonPath, resourcesPath } from "./urlResourcesPath";
|
||||
import { id } from "tsafe/id";
|
||||
@ -32,81 +30,100 @@ export const kcContextCommonMock: KcContextBase.Common = {
|
||||
},
|
||||
"locale": {
|
||||
"supported": [
|
||||
/* spell-checker: disable */
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=de",
|
||||
"label": "Deutsch",
|
||||
"languageTag": "de",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=no",
|
||||
"label": "Norsk",
|
||||
"languageTag": "no",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=ru",
|
||||
"label": "Русский",
|
||||
"languageTag": "ru",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=sv",
|
||||
"label": "Svenska",
|
||||
"languageTag": "sv",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=pt-BR",
|
||||
"label": "Português (Brasil)",
|
||||
"languageTag": "pt-BR",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=lt",
|
||||
"label": "Lietuvių",
|
||||
"languageTag": "lt",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=en",
|
||||
"label": "English",
|
||||
"languageTag": "en",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=it",
|
||||
"label": "Italiano",
|
||||
"languageTag": "it",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=fr",
|
||||
"label": "Français",
|
||||
"languageTag": "fr",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=zh-CN",
|
||||
"label": "中文简体",
|
||||
"languageTag": "zh-CN",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=es",
|
||||
"label": "Español",
|
||||
"languageTag": "es",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=cs",
|
||||
"label": "Čeština",
|
||||
"languageTag": "cs",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=ja",
|
||||
"label": "日本語",
|
||||
"languageTag": "ja",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=sk",
|
||||
"label": "Slovenčina",
|
||||
"languageTag": "sk",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=pl",
|
||||
"label": "Polski",
|
||||
"languageTag": "pl",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=ca",
|
||||
"label": "Català",
|
||||
"languageTag": "ca",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=nl",
|
||||
"label": "Nederlands",
|
||||
"languageTag": "nl",
|
||||
},
|
||||
{
|
||||
"url": "/auth/realms/myrealm/login-actions/authenticate?client_id=account&tab_id=HoAx28ja4xg&execution=ee6c2834-46a4-4a20-a1b6-f6d6f6451b36&kc_locale=tr",
|
||||
"label": "Türkçe",
|
||||
"languageTag": "tr",
|
||||
},
|
||||
/* spell-checker: enable */
|
||||
],
|
||||
//"current": null as any
|
||||
"current": "English",
|
||||
"currentLanguageTag": "en",
|
||||
},
|
||||
"auth": {
|
||||
"showUsername": false,
|
||||
@ -124,11 +141,6 @@ export const kcContextCommonMock: KcContextBase.Common = {
|
||||
"isAppInitiatedAction": false,
|
||||
};
|
||||
|
||||
Object.defineProperty(kcContextCommonMock.locale!, "current", {
|
||||
"get": () => getKcLanguageTagLabel(getEvtKcLanguage().state),
|
||||
"enumerable": true,
|
||||
});
|
||||
|
||||
const loginUrl = {
|
||||
...kcContextCommonMock.url,
|
||||
"loginResetCredentialsUrl": "/auth/realms/myrealm/login-actions/reset-credentials?client_id=account&tab_id=HoAx28ja4xg",
|
||||
@ -367,4 +379,33 @@ export const kcContextMocks: KcContextBase[] = [
|
||||
"pageId": "login-idp-link-confirm.ftl",
|
||||
"idpAlias": "FranceConnect",
|
||||
}),
|
||||
id<KcContextBase.LoginIdpLinkEmail>({
|
||||
...kcContextCommonMock,
|
||||
"pageId": "login-idp-link-email.ftl",
|
||||
"idpAlias": "FranceConnect",
|
||||
"brokerContext": {
|
||||
"username": "anUsername",
|
||||
},
|
||||
}),
|
||||
id<KcContextBase.LoginConfigTotp>({
|
||||
...kcContextCommonMock,
|
||||
"pageId": "login-config-totp.ftl",
|
||||
totp: {
|
||||
totpSecretEncoded: "KVVF G2BY N4YX S6LB IUYT K2LH IFYE 4SBV",
|
||||
qrUrl: "#",
|
||||
totpSecretQrCode:
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAPYAAAD2AQAAAADNaUdlAAACM0lEQVR4Xu3OIZJgOQwDUDFd2UxiurLAVnnbHw4YGDKtSiWOn4Gxf81//7r/+q8b4HfLGBZDK9d85NmNR+sB42sXvOYrN5P1DcgYYFTGfOlbzE8gzwy3euweGizw7cfdl34/GRhlkxjKNV+5AebPXPORX1JuB9x8ZfbyyD2y1krWAKsbMq1HnqQDaLfa77p4+MqvzEGSqvSAD/2IHW2yHaigR9tX3m8dDIYGcNf3f+gDpVBZbZU77zyJ6Rlcy+qoTMG887KAPD9hsh6a1Sv3gJUHGHUAxSMzj7zqDDe7Phmt2eG+8UsMxjRGm816MAO+8VMl1R1jGHOrZB/5Zo/WXAPgxixm9Mo96vDGrM1eOto8c4Ax4wF437mifOXlpiPzCnN7Y9l95NnEMxgMY9AAGA8fucH14Y1aVb6N/cqrmyh0BVht7k1e+bU8LK0Cg5vmVq9c5vHIjOfqxDIfeTraNVTwewa4wVe+SW5N+uP1qACeudUZbqGOfA6VZV750Noq2Xx3kpveV44ZelSV1V7KFHzkWyVrrlUwG0Pl9pWnoy3vsQoME6vKI69i5osVgwWzHT7zjmJtMcNUSVn1oYMd7ZodbgowZl45VG0uVuLPUr1yc79uaQBag/mqR34xhlWyHm1prplHboCWdZ4TeZjsK8+dI+jbz1C5hl65mcpgB5dhcj8+dGO+0Ko68+lD37JDD83dpDLzzK+TrQyaVwGj6pUboGV+7+AyN8An/pf84/7rv/4/1l4OCc/1BYMAAAAASUVORK5CYII=",
|
||||
manualUrl: "#",
|
||||
totpSecret: "G4nsI8lQagRMUchH8jEG",
|
||||
otpCredentials: [],
|
||||
policy: {
|
||||
supportedApplications: ["FreeOTP", "Google Authenticator"],
|
||||
algorithm: "HmacSHA1",
|
||||
digits: 6,
|
||||
lookAheadWindow: 1,
|
||||
type: "totp",
|
||||
period: 30,
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
@ -1,63 +0,0 @@
|
||||
import { objectKeys } from "tsafe/objectKeys";
|
||||
import { kcMessages } from "./kcMessages/login";
|
||||
|
||||
export type KcLanguageTag = keyof typeof kcMessages;
|
||||
|
||||
const kcLanguageByTagLabel = {
|
||||
/* spell-checker: disable */
|
||||
"es": "Español",
|
||||
"it": "Italiano",
|
||||
"fr": "Français",
|
||||
"ca": "Català",
|
||||
"en": "English",
|
||||
"de": "Deutsch",
|
||||
"no": "Norsk",
|
||||
"pt-BR": "Português (Brasil)",
|
||||
"ru": "Русский",
|
||||
"sk": "Slovenčina",
|
||||
"ja": "日本語",
|
||||
"pl": "Polski",
|
||||
"zh-CN": "中文简体",
|
||||
"sv": "Svenska",
|
||||
"lt": "Lietuvių",
|
||||
"cs": "Čeština",
|
||||
"nl": "Nederlands",
|
||||
"tr": "Türkçe",
|
||||
"da": "Dansk",
|
||||
"hu": "Magyar",
|
||||
/* spell-checker: enable */
|
||||
} as const;
|
||||
|
||||
export type LanguageLabel = typeof kcLanguageByTagLabel[keyof typeof kcLanguageByTagLabel];
|
||||
|
||||
export function getKcLanguageTagLabel(language: KcLanguageTag): LanguageLabel {
|
||||
return kcLanguageByTagLabel[language] ?? language;
|
||||
}
|
||||
|
||||
export const kcLanguageTags = objectKeys(kcMessages);
|
||||
|
||||
/**
|
||||
* Pass in "fr-FR" or "français" for example, it will return the AvailableLanguage
|
||||
* it corresponds to: "fr".
|
||||
* If there is no reasonable match it's guessed from navigator.language.
|
||||
* If still no matches "en" is returned.
|
||||
*/
|
||||
export function getBestMatchAmongKcLanguageTag(languageLike: string): KcLanguageTag {
|
||||
const iso2LanguageLike = languageLike.split("-")[0].toLowerCase();
|
||||
|
||||
const kcLanguageTag = kcLanguageTags.find(
|
||||
language =>
|
||||
language.toLowerCase().includes(iso2LanguageLike) ||
|
||||
getKcLanguageTagLabel(language).toLocaleLowerCase() === languageLike.toLocaleLowerCase(),
|
||||
);
|
||||
|
||||
if (kcLanguageTag !== undefined) {
|
||||
return kcLanguageTag;
|
||||
}
|
||||
|
||||
if (languageLike !== navigator.language) {
|
||||
return getBestMatchAmongKcLanguageTag(navigator.language);
|
||||
}
|
||||
|
||||
return "en";
|
||||
}
|
4732
src/lib/i18n/generated_kcMessages/18.0.1/account.ts
Normal file
4732
src/lib/i18n/generated_kcMessages/18.0.1/account.ts
Normal file
File diff suppressed because it is too large
Load Diff
283
src/lib/i18n/generated_kcMessages/18.0.1/admin.ts
Normal file
283
src/lib/i18n/generated_kcMessages/18.0.1/admin.ts
Normal file
@ -0,0 +1,283 @@
|
||||
//This code was automatically generated by running dist/bin/generate-i18n-messages.js
|
||||
//PLEASE DO NOT EDIT MANUALLY
|
||||
|
||||
/* spell-checker: disable */
|
||||
export const kcMessages = {
|
||||
"ca": {
|
||||
"invalidPasswordHistoryMessage": "Contrasenya incorrecta: no pot ser igual a cap de les últimes {0} contrasenyes.",
|
||||
"invalidPasswordMinDigitsMessage": "Contraseña incorrecta: debe contener al menos {0} caracteres numéricos.",
|
||||
"invalidPasswordMinLengthMessage": "Contrasenya incorrecta: longitud mínima {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Contrasenya incorrecta: ha de contenir almenys {0} lletres minúscules.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Contrasenya incorrecta: ha de contenir almenys {0} caràcters especials.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Contrasenya incorrecta: ha de contenir almenys {0} lletres majúscules.",
|
||||
"invalidPasswordNotUsernameMessage": "Contrasenya incorrecta: no pot ser igual al nom d'usuari.",
|
||||
"invalidPasswordRegexPatternMessage": "Contrasenya incorrecta: no compleix l'expressió regular.",
|
||||
},
|
||||
"de": {
|
||||
"invalidPasswordMinLengthMessage": "Ungültiges Passwort: muss mindestens {0} Zeichen beinhalten.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Ungültiges Passwort: muss mindestens {0} Kleinbuchstaben beinhalten.",
|
||||
"invalidPasswordMinDigitsMessage": "Ungültiges Passwort: muss mindestens {0} Ziffern beinhalten.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Ungültiges Passwort: muss mindestens {0} Großbuchstaben beinhalten.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Ungültiges Passwort: muss mindestens {0} Sonderzeichen beinhalten.",
|
||||
"invalidPasswordNotUsernameMessage": "Ungültiges Passwort: darf nicht identisch mit dem Benutzernamen sein.",
|
||||
"invalidPasswordNotEmailMessage": "Ungültiges Passwort: darf nicht identisch mit der E-Mail-Adresse sein.",
|
||||
"invalidPasswordRegexPatternMessage": "Ungültiges Passwort: stimmt nicht mit Regex-Muster überein.",
|
||||
"invalidPasswordHistoryMessage": "Ungültiges Passwort: darf nicht identisch mit einem der letzten {0} Passwörter sein.",
|
||||
"invalidPasswordBlacklistedMessage": "Ungültiges Passwort: Passwort ist zu bekannt und auf der schwarzen Liste.",
|
||||
"invalidPasswordGenericMessage": "Ungültiges Passwort: neues Passwort erfüllt die Passwort-Anforderungen nicht.",
|
||||
},
|
||||
"en": {
|
||||
"invalidPasswordMinLengthMessage": "Invalid password: minimum length {0}.",
|
||||
"invalidPasswordMaxLengthMessage": "Invalid password: maximum length {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Invalid password: must contain at least {0} lower case characters.",
|
||||
"invalidPasswordMinDigitsMessage": "Invalid password: must contain at least {0} numerical digits.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Invalid password: must contain at least {0} upper case characters.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Invalid password: must contain at least {0} special characters.",
|
||||
"invalidPasswordNotUsernameMessage": "Invalid password: must not be equal to the username.",
|
||||
"invalidPasswordNotEmailMessage": "Invalid password: must not be equal to the email.",
|
||||
"invalidPasswordRegexPatternMessage": "Invalid password: fails to match regex pattern(s).",
|
||||
"invalidPasswordHistoryMessage": "Invalid password: must not be equal to any of last {0} passwords.",
|
||||
"invalidPasswordBlacklistedMessage": "Invalid password: password is blacklisted.",
|
||||
"invalidPasswordGenericMessage": "Invalid password: new password does not match password policies.",
|
||||
"ldapErrorEditModeMandatory": "Edit Mode is mandatory",
|
||||
"ldapErrorInvalidCustomFilter": 'Custom configured LDAP filter does not start with "(" or does not end with ")".',
|
||||
"ldapErrorConnectionTimeoutNotNumber": "Connection Timeout must be a number",
|
||||
"ldapErrorReadTimeoutNotNumber": "Read Timeout must be a number",
|
||||
"ldapErrorMissingClientId": "Client ID needs to be provided in config when Realm Roles Mapping is not used.",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType":
|
||||
"Not possible to preserve group inheritance and use UID membership type together.",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "Can not set write only when LDAP provider mode is not WRITABLE",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "Can not set write-only and read-only together",
|
||||
"ldapErrorCantEnableStartTlsAndConnectionPooling": "Can not enable both StartTLS and connection pooling.",
|
||||
"ldapErrorCantEnableUnsyncedAndImportOff": "Can not disable Importing users when LDAP provider mode is UNSYNCED",
|
||||
"ldapErrorMissingGroupsPathGroup": "Groups path group does not exist - please create the group on specified path first",
|
||||
"ldapErrorValidatePasswordPolicyAvailableForWritableOnly": "Validate Password Policy is applicable only with WRITABLE edit mode",
|
||||
"clientRedirectURIsFragmentError": "Redirect URIs must not contain an URI fragment",
|
||||
"clientRootURLFragmentError": "Root URL must not contain an URL fragment",
|
||||
"clientRootURLIllegalSchemeError": "Root URL uses an illegal scheme",
|
||||
"clientBaseURLIllegalSchemeError": "Base URL uses an illegal scheme",
|
||||
"backchannelLogoutUrlIllegalSchemeError": "Backchannel logout URL uses an illegal scheme",
|
||||
"clientRedirectURIsIllegalSchemeError": "A redirect URI uses an illegal scheme",
|
||||
"clientBaseURLInvalid": "Base URL is not a valid URL",
|
||||
"clientRootURLInvalid": "Root URL is not a valid URL",
|
||||
"clientRedirectURIsInvalid": "A redirect URI is not a valid URI",
|
||||
"backchannelLogoutUrlIsInvalid": "Backchannel logout URL is not a valid URL",
|
||||
"pairwiseMalformedClientRedirectURI": "Client contained an invalid redirect URI.",
|
||||
"pairwiseClientRedirectURIsMissingHost": "Client redirect URIs must contain a valid host component.",
|
||||
"pairwiseClientRedirectURIsMultipleHosts":
|
||||
"Without a configured Sector Identifier URI, client redirect URIs must not contain multiple host components.",
|
||||
"pairwiseMalformedSectorIdentifierURI": "Malformed Sector Identifier URI.",
|
||||
"pairwiseFailedToGetRedirectURIs": "Failed to get redirect URIs from the Sector Identifier URI.",
|
||||
"pairwiseRedirectURIsMismatch": "Client redirect URIs does not match redirect URIs fetched from the Sector Identifier URI.",
|
||||
"duplicatedJwksSettings": 'The "Use JWKS" switch and the switch "Use JWKS URL" cannot be ON at the same time.',
|
||||
"error-invalid-value": "Invalid value.",
|
||||
"error-invalid-blank": "Please specify value.",
|
||||
"error-empty": "Please specify value.",
|
||||
"error-invalid-length": "Attribute {0} must have a length between {1} and {2}.",
|
||||
"error-invalid-length-too-short": "Attribute {0} must have minimal length of {1}.",
|
||||
"error-invalid-length-too-long": "Attribute {0} must have maximal length of {2}.",
|
||||
"error-invalid-email": "Invalid email address.",
|
||||
"error-invalid-number": "Invalid number.",
|
||||
"error-number-out-of-range": "Attribute {0} must be a number between {1} and {2}.",
|
||||
"error-number-out-of-range-too-small": "Attribute {0} must have minimal value of {1}.",
|
||||
"error-number-out-of-range-too-big": "Attribute {0} must have maximal value of {2}.",
|
||||
"error-pattern-no-match": "Invalid value.",
|
||||
"error-invalid-uri": "Invalid URL.",
|
||||
"error-invalid-uri-scheme": "Invalid URL scheme.",
|
||||
"error-invalid-uri-fragment": "Invalid URL fragment.",
|
||||
"error-user-attribute-required": "Please specify attribute {0}.",
|
||||
"error-invalid-date": "Attribute {0} is invalid date.",
|
||||
"error-user-attribute-read-only": "Attribute {0} is read only.",
|
||||
"error-username-invalid-character": "{0} contains invalid character.",
|
||||
"error-person-name-invalid-character": "{0} contains invalid character.",
|
||||
},
|
||||
"es": {
|
||||
"invalidPasswordMinLengthMessage": "Contraseña incorrecta: longitud mínima {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Contraseña incorrecta: debe contener al menos {0} letras minúsculas.",
|
||||
"invalidPasswordMinDigitsMessage": "Contraseña incorrecta: debe contener al menos {0} caracteres numéricos.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Contraseña incorrecta: debe contener al menos {0} letras mayúsculas.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Contraseña incorrecta: debe contener al menos {0} caracteres especiales.",
|
||||
"invalidPasswordNotUsernameMessage": "Contraseña incorrecta: no puede ser igual al nombre de usuario.",
|
||||
"invalidPasswordRegexPatternMessage": "Contraseña incorrecta: no cumple la expresión regular.",
|
||||
"invalidPasswordHistoryMessage": "Contraseña incorrecta: no puede ser igual a ninguna de las últimas {0} contraseñas.",
|
||||
},
|
||||
"fi": {},
|
||||
"fr": {
|
||||
"invalidPasswordMinLengthMessage": "Mot de passe invalide : longueur minimale requise de {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Mot de passe invalide : doit contenir au moins {0} lettre(s) en minuscule.",
|
||||
"invalidPasswordMinDigitsMessage": "Mot de passe invalide : doit contenir au moins {0} chiffre(s).",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Mot de passe invalide : doit contenir au moins {0} lettre(s) en majuscule.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Mot de passe invalide : doit contenir au moins {0} caractère(s) spéciaux.",
|
||||
"invalidPasswordNotUsernameMessage": "Mot de passe invalide : ne doit pas être identique au nom d'utilisateur.",
|
||||
"invalidPasswordRegexPatternMessage": "Mot de passe invalide : ne valide pas l'expression rationnelle.",
|
||||
"invalidPasswordHistoryMessage": "Mot de passe invalide : ne doit pas être égal aux {0} derniers mot de passe.",
|
||||
},
|
||||
"it": {},
|
||||
"ja": {
|
||||
"invalidPasswordMinLengthMessage": "無効なパスワード: 最小{0}の長さが必要です。",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "無効なパスワード: 少なくとも{0}文字の小文字を含む必要があります。",
|
||||
"invalidPasswordMinDigitsMessage": "無効なパスワード: 少なくとも{0}文字の数字を含む必要があります。",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "無効なパスワード: 少なくとも{0}文字の大文字を含む必要があります。",
|
||||
"invalidPasswordMinSpecialCharsMessage": "無効なパスワード: 少なくとも{0}文字の特殊文字を含む必要があります。",
|
||||
"invalidPasswordNotUsernameMessage": "無効なパスワード: ユーザー名と同じパスワードは禁止されています。",
|
||||
"invalidPasswordRegexPatternMessage": "無効なパスワード: 正規表現パターンと一致しません。",
|
||||
"invalidPasswordHistoryMessage": "無効なパスワード: 最近の{0}パスワードのいずれかと同じパスワードは禁止されています。",
|
||||
"invalidPasswordBlacklistedMessage": "無効なパスワード: パスワードがブラックリストに含まれています。",
|
||||
"invalidPasswordGenericMessage": "無効なパスワード: 新しいパスワードはパスワード・ポリシーと一致しません。",
|
||||
"ldapErrorInvalidCustomFilter": "LDAPフィルターのカスタム設定が、「(」から開始または「)」で終了となっていません。",
|
||||
"ldapErrorConnectionTimeoutNotNumber": "接続タイムアウトは数字でなければなりません",
|
||||
"ldapErrorReadTimeoutNotNumber": "読み取りタイムアウトは数字でなければなりません",
|
||||
"ldapErrorMissingClientId": "レルムロール・マッピングを使用しない場合は、クライアントIDは設定内で提供される必要があります。",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType":
|
||||
"グループの継承を維持することと、UIDメンバーシップ・タイプを使用することは同時にできません。",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "LDAPプロバイダー・モードがWRITABLEではない場合は、write onlyを設定することはできません。",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "write-onlyとread-onlyを一緒に設定することはできません。",
|
||||
"ldapErrorCantEnableStartTlsAndConnectionPooling": "StartTLSと接続プーリングの両方を有効にできません。",
|
||||
"clientRedirectURIsFragmentError": "リダイレクトURIにURIフラグメントを含めることはできません。",
|
||||
"clientRootURLFragmentError": "ルートURLにURLフラグメントを含めることはできません。",
|
||||
"pairwiseMalformedClientRedirectURI": "クライアントに無効なリダイレクトURIが含まれていました。",
|
||||
"pairwiseClientRedirectURIsMissingHost": "クライアントのリダイレクトURIには有効なホスト・コンポーネントが含まれている必要があります。",
|
||||
"pairwiseClientRedirectURIsMultipleHosts":
|
||||
"設定されたセレクター識別子URIがない場合は、クライアントのリダイレクトURIは複数のホスト・コンポーネントを含むことはできません。",
|
||||
"pairwiseMalformedSectorIdentifierURI": "不正なセレクター識別子URIです。",
|
||||
"pairwiseFailedToGetRedirectURIs": "セクター識別子URIからリダイレクトURIを取得できませんでした。",
|
||||
"pairwiseRedirectURIsMismatch": "クライアントのリダイレクトURIは、セクター識別子URIからフェッチされたリダイレクトURIと一致しません。",
|
||||
},
|
||||
"lt": {
|
||||
"invalidPasswordMinLengthMessage": "Per trumpas slaptažodis: mažiausias ilgis {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Neteisingas slaptažodis: privaloma įvesti {0} mažąją raidę.",
|
||||
"invalidPasswordMinDigitsMessage": "Neteisingas slaptažodis: privaloma įvesti {0} skaitmenį.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Neteisingas slaptažodis: privaloma įvesti {0} didžiąją raidę.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Neteisingas slaptažodis: privaloma įvesti {0} specialų simbolį.",
|
||||
"invalidPasswordNotUsernameMessage": "Neteisingas slaptažodis: slaptažodis negali sutapti su naudotojo vardu.",
|
||||
"invalidPasswordRegexPatternMessage": "Neteisingas slaptažodis: slaptažodis netenkina regex taisyklės(ių).",
|
||||
"invalidPasswordHistoryMessage": "Neteisingas slaptažodis: slaptažodis negali sutapti su prieš tai buvusiais {0} slaptažodžiais.",
|
||||
"ldapErrorInvalidCustomFilter": 'Sukonfigūruotas LDAP filtras neprasideda "(" ir nesibaigia ")" simboliais.',
|
||||
"ldapErrorMissingClientId": "Privaloma nurodyti kliento ID kai srities rolių susiejimas nėra nenaudojamas.",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType": "Grupių paveldėjimo ir UID narystės tipas kartu negali būti naudojami.",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "Negalima nustatyti rašymo rėžimo kuomet LDAP teikėjo rėžimas ne WRITABLE",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "Negalima nustatyti tik rašyti ir tik skaityti kartu",
|
||||
"clientRedirectURIsFragmentError": "Nurodykite URI fragmentą, kurio negali būti peradresuojamuose URI adresuose",
|
||||
"clientRootURLFragmentError": "Nurodykite URL fragmentą, kurio negali būti šakniniame URL adrese",
|
||||
"pairwiseMalformedClientRedirectURI": "Klientas pateikė neteisingą nukreipimo nuorodą.",
|
||||
"pairwiseClientRedirectURIsMissingHost": "Kliento nukreipimo nuorodos privalo būti nurodytos su serverio vardo komponentu.",
|
||||
"pairwiseClientRedirectURIsMultipleHosts":
|
||||
"Kuomet nesukonfigūruotas sektoriaus identifikatoriaus URL, kliento nukreipimo nuorodos privalo talpinti ne daugiau kaip vieną skirtingą serverio vardo komponentą.",
|
||||
"pairwiseMalformedSectorIdentifierURI": "Neteisinga sektoriaus identifikatoriaus URI.",
|
||||
"pairwiseFailedToGetRedirectURIs": "Nepavyko gauti nukreipimo nuorodų iš sektoriaus identifikatoriaus URI.",
|
||||
"pairwiseRedirectURIsMismatch": "Kliento nukreipimo nuoroda neatitinka nukreipimo nuorodų iš sektoriaus identifikatoriaus URI.",
|
||||
},
|
||||
"lv": {},
|
||||
"nl": {
|
||||
"invalidPasswordMinLengthMessage": "Ongeldig wachtwoord: de minimale lengte is {0} karakters.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Ongeldig wachtwoord: het moet minstens {0} kleine letters bevatten.",
|
||||
"invalidPasswordMinDigitsMessage": "Ongeldig wachtwoord: het moet minstens {0} getallen bevatten.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Ongeldig wachtwoord: het moet minstens {0} hoofdletters bevatten.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Ongeldig wachtwoord: het moet minstens {0} speciale karakters bevatten.",
|
||||
"invalidPasswordNotUsernameMessage": "Ongeldig wachtwoord: het mag niet overeenkomen met de gebruikersnaam.",
|
||||
"invalidPasswordRegexPatternMessage": "Ongeldig wachtwoord: het voldoet niet aan het door de beheerder ingestelde patroon.",
|
||||
"invalidPasswordHistoryMessage": "Ongeldig wachtwoord: het mag niet overeen komen met een van de laatste {0} wachtwoorden.",
|
||||
"invalidPasswordGenericMessage": "Ongeldig wachtwoord: het nieuwe wachtwoord voldoet niet aan het wachtwoordbeleid.",
|
||||
"ldapErrorInvalidCustomFilter": 'LDAP filter met aangepaste configuratie start niet met "(" of eindigt niet met ")".',
|
||||
"ldapErrorConnectionTimeoutNotNumber": "Verbindingstimeout moet een getal zijn",
|
||||
"ldapErrorReadTimeoutNotNumber": "Lees-timeout moet een getal zijn",
|
||||
"ldapErrorMissingClientId": "Client ID moet ingesteld zijn als Realm Roles Mapping niet gebruikt wordt.",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType": "Kan groepsovererving niet behouden bij UID-lidmaatschapstype.",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "Alleen-schrijven niet mogelijk als LDAP provider mode niet WRITABLE is",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "Alleen-schrijven en alleen-lezen mogen niet tegelijk ingesteld zijn",
|
||||
"clientRedirectURIsFragmentError": "Redirect URIs mogen geen URI fragment bevatten",
|
||||
"clientRootURLFragmentError": "Root URL mag geen URL fragment bevatten",
|
||||
"pairwiseMalformedClientRedirectURI": "Client heeft een ongeldige redirect URI.",
|
||||
"pairwiseClientRedirectURIsMissingHost": "Client redirect URIs moeten een geldige host-component bevatten.",
|
||||
"pairwiseClientRedirectURIsMultipleHosts":
|
||||
"Zonder een geconfigureerde Sector Identifier URI mogen client redirect URIs niet meerdere host componenten hebben.",
|
||||
"pairwiseMalformedSectorIdentifierURI": "Onjuist notatie in Sector Identifier URI.",
|
||||
"pairwiseFailedToGetRedirectURIs": "Kon geen redirect URIs verkrijgen van de Sector Identifier URI.",
|
||||
"pairwiseRedirectURIsMismatch": "Client redirect URIs komen niet overeen met redict URIs ontvangen van de Sector Identifier URI.",
|
||||
},
|
||||
"no": {
|
||||
"invalidPasswordMinLengthMessage": "Ugyldig passord: minimum lengde {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Ugyldig passord: må inneholde minst {0} små bokstaver.",
|
||||
"invalidPasswordMinDigitsMessage": "Ugyldig passord: må inneholde minst {0} sifre.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Ugyldig passord: må inneholde minst {0} store bokstaver.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Ugyldig passord: må inneholde minst {0} spesialtegn.",
|
||||
"invalidPasswordNotUsernameMessage": "Ugyldig passord: kan ikke være likt brukernavn.",
|
||||
"invalidPasswordRegexPatternMessage": "Ugyldig passord: tilfredsstiller ikke kravene for passord-mønster.",
|
||||
"invalidPasswordHistoryMessage": "Ugyldig passord: kan ikke være likt noen av de {0} foregående passordene.",
|
||||
"ldapErrorInvalidCustomFilter": 'Tilpasset konfigurasjon av LDAP-filter starter ikke med "(" eller slutter ikke med ")".',
|
||||
"ldapErrorMissingClientId": "KlientID må være tilgjengelig i config når sikkerhetsdomenerollemapping ikke brukes.",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType": "Ikke mulig å bevare gruppearv og samtidig bruke UID medlemskapstype.",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "Kan ikke sette write-only når LDAP leverandør-modus ikke er WRITABLE",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "Kan ikke sette både write-only og read-only",
|
||||
},
|
||||
"pl": {},
|
||||
"pt-BR": {
|
||||
"invalidPasswordMinLengthMessage": "Senha inválida: deve conter ao menos {0} caracteres.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Senha inválida: deve conter ao menos {0} caracteres minúsculos.",
|
||||
"invalidPasswordMinDigitsMessage": "Senha inválida: deve conter ao menos {0} digitos numéricos.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Senha inválida: deve conter ao menos {0} caracteres maiúsculos.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Senha inválida: deve conter ao menos {0} caracteres especiais.",
|
||||
"invalidPasswordNotUsernameMessage": "Senha inválida: não deve ser igual ao nome de usuário.",
|
||||
"invalidPasswordRegexPatternMessage": "Senha inválida: falha ao passar por padrões.",
|
||||
"invalidPasswordHistoryMessage": "Senha inválida: não deve ser igual às últimas {0} senhas.",
|
||||
"ldapErrorInvalidCustomFilter": 'Filtro LDAP não inicia com "(" ou não termina com ")".',
|
||||
"ldapErrorMissingClientId": "ID do cliente precisa ser definido na configuração quando mapeamentos de Roles do Realm não é utilizado.",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType":
|
||||
"Não é possível preservar herança de grupos e usar tipo de associação de UID ao mesmo tempo.",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "Não é possível definir modo de somente escrita quando o provedor LDAP não suporta escrita",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "Não é possível definir somente escrita e somente leitura ao mesmo tempo",
|
||||
"clientRedirectURIsFragmentError": "URIs de redirecionamento não podem conter fragmentos",
|
||||
"clientRootURLFragmentError": "URL raiz não pode conter fragmentos",
|
||||
},
|
||||
"ru": {
|
||||
"invalidPasswordMinLengthMessage": "Некорректный пароль: длина пароля должна быть не менее {0} символов(а).",
|
||||
"invalidPasswordMinDigitsMessage": "Некорректный пароль: должен содержать не менее {0} цифр(ы).",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "Некорректный пароль: пароль должен содержать не менее {0} символов(а) в нижнем регистре.",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "Некорректный пароль: пароль должен содержать не менее {0} символов(а) в верхнем регистре.",
|
||||
"invalidPasswordMinSpecialCharsMessage": "Некорректный пароль: пароль должен содержать не менее {0} спецсимволов(а).",
|
||||
"invalidPasswordNotUsernameMessage": "Некорректный пароль: пароль не должен совпадать с именем пользователя.",
|
||||
"invalidPasswordRegexPatternMessage": "Некорректный пароль: пароль не прошел проверку по регулярному выражению.",
|
||||
"invalidPasswordHistoryMessage": "Некорректный пароль: пароль не должен совпадать с последним(и) {0} паролем(ями).",
|
||||
"invalidPasswordGenericMessage": "Некорректный пароль: новый пароль не соответствует правилам пароля.",
|
||||
"ldapErrorInvalidCustomFilter": 'Сконфигурированный пользователем фильтр LDAP не должен начинаться с "(" или заканчиваться на ")".',
|
||||
"ldapErrorMissingClientId": "Client ID должен быть настроен в конфигурации, если не используется сопоставление ролей в realm.",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType": "Не удалось унаследовать группу и использовать членство UID типа вместе.",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": 'Невозможно установить режим "только на запись", когда LDAP провайдер не в режиме WRITABLE',
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": 'Невозможно одновременно установить режимы "только на чтение" и "только на запись"',
|
||||
"clientRedirectURIsFragmentError": "URI перенаправления не должен содержать фрагмент URI",
|
||||
"clientRootURLFragmentError": "Корневой URL не должен содержать фрагмент URL ",
|
||||
"pairwiseMalformedClientRedirectURI": "Клиент содержит некорректный URI перенаправления.",
|
||||
"pairwiseClientRedirectURIsMissingHost": "URI перенаправления клиента должен содержать корректный компонент хоста.",
|
||||
"pairwiseClientRedirectURIsMultipleHosts":
|
||||
"Без конфигурации по части идентификатора URI, URI перенаправления клиента не может содержать несколько компонентов хоста.",
|
||||
"pairwiseMalformedSectorIdentifierURI": "Искаженная часть идентификатора URI.",
|
||||
"pairwiseFailedToGetRedirectURIs": "Не удалось получить идентификаторы URI перенаправления из части идентификатора URI.",
|
||||
"pairwiseRedirectURIsMismatch": "Клиент URI переадресации не соответствует URI переадресации, полученной из части идентификатора URI.",
|
||||
},
|
||||
"zh-CN": {
|
||||
"invalidPasswordMinLengthMessage": "无效的密码:最短长度 {0}.",
|
||||
"invalidPasswordMinLowerCaseCharsMessage": "无效的密码:至少包含 {0} 小写字母",
|
||||
"invalidPasswordMinDigitsMessage": "无效的密码:至少包含 {0} 个数字",
|
||||
"invalidPasswordMinUpperCaseCharsMessage": "无效的密码:最短长度 {0} 大写字母",
|
||||
"invalidPasswordMinSpecialCharsMessage": "无效的密码:最短长度 {0} 特殊字符",
|
||||
"invalidPasswordNotUsernameMessage": "无效的密码: 不可以与用户名相同",
|
||||
"invalidPasswordRegexPatternMessage": "无效的密码: 无法与正则表达式匹配",
|
||||
"invalidPasswordHistoryMessage": "无效的密码:不能与最后使用的 {0} 个密码相同",
|
||||
"ldapErrorInvalidCustomFilter": '定制的 LDAP过滤器不是以 "(" 开头或以 ")"结尾.',
|
||||
"ldapErrorConnectionTimeoutNotNumber": "Connection Timeout 必须是个数字",
|
||||
"ldapErrorMissingClientId": "当域角色映射未启用时,客户端 ID 需要指定。",
|
||||
"ldapErrorCantPreserveGroupInheritanceWithUIDMembershipType": "无法在使用UID成员类型的同时维护组继承属性。",
|
||||
"ldapErrorCantWriteOnlyForReadOnlyLdap": "当LDAP提供方不是可写模式时,无法设置只写",
|
||||
"ldapErrorCantWriteOnlyAndReadOnly": "无法同时设置只读和只写",
|
||||
"clientRedirectURIsFragmentError": "重定向URL不应包含URI片段",
|
||||
"clientRootURLFragmentError": "根URL 不应包含 URL 片段",
|
||||
"pairwiseMalformedClientRedirectURI": "客户端包含一个无效的重定向URL",
|
||||
"pairwiseClientRedirectURIsMissingHost": "客户端重定向URL需要有一个有效的主机",
|
||||
"pairwiseClientRedirectURIsMultipleHosts":
|
||||
"Without a configured Sector Identifier URI, client redirect URIs must not contain multiple host components.",
|
||||
"pairwiseMalformedSectorIdentifierURI": "Malformed Sector Identifier URI.",
|
||||
"pairwiseFailedToGetRedirectURIs": "无法从服务器获得重定向URL",
|
||||
"pairwiseRedirectURIsMismatch": "客户端的重定向URI与服务器端获取的URI配置不匹配。",
|
||||
},
|
||||
};
|
||||
/* spell-checker: enable */
|
1062
src/lib/i18n/generated_kcMessages/18.0.1/email.ts
Normal file
1062
src/lib/i18n/generated_kcMessages/18.0.1/email.ts
Normal file
File diff suppressed because it is too large
Load Diff
6063
src/lib/i18n/generated_kcMessages/18.0.1/login.ts
Normal file
6063
src/lib/i18n/generated_kcMessages/18.0.1/login.ts
Normal file
File diff suppressed because it is too large
Load Diff
208
src/lib/i18n/index.tsx
Normal file
208
src/lib/i18n/index.tsx
Normal file
@ -0,0 +1,208 @@
|
||||
import "minimal-polyfills/Object.fromEntries";
|
||||
//NOTE for later: https://github.com/remarkjs/react-markdown/blob/236182ecf30bd89c1e5a7652acaf8d0bf81e6170/src/renderers.js#L7-L35
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import memoize from "memoizee";
|
||||
import { kcMessages as kcMessagesBase } from "./generated_kcMessages/18.0.1/login";
|
||||
import { assert } from "tsafe/assert";
|
||||
import type { Equals } from "tsafe";
|
||||
|
||||
export const kcMessages = {
|
||||
...kcMessagesBase,
|
||||
"en": {
|
||||
...kcMessagesBase["en"],
|
||||
"termsText": "⏳",
|
||||
"shouldBeEqual": "{0} should be equal to {1}",
|
||||
"shouldBeDifferent": "{0} should be different to {1}",
|
||||
"shouldMatchPattern": "Pattern should match: `/{0}/`",
|
||||
"mustBeAnInteger": "Must be an integer",
|
||||
"notAValidOption": "Not a valid option",
|
||||
},
|
||||
"fr": {
|
||||
...kcMessagesBase["fr"],
|
||||
/* spell-checker: disable */
|
||||
"shouldBeEqual": "{0} doit être egale à {1}",
|
||||
"shouldBeDifferent": "{0} doit être différent de {1}",
|
||||
"shouldMatchPattern": "Dois respecter le schéma: `/{0}/`",
|
||||
"mustBeAnInteger": "Doit être un nombre entiers",
|
||||
"notAValidOption": "N'est pas une option valide",
|
||||
/* spell-checker: enable */
|
||||
},
|
||||
};
|
||||
|
||||
export type KcLanguageTag = keyof typeof kcMessages;
|
||||
|
||||
export const kcLanguageTags = [
|
||||
"en",
|
||||
"fr",
|
||||
"ca",
|
||||
"cs",
|
||||
"da",
|
||||
"de",
|
||||
"es",
|
||||
"hu",
|
||||
"it",
|
||||
"ja",
|
||||
"lt",
|
||||
"nl",
|
||||
"no",
|
||||
"pl",
|
||||
"pt-BR",
|
||||
"ru",
|
||||
"sk",
|
||||
"sv",
|
||||
"tr",
|
||||
"zh-CN",
|
||||
"fi",
|
||||
"lv",
|
||||
] as const;
|
||||
|
||||
assert<Equals<KcLanguageTag, typeof kcLanguageTags[number]>>();
|
||||
|
||||
type KcContextLike = { locale?: { currentLanguageTag: KcLanguageTag } };
|
||||
|
||||
export function getCurrentKcLanguageTag(kcContext: KcContextLike) {
|
||||
return kcContext.locale?.currentLanguageTag ?? "en";
|
||||
}
|
||||
|
||||
export function getTagLabel(params: {
|
||||
kcContext: {
|
||||
locale?: {
|
||||
supported: { languageTag: KcLanguageTag; label: string }[];
|
||||
};
|
||||
};
|
||||
kcLanguageTag: KcLanguageTag;
|
||||
}): string {
|
||||
const { kcContext, kcLanguageTag } = params;
|
||||
|
||||
const { locale } = kcContext;
|
||||
|
||||
assert(locale !== undefined, "Internationalization not enabled");
|
||||
|
||||
const targetSupportedLocale = locale.supported.find(({ languageTag }) => languageTag === kcLanguageTag);
|
||||
|
||||
assert(targetSupportedLocale !== undefined, `${kcLanguageTag} need to be enabled in Keycloak admin`);
|
||||
|
||||
return targetSupportedLocale.label;
|
||||
}
|
||||
|
||||
export function changeLocale(params: {
|
||||
kcContext: {
|
||||
locale?: {
|
||||
supported: { languageTag: KcLanguageTag; url: string }[];
|
||||
};
|
||||
};
|
||||
kcLanguageTag: KcLanguageTag;
|
||||
}): never {
|
||||
const { kcContext, kcLanguageTag } = params;
|
||||
|
||||
const { locale } = kcContext;
|
||||
|
||||
assert(locale !== undefined, "Internationalization not enabled");
|
||||
|
||||
const targetSupportedLocale = locale.supported.find(({ languageTag }) => languageTag === kcLanguageTag);
|
||||
|
||||
assert(targetSupportedLocale !== undefined, `${kcLanguageTag} need to be enabled in Keycloak admin`);
|
||||
|
||||
window.location.href = targetSupportedLocale.url;
|
||||
|
||||
assert(false, "never");
|
||||
}
|
||||
|
||||
export type MessageKey = keyof typeof kcMessages["en"];
|
||||
|
||||
function resolveMsg<Key extends string, DoRenderMarkdown extends boolean>(props: {
|
||||
key: Key;
|
||||
args: (string | undefined)[];
|
||||
kcLanguageTag: string;
|
||||
doRenderMarkdown: DoRenderMarkdown;
|
||||
}): Key extends MessageKey ? (DoRenderMarkdown extends true ? JSX.Element : string) : undefined {
|
||||
const { key, args, kcLanguageTag, doRenderMarkdown } = props;
|
||||
|
||||
let str = kcMessages[kcLanguageTag as any as "en"][key as MessageKey] ?? kcMessages["en"][key as MessageKey];
|
||||
|
||||
if (str === undefined) {
|
||||
return undefined as any;
|
||||
}
|
||||
|
||||
str = (() => {
|
||||
const startIndex = str
|
||||
.match(/{[0-9]+}/g)
|
||||
?.map(g => g.match(/{([0-9]+)}/)![1])
|
||||
.map(indexStr => parseInt(indexStr))
|
||||
.sort((a, b) => a - b)[0];
|
||||
|
||||
if (startIndex === undefined) {
|
||||
return str;
|
||||
}
|
||||
|
||||
args.forEach((arg, i) => {
|
||||
if (arg === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
str = str.replace(new RegExp(`\\{${i + startIndex}\\}`, "g"), arg);
|
||||
});
|
||||
|
||||
return str;
|
||||
})();
|
||||
|
||||
return (
|
||||
doRenderMarkdown ? (
|
||||
<ReactMarkdown allowDangerousHtml renderers={key === "termsText" ? undefined : { "paragraph": "span" }}>
|
||||
{str}
|
||||
</ReactMarkdown>
|
||||
) : (
|
||||
str
|
||||
)
|
||||
) as any;
|
||||
}
|
||||
|
||||
function resolveMsgAdvanced<Key extends string, DoRenderMarkdown extends boolean>(props: {
|
||||
key: Key;
|
||||
args: (string | undefined)[];
|
||||
kcLanguageTag: string;
|
||||
doRenderMarkdown: DoRenderMarkdown;
|
||||
}): DoRenderMarkdown extends true ? JSX.Element : string {
|
||||
const { key, args, kcLanguageTag, doRenderMarkdown } = props;
|
||||
|
||||
const match = key.match(/^\$\{([^{]+)\}$/);
|
||||
|
||||
const keyUnwrappedFromCurlyBraces = match === null ? key : match[1];
|
||||
|
||||
const out = resolveMsg({
|
||||
"key": keyUnwrappedFromCurlyBraces,
|
||||
args,
|
||||
kcLanguageTag,
|
||||
doRenderMarkdown,
|
||||
});
|
||||
|
||||
return (out !== undefined ? out : doRenderMarkdown ? <span>{keyUnwrappedFromCurlyBraces}</span> : keyUnwrappedFromCurlyBraces) as any;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the language is switched the page is reloaded, this may appear
|
||||
* as a bug as you might notice that the language successfully switch before
|
||||
* reload.
|
||||
* However we need to tell Keycloak that the user have changed the language
|
||||
* during login so we can retrieve the "local" field of the JWT encoded accessToken.
|
||||
* https://user-images.githubusercontent.com/6702424/138096682-351bb61f-f24e-4caf-91b7-cca8cfa2cb58.mov
|
||||
*
|
||||
* advancedMsg("${access-denied}") === advancedMsg("access-denied") === msg("access-denied")
|
||||
* advancedMsg("${not-a-message-key}") === advancedMsg(not-a-message-key") === "not-a-message-key"
|
||||
*
|
||||
*
|
||||
* NOTE: This function is memoized, it always returns the same object for a given kcContext)
|
||||
*
|
||||
*/
|
||||
export const getMsg = memoize((kcContext: KcContextLike) => {
|
||||
const kcLanguageTag = getCurrentKcLanguageTag(kcContext);
|
||||
|
||||
return {
|
||||
"msgStr": (key: MessageKey, ...args: (string | undefined)[]): string => resolveMsg({ key, args, kcLanguageTag, "doRenderMarkdown": false }),
|
||||
"msg": (key: MessageKey, ...args: (string | undefined)[]): JSX.Element => resolveMsg({ key, args, kcLanguageTag, "doRenderMarkdown": true }),
|
||||
"advancedMsg": <Key extends string>(key: Key, ...args: (string | undefined)[]): JSX.Element =>
|
||||
resolveMsgAdvanced({ key, args, kcLanguageTag, "doRenderMarkdown": true }),
|
||||
"advancedMsgStr": <Key extends string>(key: Key, ...args: (string | undefined)[]): string =>
|
||||
resolveMsgAdvanced({ key, args, kcLanguageTag, "doRenderMarkdown": false }),
|
||||
};
|
||||
});
|
@ -1,50 +0,0 @@
|
||||
import { kcMessages as kcMessagesBase } from "../generated_kcMessages/15.0.2/login";
|
||||
import { Evt } from "evt";
|
||||
import { objectKeys } from "tsafe/objectKeys";
|
||||
|
||||
const kcMessages = {
|
||||
...kcMessagesBase,
|
||||
"en": {
|
||||
...kcMessagesBase["en"],
|
||||
"shouldBeEqual": "{0} should be equal to {1}",
|
||||
"shouldBeDifferent": "{0} should be different to {1}",
|
||||
"shouldMatchPattern": "Pattern should match: `/{0}/`",
|
||||
"mustBeAnInteger": "Must be an integer",
|
||||
"notAValidOption": "Not a valid option",
|
||||
},
|
||||
"fr": {
|
||||
...kcMessagesBase["fr"],
|
||||
/* spell-checker: disable */
|
||||
"shouldBeEqual": "{0} doit être egale à {1}",
|
||||
"shouldBeDifferent": "{0} doit être différent de {1}",
|
||||
"shouldMatchPattern": "Dois respecter le schéma: `/{0}/`",
|
||||
"mustBeAnInteger": "Doit être un nombre entiers",
|
||||
"notAValidOption": "N'est pas une option valide",
|
||||
/* spell-checker: enable */
|
||||
},
|
||||
};
|
||||
|
||||
export const evtTermsUpdated = Evt.asNonPostable(Evt.create<void>());
|
||||
|
||||
(["termsText", "doAccept", "doDecline", "termsTitle"] as const).forEach(key =>
|
||||
objectKeys(kcMessages).forEach(kcLanguage =>
|
||||
Object.defineProperty(
|
||||
kcMessages[kcLanguage],
|
||||
key,
|
||||
(() => {
|
||||
let value = key === "termsText" ? "⏳" : kcMessages[kcLanguage][key];
|
||||
|
||||
return {
|
||||
"enumerable": true,
|
||||
"get": () => value,
|
||||
"set": (newValue: string) => {
|
||||
value = newValue;
|
||||
Evt.asPostable(evtTermsUpdated).post();
|
||||
},
|
||||
};
|
||||
})(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export { kcMessages };
|
@ -1,28 +0,0 @@
|
||||
import { createUseGlobalState } from "powerhooks/useGlobalState";
|
||||
import { getKcContextFromWindow } from "../getKcContext/getKcContextFromWindow";
|
||||
import { getBestMatchAmongKcLanguageTag } from "./KcLanguageTag";
|
||||
import type { StatefulEvt } from "powerhooks";
|
||||
import { KcLanguageTag } from "./KcLanguageTag";
|
||||
|
||||
//export const { useKcLanguageTag, evtKcLanguageTag } = createUseGlobalState(
|
||||
const wrap = createUseGlobalState(
|
||||
"kcLanguageTag",
|
||||
() => {
|
||||
const kcContext = getKcContextFromWindow();
|
||||
|
||||
const languageLike = kcContext?.locale?.current ?? (typeof navigator === "undefined" ? undefined : navigator.language);
|
||||
|
||||
if (languageLike === undefined) {
|
||||
return "en";
|
||||
}
|
||||
|
||||
return getBestMatchAmongKcLanguageTag(languageLike);
|
||||
},
|
||||
{ "persistance": "localStorage" },
|
||||
);
|
||||
|
||||
export const { useKcLanguageTag } = wrap;
|
||||
|
||||
export function getEvtKcLanguage(): StatefulEvt<KcLanguageTag> {
|
||||
return wrap.evtKcLanguageTag;
|
||||
}
|
@ -1,115 +0,0 @@
|
||||
import "minimal-polyfills/Object.fromEntries";
|
||||
import { useReducer } from "react";
|
||||
import { useKcLanguageTag } from "./useKcLanguageTag";
|
||||
import { kcMessages, evtTermsUpdated } from "./kcMessages/login";
|
||||
import { useEvt } from "evt/hooks";
|
||||
//NOTE for later: https://github.com/remarkjs/react-markdown/blob/236182ecf30bd89c1e5a7652acaf8d0bf81e6170/src/renderers.js#L7-L35
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import { useGuaranteedMemo } from "powerhooks/useGuaranteedMemo";
|
||||
|
||||
export { kcMessages };
|
||||
|
||||
export type MessageKey = keyof typeof kcMessages["en"];
|
||||
|
||||
function resolveMsg<Key extends string, DoRenderMarkdown extends boolean>(props: {
|
||||
key: Key;
|
||||
args: (string | undefined)[];
|
||||
kcLanguageTag: string;
|
||||
doRenderMarkdown: DoRenderMarkdown;
|
||||
}): Key extends MessageKey ? (DoRenderMarkdown extends true ? JSX.Element : string) : undefined {
|
||||
const { key, args, kcLanguageTag, doRenderMarkdown } = props;
|
||||
|
||||
let str = kcMessages[kcLanguageTag as any as "en"][key as MessageKey] ?? kcMessages["en"][key as MessageKey];
|
||||
|
||||
if (str === undefined) {
|
||||
return undefined as any;
|
||||
}
|
||||
|
||||
str = (() => {
|
||||
const startIndex = str
|
||||
.match(/{[0-9]+}/g)
|
||||
?.map(g => g.match(/{([0-9]+)}/)![1])
|
||||
.map(indexStr => parseInt(indexStr))
|
||||
.sort((a, b) => a - b)[0];
|
||||
|
||||
if (startIndex === undefined) {
|
||||
return str;
|
||||
}
|
||||
|
||||
args.forEach((arg, i) => {
|
||||
if (arg === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
str = str.replace(new RegExp(`\\{${i + startIndex}\\}`, "g"), arg);
|
||||
});
|
||||
|
||||
return str;
|
||||
})();
|
||||
|
||||
return (
|
||||
doRenderMarkdown ? (
|
||||
<ReactMarkdown allowDangerousHtml renderers={key === "termsText" ? undefined : { "paragraph": "span" }}>
|
||||
{str}
|
||||
</ReactMarkdown>
|
||||
) : (
|
||||
str
|
||||
)
|
||||
) as any;
|
||||
}
|
||||
|
||||
function resolveMsgAdvanced<Key extends string, DoRenderMarkdown extends boolean>(props: {
|
||||
key: Key;
|
||||
args: (string | undefined)[];
|
||||
kcLanguageTag: string;
|
||||
doRenderMarkdown: DoRenderMarkdown;
|
||||
}): DoRenderMarkdown extends true ? JSX.Element : string {
|
||||
const { key, args, kcLanguageTag, doRenderMarkdown } = props;
|
||||
|
||||
const match = key.match(/^\$\{([^{]+)\}$/);
|
||||
|
||||
const keyUnwrappedFromCurlyBraces = match === null ? key : match[1];
|
||||
|
||||
const out = resolveMsg({
|
||||
"key": keyUnwrappedFromCurlyBraces,
|
||||
args,
|
||||
kcLanguageTag,
|
||||
doRenderMarkdown,
|
||||
});
|
||||
|
||||
return (out !== undefined ? out : doRenderMarkdown ? <span>{keyUnwrappedFromCurlyBraces}</span> : keyUnwrappedFromCurlyBraces) as any;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the language is switched the page is reloaded, this may appear
|
||||
* as a bug as you might notice that the language successfully switch before
|
||||
* reload.
|
||||
* However we need to tell Keycloak that the user have changed the language
|
||||
* during login so we can retrieve the "local" field of the JWT encoded accessToken.
|
||||
* https://user-images.githubusercontent.com/6702424/138096682-351bb61f-f24e-4caf-91b7-cca8cfa2cb58.mov
|
||||
*
|
||||
* advancedMsg("${access-denied}") === advancedMsg("access-denied") === msg("access-denied")
|
||||
* advancedMsg("${not-a-message-key}") === advancedMsg(not-a-message-key") === "not-a-message-key"
|
||||
*
|
||||
*/
|
||||
export function useKcMessage() {
|
||||
const { kcLanguageTag } = useKcLanguageTag();
|
||||
|
||||
const [trigger, forceUpdate] = useReducer((counter: number) => counter + 1, 0);
|
||||
|
||||
useEvt(ctx => evtTermsUpdated.attach(ctx, forceUpdate), []);
|
||||
|
||||
return useGuaranteedMemo(
|
||||
() => ({
|
||||
"msgStr": (key: MessageKey, ...args: (string | undefined)[]): string =>
|
||||
resolveMsg({ key, args, kcLanguageTag, "doRenderMarkdown": false }),
|
||||
"msg": (key: MessageKey, ...args: (string | undefined)[]): JSX.Element =>
|
||||
resolveMsg({ key, args, kcLanguageTag, "doRenderMarkdown": true }),
|
||||
"advancedMsg": <Key extends string>(key: Key, ...args: (string | undefined)[]): JSX.Element =>
|
||||
resolveMsgAdvanced({ key, args, kcLanguageTag, "doRenderMarkdown": true }),
|
||||
"advancedMsgStr": <Key extends string>(key: Key, ...args: (string | undefined)[]): string =>
|
||||
resolveMsgAdvanced({ key, args, kcLanguageTag, "doRenderMarkdown": false }),
|
||||
}),
|
||||
[kcLanguageTag, trigger],
|
||||
);
|
||||
}
|
@ -1,18 +1,11 @@
|
||||
export * from "./getKcContext";
|
||||
|
||||
export * from "./i18n/KcLanguageTag";
|
||||
export * from "./i18n/useKcLanguageTag";
|
||||
export * from "./i18n/useKcMessage";
|
||||
export * from "./i18n/kcMessages/login";
|
||||
export * from "./i18n";
|
||||
|
||||
export { useDownloadTerms } from "./components/Terms";
|
||||
|
||||
export * from "./components/KcProps";
|
||||
export * from "./components/Login";
|
||||
export * from "./components/Template";
|
||||
export * from "./components/KcApp";
|
||||
export * from "./components/Info";
|
||||
export * from "./components/Error";
|
||||
export * from "./components/LoginResetPassword";
|
||||
export * from "./components/LoginVerifyEmail";
|
||||
export * from "./components/KcProps";
|
||||
export * from "./keycloakJsAdapter";
|
||||
export * from "./useFormValidationSlice";
|
||||
|
||||
|
@ -44,8 +44,9 @@ export declare namespace keycloak_js {
|
||||
export function createKeycloakAdapter(params: {
|
||||
keycloakInstance: keycloak_js.KeycloakInstance;
|
||||
transformUrlBeforeRedirect(url: string): string;
|
||||
getRedirectMethod?: () => "overwrite location.href" | "location.replace";
|
||||
}): keycloak_js.KeycloakAdapter {
|
||||
const { keycloakInstance, transformUrlBeforeRedirect } = params;
|
||||
const { keycloakInstance, transformUrlBeforeRedirect, getRedirectMethod = () => "overwrite location.href" } = params;
|
||||
|
||||
const neverResolvingPromise: keycloak_js.KeycloakPromise<void, void> = Object.defineProperties(new Promise(() => {}), {
|
||||
"success": { "value": () => {} },
|
||||
@ -54,25 +55,50 @@ export function createKeycloakAdapter(params: {
|
||||
|
||||
return {
|
||||
"login": options => {
|
||||
window.location.href = transformUrlBeforeRedirect(keycloakInstance.createLoginUrl(options));
|
||||
const newHref = transformUrlBeforeRedirect(keycloakInstance.createLoginUrl(options));
|
||||
switch (getRedirectMethod()) {
|
||||
case "location.replace":
|
||||
window.location.replace(newHref);
|
||||
break;
|
||||
case "overwrite location.href":
|
||||
window.location.href = newHref;
|
||||
break;
|
||||
}
|
||||
return neverResolvingPromise;
|
||||
},
|
||||
"register": options => {
|
||||
const newHref = transformUrlBeforeRedirect(keycloakInstance.createRegisterUrl(options));
|
||||
switch (getRedirectMethod()) {
|
||||
case "location.replace":
|
||||
window.location.replace(newHref);
|
||||
break;
|
||||
case "overwrite location.href":
|
||||
window.location.href = newHref;
|
||||
break;
|
||||
}
|
||||
|
||||
return neverResolvingPromise;
|
||||
},
|
||||
"logout": options => {
|
||||
window.location.replace(transformUrlBeforeRedirect(keycloakInstance.createLogoutUrl(options)));
|
||||
return neverResolvingPromise;
|
||||
},
|
||||
"register": options => {
|
||||
window.location.href = transformUrlBeforeRedirect(keycloakInstance.createRegisterUrl(options));
|
||||
|
||||
return neverResolvingPromise;
|
||||
},
|
||||
"accountManagement": () => {
|
||||
var accountUrl = transformUrlBeforeRedirect(keycloakInstance.createAccountUrl());
|
||||
if (typeof accountUrl !== "undefined") {
|
||||
window.location.href = accountUrl;
|
||||
} else {
|
||||
const accountUrl = transformUrlBeforeRedirect(keycloakInstance.createAccountUrl());
|
||||
|
||||
if (accountUrl === "undefined") {
|
||||
throw new Error("Not supported by the OIDC server");
|
||||
}
|
||||
|
||||
switch (getRedirectMethod()) {
|
||||
case "location.replace":
|
||||
window.location.replace(accountUrl);
|
||||
break;
|
||||
case "overwrite location.href":
|
||||
window.location.href = accountUrl;
|
||||
break;
|
||||
}
|
||||
|
||||
return neverResolvingPromise;
|
||||
},
|
||||
"redirectUri": options => {
|
||||
|
@ -1,35 +1,30 @@
|
||||
import "./tools/Array.prototype.every";
|
||||
import { useMemo, useReducer, Fragment } from "react";
|
||||
import type { KcContextBase, Validators, Attribute } from "./getKcContext/KcContextBase";
|
||||
import { useKcMessage } from "./i18n/useKcMessage";
|
||||
import { getMsg } from "./i18n";
|
||||
import type { KcLanguageTag } from "./i18n";
|
||||
import { useConstCallback } from "powerhooks/useConstCallback";
|
||||
import { id } from "tsafe/id";
|
||||
import type { MessageKey } from "./i18n/useKcMessage";
|
||||
import type { MessageKey } from "./i18n";
|
||||
import { emailRegexp } from "./tools/emailRegExp";
|
||||
|
||||
export type KcContextLike = {
|
||||
messagesPerField: Pick<KcContextBase.Common["messagesPerField"], "existsError" | "get">;
|
||||
attributes: { name: string; value?: string; validators: Validators }[];
|
||||
passwordRequired: boolean;
|
||||
realm: { registrationEmailAsUsername: boolean };
|
||||
};
|
||||
|
||||
export function useGetErrors(params: {
|
||||
kcContext: {
|
||||
messagesPerField: Pick<KcContextBase.Common["messagesPerField"], "existsError" | "get">;
|
||||
profile: {
|
||||
attributes: { name: string; value?: string; validators: Validators }[];
|
||||
};
|
||||
locale?: { currentLanguageTag: KcLanguageTag };
|
||||
};
|
||||
}) {
|
||||
const {
|
||||
kcContext: {
|
||||
messagesPerField,
|
||||
profile: { attributes },
|
||||
},
|
||||
} = params;
|
||||
const { kcContext } = params;
|
||||
|
||||
const { msg, msgStr, advancedMsg, advancedMsgStr } = useKcMessage();
|
||||
const {
|
||||
messagesPerField,
|
||||
profile: { attributes },
|
||||
} = kcContext;
|
||||
|
||||
const { msg, msgStr, advancedMsg, advancedMsgStr } = getMsg(kcContext);
|
||||
|
||||
const getErrors = useConstCallback((params: { name: string; fieldValueByAttributeName: Record<string, { value: string }> }) => {
|
||||
const { name, fieldValueByAttributeName } = params;
|
||||
@ -318,6 +313,9 @@ export function useFormValidationSlice(params: {
|
||||
};
|
||||
passwordRequired: boolean;
|
||||
realm: { registrationEmailAsUsername: boolean };
|
||||
locale?: {
|
||||
currentLanguageTag: KcLanguageTag;
|
||||
};
|
||||
};
|
||||
/** NOTE: Try to avoid passing a new ref every render for better performances. */
|
||||
passwordValidators?: Validators;
|
||||
@ -387,6 +385,7 @@ export function useFormValidationSlice(params: {
|
||||
"profile": {
|
||||
"attributes": attributesWithPassword,
|
||||
},
|
||||
"locale": kcContext.locale,
|
||||
},
|
||||
});
|
||||
|
||||
|
@ -8,7 +8,7 @@ generateKeycloakThemeResources({
|
||||
"themeName": "keycloakify-demo-app",
|
||||
"reactAppBuildDirPath": pathJoin(sampleReactProjectDirPath, "build"),
|
||||
"keycloakThemeBuildingDirPath": pathJoin(sampleReactProjectDirPath, "build_keycloak_theme"),
|
||||
"keycloakThemeEmailDirPath": pathJoin(sampleReactProjectDirPath, "keycloak_theme_email"),
|
||||
"keycloakThemeEmailDirPath": pathJoin(sampleReactProjectDirPath, "keycloak_email"),
|
||||
"urlPathname": "/keycloakify-demo-app/",
|
||||
"urlOrigin": undefined,
|
||||
"extraPagesId": ["my-custom-page.ftl"],
|
||||
|
Reference in New Issue
Block a user