diff --git a/.gitignore b/.gitignore index 2d268c0..ba7615f 100644 --- a/.gitignore +++ b/.gitignore @@ -55,28 +55,47 @@ jspm_packages /dist_keycloak /build /storybook-static - -# ── Secrets and credentials ─────────────────────────────────────────────── -# Deliberately explicit. Nothing sensitive has ever been committed here (634 -# commits scanned before this repo went public: no .env, no key material, no -# credentials), and these patterns are what keeps that true. -# -# Real configuration lives in the .env file on the deploy host and in GitHub -# environment secrets. Neither belongs in git. -.env -.env.* -!.env.example -*.pem -*.key -*.p12 -*.keystore -id_rsa -id_ed25519 - -# ── Python (tooling that runs alongside this repo) ──────────────────────── -__pycache__/ -*.py[cod] -.pytest_cache/ -.ipynb_checkpoints/ -coverage.xml -.coverage + +# Markdown notes stay local +*.md + +# Local agent review guides +/accessibility.md +/code-quality.md +/craft-standard.md +/qc.md +/qa-testing.md +/safety-review.md + +# QC agents and the slash command stay in git +!.cursor/ +!.cursor/**/ +!.cursor/**/*.md + +# Local theme jar copies - build output, never commit +theme-update.jar + +# ── Secrets and credentials ─────────────────────────────────────────────── +# Deliberately explicit. Nothing sensitive has ever been committed here (634 +# commits scanned before this repo went public: no .env, no key material, no +# credentials), and these patterns are what keeps that true. +# +# Real configuration lives in the .env file on the deploy host and in GitHub +# environment secrets. Neither belongs in git. +.env +.env.* +!.env.example +*.pem +*.key +*.p12 +*.keystore +id_rsa +id_ed25519 + +# ── Python (tooling that runs alongside this repo) ──────────────────────── +__pycache__/ +*.py[cod] +.pytest_cache/ +.ipynb_checkpoints/ +coverage.xml +.coverage diff --git a/.keycloakify/realm-kc-25.json b/.keycloakify/realm-kc-25.json index eaf5f36..b3d13ec 100644 --- a/.keycloakify/realm-kc-25.json +++ b/.keycloakify/realm-kc-25.json @@ -28,9 +28,9 @@ "enabled": true, "sslRequired": "none", "registrationAllowed": true, - "registrationEmailAsUsername": false, + "registrationEmailAsUsername": true, "rememberMe": true, - "verifyEmail": false, + "verifyEmail": true, "loginWithEmailAllowed": true, "duplicateEmailsAllowed": false, "resetPasswordAllowed": true, @@ -438,7 +438,11 @@ "profile.attributes.favourite_pet": "Animal de compagnie préféré", "profile.attributes.favourite_pet.cat": "Chat", "profile.attributes.favourite_pet.dog": "Chien", - "profile.attributes.favourite_pet.bird": "Oiseau" + "profile.attributes.favourite_pet.bird": "Oiseau", + "firstName": "", + "lastName": "", + "profile.attributes.termsAccepted ": "", + "username": "" }, "hu": { "profile.attributes.favourite_pet": "" @@ -468,7 +472,11 @@ "profile.attributes.favourite_pet": "Favourite Pet", "profile.attributes.favourite_pet.cat": "Cat", "profile.attributes.favourite_pet.dog": "Dog", - "profile.attributes.favourite_pet.bird": "Bird" + "profile.attributes.favourite_pet.bird": "Bird", + "firstName": "First name", + "lastName": "Last name", + "profile.attributes.termsAccepted ": "Terms accepted", + "username": "Username" }, "it": { "profile.attributes.favourite_pet": "" @@ -477,7 +485,11 @@ "profile.attributes.favourite_pet": "Mascota favorita", "profile.attributes.favourite_pet.cat": "Gato", "profile.attributes.favourite_pet.dog": "Perro", - "profile.attributes.favourite_pet.bird": "Pájaro" + "profile.attributes.favourite_pet.bird": "Pájaro", + "firstName": "", + "lastName": "", + "profile.attributes.termsAccepted ": "", + "username": "" }, "cs": { "profile.attributes.favourite_pet": "" @@ -1692,14 +1704,14 @@ "subComponents": {}, "config": { "allowed-protocol-mapper-types": [ + "oidc-sha256-pairwise-sub-mapper", + "saml-user-property-mapper", "saml-role-list-mapper", + "oidc-address-mapper", "oidc-usermodel-property-mapper", "oidc-usermodel-attribute-mapper", - "oidc-address-mapper", - "oidc-sha256-pairwise-sub-mapper", - "oidc-full-name-mapper", - "saml-user-property-mapper", - "saml-user-attribute-mapper" + "saml-user-attribute-mapper", + "oidc-full-name-mapper" ] } }, @@ -1730,12 +1742,12 @@ "config": { "allowed-protocol-mapper-types": [ "oidc-address-mapper", - "saml-user-attribute-mapper", - "oidc-full-name-mapper", - "oidc-sha256-pairwise-sub-mapper", + "saml-role-list-mapper", "oidc-usermodel-property-mapper", + "oidc-sha256-pairwise-sub-mapper", + "oidc-full-name-mapper", + "saml-user-attribute-mapper", "saml-user-property-mapper", - "saml-role-list-mapper", "oidc-usermodel-attribute-mapper" ] } @@ -1777,7 +1789,7 @@ "subComponents": {}, "config": { "kc.user.profile.config": [ - "{\"attributes\":[{\"name\":\"username\",\"displayName\":\"${username}\",\"validations\":{\"length\":{\"min\":3,\"max\":255},\"username-prohibited-characters\":{},\"up-username-not-idn-homograph\":{}},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false},{\"name\":\"email\",\"displayName\":\"${email}\",\"validations\":{\"email\":{},\"length\":{\"max\":255}},\"required\":{\"roles\":[\"user\"]},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false},{\"name\":\"firstName\",\"displayName\":\"${firstName}\",\"validations\":{\"length\":{\"max\":255},\"person-name-prohibited-characters\":{}},\"required\":{\"roles\":[\"user\"]},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false},{\"name\":\"lastName\",\"displayName\":\"${lastName}\",\"validations\":{\"length\":{\"max\":255},\"person-name-prohibited-characters\":{}},\"required\":{\"roles\":[\"user\"]},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false},{\"name\":\"favourite_pet\",\"displayName\":\"${profile.attributes.favourite_pet}\",\"validations\":{\"options\":{\"options\":[\"cat\",\"dog\",\"bird\"]}},\"annotations\":{\"inputType\":\"select\",\"inputOptionLabelsI18nPrefix\":\"profile.attributes.favourite_pet\"},\"required\":{\"roles\":[\"admin\",\"user\"]},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false}],\"groups\":[{\"name\":\"user-metadata\",\"displayHeader\":\"User metadata\",\"displayDescription\":\"Attributes, which refer to user metadata\"}]}" + "{\"attributes\":[{\"name\":\"username\",\"displayName\":\"${username}\",\"validations\":{\"length\":{\"min\":3,\"max\":255},\"username-prohibited-characters\":{},\"up-username-not-idn-homograph\":{}},\"annotations\":{},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false},{\"name\":\"email\",\"displayName\":\"${email}\",\"validations\":{\"email\":{},\"length\":{\"max\":255}},\"required\":{\"roles\":[\"user\"]},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false},{\"name\":\"firstName\",\"displayName\":\"${firstName}\",\"validations\":{\"length\":{\"max\":255},\"person-name-prohibited-characters\":{}},\"annotations\":{},\"permissions\":{\"view\":[\"admin\"],\"edit\":[\"admin\"]},\"multivalued\":false},{\"name\":\"lastName\",\"displayName\":\"${lastName}\",\"validations\":{\"length\":{\"max\":255},\"person-name-prohibited-characters\":{}},\"annotations\":{},\"permissions\":{\"view\":[\"admin\"],\"edit\":[\"admin\"]},\"multivalued\":false},{\"name\":\"favourite_pet\",\"displayName\":\"${profile.attributes.favourite_pet}\",\"validations\":{\"options\":{\"options\":[\"cat\",\"dog\",\"bird\"]}},\"annotations\":{\"inputType\":\"select\",\"inputOptionLabelsI18nPrefix\":\"profile.attributes.favourite_pet\"},\"permissions\":{\"view\":[\"admin\"],\"edit\":[\"admin\"]},\"multivalued\":false},{\"name\":\"termsAccepted\",\"displayName\":\"${profile.attributes.termsAccepted }\",\"validations\":{},\"annotations\":{},\"required\":{\"roles\":[\"user\"]},\"permissions\":{\"view\":[\"admin\",\"user\"],\"edit\":[\"admin\",\"user\"]},\"multivalued\":false}],\"groups\":[{\"name\":\"user-metadata\",\"displayHeader\":\"User metadata\",\"displayDescription\":\"Attributes, which refer to user metadata\"}]}" ] } } diff --git a/src/login/KcContext.ts b/src/login/KcContext.ts index 4dcccea..60ec220 100644 --- a/src/login/KcContext.ts +++ b/src/login/KcContext.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-empty-object-type */ -import type { ExtendKcContext } from "keycloakify/login"; +import type { ExtendKcContext, PasswordPolicies } from "keycloakify/login/KcContext"; import type { KcEnvName, ThemeName } from "../kc.gen"; export type KcContextExtension = { @@ -12,6 +12,9 @@ export type KcContextExtension = { export type KcContextExtensionPerPage = { "signed-in.ftl": {}; + "login-update-password.ftl": { + passwordPolicies?: PasswordPolicies; + }; "register.ftl": { social?: { displayInfo?: boolean; diff --git a/src/login/KcPage.tsx b/src/login/KcPage.tsx index 8fbb0d1..5caf646 100644 --- a/src/login/KcPage.tsx +++ b/src/login/KcPage.tsx @@ -22,6 +22,8 @@ const Info = lazy(() => import("./pages/Info")); const SignedIn = lazy(() => import("./pages/SignedIn")); const IdpReviewUserProfile = lazy(() => import("./pages/IdpReviewUserProfile")); const LoginResetPassword = lazy(() => import("./pages/LoginResetPassword")); +const LoginUpdatePassword = lazy(() => import("./pages/LoginUpdatePassword")); +const Terms = lazy(() => import("./pages/Terms")); const Register = lazy(() => import("./pages/Register")); const UserProfileFormFields = lazy(() => import("./UserProfileFormFields")); @@ -35,6 +37,7 @@ export default function KcPage(props: { kcContext: KcContext }) { const Template = (templateProps: { children?: ReactNode; displayMessage?: boolean; + displayInfo?: boolean; socialProvidersNode?: ReactNode; infoNode?: ReactNode; headerNode?: ReactNode; @@ -42,6 +45,7 @@ export default function KcPage(props: { kcContext: KcContext }) { ); + case "login-update-password.ftl": + return ( + + ); + case "terms.ftl": + return ( + + ); case "register.ftl": return ( & { shouldRevealErrors?: boolean; + /** Register owns the visible checkbox. Other pages draw it here when the realm sends the attribute. */ + termsAccepted?: boolean; }; export default function UserProfileFormFields(props: ProfileFormFieldsProps) { @@ -28,10 +32,14 @@ export default function UserProfileFormFields(props: ProfileFormFieldsProps) { doMakeUserConfirmPassword, BeforeField, AfterField, - shouldRevealErrors = false + shouldRevealErrors = false, + termsAccepted } = props; - const { advancedMsg } = i18n; + const { advancedMsg, msgStr } = i18n; + const passwordPolicies = "passwordPolicies" in kcContext ? kcContext.passwordPolicies : undefined; + const loginUrl = kcContext.url.loginUrl; + const lockEmail = kcContext.pageId === "idp-review-user-profile.ftl"; const { formState: { formFieldStates, isFormSubmittable }, @@ -49,6 +57,28 @@ export default function UserProfileFormFields(props: ProfileFormFieldsProps) { onIsFormSubmittableValueChange(isFormSubmittable); }, [isFormSubmittable]); + useEffect(() => { + if (termsAccepted === undefined) { + return; + } + + const field = formFieldStatesRef.current.find(({ attribute }) => attribute.name === "termsAccepted"); + if (field === undefined || Array.isArray(field.valueOrValues)) { + return; + } + + const nextValue = termsAccepted ? "on" : ""; + if (field.valueOrValues === nextValue) { + return; + } + + dispatchFormAction({ + action: "update", + name: "termsAccepted", + valueOrValues: nextValue + }); + }, [termsAccepted, dispatchFormAction]); + useEffect(() => { if (!shouldRevealErrors) { return; @@ -83,6 +113,33 @@ export default function UserProfileFormFields(props: ProfileFormFieldsProps) { return ( <> {orderedFields.map(({ attribute, displayableErrors, valueOrValues }) => { + if (attribute.name === "termsAccepted") { + if (termsAccepted !== undefined) { + return ; + } + + return ( + + ); + } + + const passwordValue = typeof valueOrValues === "string" ? valueOrValues : ""; + const passwordRules = + attribute.name === "password" ? getPasswordRules(passwordValue, passwordPolicies) : []; + const describedBy = [ + passwordRules.length > 0 ? "password-requirements" : undefined, + displayableErrors.length > 0 ? `input-error-${attribute.name}` : undefined + ] + .filter(id => id !== undefined) + .join(" "); + return ( @@ -133,8 +190,29 @@ export default function UserProfileFormFields(props: ProfileFormFieldsProps) { dispatchFormAction={dispatchFormAction} kcClsx={kcClsx} i18n={i18n} + ariaDescribedBy={describedBy === "" ? undefined : describedBy} + loginUrl={loginUrl} + emailExistsMessage={msgStr("emailExistsMessage")} + passwordConfirmMessage={msgStr("invalidPasswordConfirmMessage")} + locked={lockEmail && attribute.name === "email" && (attribute.value ?? "") !== ""} + /> + {passwordRules.length > 0 && ( + 0 && passwordValue !== ""} + /> + )} + - {attribute.annotations.inputHelperTextAfter !== undefined && (
error.fieldIndex === fieldIndex); @@ -233,6 +320,15 @@ function FieldErrors(props: { attribute: Attribute; displayableErrors: FormField return null; } + const replacement = fieldErrorReplacement({ + attributeName: attribute.name, + errors: displayableErrors, + valueOrValues, + loginUrl, + emailExistsMessage, + passwordConfirmMessage + }); + return ( - {displayableErrors - .filter(error => error.fieldIndex === fieldIndex) - .map(({ errorMessage }, i, arr) => ( + {replacement ?? + displayableErrors.map(({ errorMessage }, i, arr) => ( {errorMessage} {arr.length - 1 !== i &&
} @@ -254,6 +349,114 @@ function FieldErrors(props: { attribute: Attribute; displayableErrors: FormField ); } +function fieldErrorReplacement(params: { + attributeName: string; + errors: FormFieldError[]; + valueOrValues: string | string[]; + loginUrl: string; + emailExistsMessage: string; + passwordConfirmMessage: string; +}): ReactNode | undefined { + const { attributeName, errors, valueOrValues, loginUrl, emailExistsMessage, passwordConfirmMessage } = params; + const value = typeof valueOrValues === "string" ? valueOrValues : ""; + + if (attributeName === "password") { + // Keycloak never sends the password back, so after a server rejection the field is empty + // even though the user typed one. Only a server "please specify" means it was missing. + const serverErrors = errors.filter(error => error.source.type === "server"); + const serverRejected = + serverErrors.length > 0 && !serverErrors.some(error => /specify password|required/i.test(plainMessage(error.errorMessageStr))); + if (serverRejected) { + // The checklist blocks submit until its rules pass, so a server rejection is a rule it + // cannot show (password history, not username…). Keycloak's message is the only reason. + return undefined; + } + return value === "" ? "Password is required." : "Password does not meet all requirements."; + } + + if (attributeName === "password-confirm") { + const mismatch = errors.some( + error => + (error.source.type === "other" && error.source.rule === "passwordConfirmMatchesPassword") || + plainMessage(error.errorMessageStr).includes(passwordConfirmMessage) + ); + if (mismatch) { + return "Passwords do not match."; + } + if (value === "") { + return "Password is required."; + } + } + + if (attributeName === "email" && errors.some(error => plainMessage(error.errorMessageStr).includes(emailExistsMessage))) { + return ( + <> + An account already exists with this email. Sign in instead. + + ); + } + + return undefined; +} + +// Keycloak only sends `autocomplete` for username and email; autofill needs the name hints too. +const defaultAutocomplete: Partial> = { + firstName: "given-name", + lastName: "family-name" +}; + +function plainMessage(message: string) { + return message.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim(); +} + +function TermsAcceptedField(props: { + attribute: Attribute; + valueOrValues: string | string[]; + displayableErrors: FormFieldError[]; + dispatchFormAction: (action: FormAction) => void; + kcClsx: KcClsx; +}) { + const { attribute, valueOrValues, displayableErrors, dispatchFormAction, kcClsx } = props; + const checked = valueOrValues === "on"; + const privacyHref = getPrivacyPolicyUrl(getAppHomeUrl()) ?? "/privacy"; + const describedBy = displayableErrors.length > 0 ? "input-error-termsAccepted" : undefined; + + return ( +
+ 0} + aria-labelledby={`${attribute.name}-label`} + aria-describedby={describedBy} + onChange={event => + dispatchFormAction({ + action: "update", + name: attribute.name, + valueOrValues: event.target.checked ? "on" : "" + }) + } + /> +

+ I acknowledge the{" "} + + Privacy Policy + + . +

+ {displayableErrors.length > 0 && ( + + + Please acknowledge the Privacy Policy to continue. + + )} +
+ ); +} + type InputFieldByTypeProps = { attribute: Attribute; valueOrValues: string | string[]; @@ -261,6 +464,12 @@ type InputFieldByTypeProps = { dispatchFormAction: React.Dispatch; i18n: I18n; kcClsx: KcClsx; + ariaDescribedBy?: string; + loginUrl: string; + emailExistsMessage: string; + passwordConfirmMessage: string; + /** Keep the posted value, but do not let the user change it. */ + locked?: boolean; }; function InputFieldByType(props: InputFieldByTypeProps) { @@ -336,18 +545,25 @@ function InputTag(props: InputFieldByTypeProps & { fieldIndex: number | undefine })()} className={kcClsx("kcInputClass")} aria-invalid={displayableErrors.find(error => error.fieldIndex === fieldIndex) !== undefined} - disabled={attribute.readOnly} - autoComplete={attribute.autocomplete} + aria-describedby={props.ariaDescribedBy} + readOnly={props.locked === true} + aria-readonly={props.locked === true ? true : undefined} + disabled={attribute.readOnly && props.locked !== true} + autoComplete={attribute.autocomplete ?? defaultAutocomplete[attribute.name]} placeholder={ attribute.annotations.inputTypePlaceholder !== undefined ? advancedMsgStr(attribute.annotations.inputTypePlaceholder) : attribute.name === "email" ? "you@example.org" - : attribute.name === "password" - ? "Create a password" - : attribute.name === "password-confirm" - ? "Re-enter your password" - : undefined + : attribute.name === "firstName" + ? "Enter your first name" + : attribute.name === "lastName" + ? "Enter your last name" + : attribute.name === "password" + ? "Create a password" + : attribute.name === "password-confirm" + ? "Re-enter your password" + : undefined } pattern={attribute.annotations.inputTypePattern} size={attribute.annotations.inputTypeSize === undefined ? undefined : parseInt(`${attribute.annotations.inputTypeSize}`)} @@ -361,7 +577,11 @@ function InputTag(props: InputFieldByTypeProps & { fieldIndex: number | undefine min={attribute.annotations.inputTypeMin} step={attribute.annotations.inputTypeStep} {...Object.fromEntries(Object.entries(attribute.html5DataAnnotations ?? {}).map(([key, value]) => [`data-${key}`, value]))} - onChange={event => + onChange={event => { + if (props.locked) { + return; + } + dispatchFormAction({ action: "update", name: attribute.name, @@ -380,8 +600,8 @@ function InputTag(props: InputFieldByTypeProps & { fieldIndex: number | undefine return event.target.value; })() - }) - } + }); + }} onBlur={() => dispatchFormAction({ action: "focus lost", @@ -401,7 +621,16 @@ function InputTag(props: InputFieldByTypeProps & { fieldIndex: number | undefine return ( <> - + as the header; custom pages use .h1 instead. */ +.civic-auth-header > span[data-kc-msg] { + display: block; + color: var(--primary); + font-size: 24px; + font-weight: 650; + letter-spacing: -0.02em; + line-height: 1.25; + text-wrap: balance; +} + /* Footer */ .civic-footer { width: 100%; @@ -1149,6 +1305,26 @@ select.form-control:focus, .civic-brand-panel { display: none; } + + .civic-mobile-legal { + display: block; + margin-top: auto; + padding-top: 24px; + color: #5b6472; + font-size: 13px; + line-height: 1.4; + text-align: center; + } + + .civic-mobile-legal a { + color: inherit; + text-decoration: none; + } + + .civic-mobile-legal a:hover { + color: var(--text); + text-decoration: underline; + } #kc-content-wrapper { padding: 40px; diff --git a/src/login/assets/civicdataspace-logo-v2.svg b/src/login/assets/civicdataspace-logo-v2.svg new file mode 100644 index 0000000..a480e5d --- /dev/null +++ b/src/login/assets/civicdataspace-logo-v2.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/login/components/CivicLogo.tsx b/src/login/components/CivicLogo.tsx index 7be49df..2065274 100644 --- a/src/login/components/CivicLogo.tsx +++ b/src/login/components/CivicLogo.tsx @@ -1,11 +1,11 @@ import React from "react"; -import logoPngUrl from "../assets/dataspacelogosep2025.png"; +import logoUrl from "../assets/civicdataspace-logo-v2.svg"; export const CivicLogo: React.FC = () => { return (
Civic DataSpace Logo diff --git a/src/login/components/CustomTemplate.tsx b/src/login/components/CustomTemplate.tsx index e7653b6..b78801b 100644 --- a/src/login/components/CustomTemplate.tsx +++ b/src/login/components/CustomTemplate.tsx @@ -1,5 +1,6 @@ import React from "react"; import { IconAlertCircle, IconArrowLeft, IconInfoCircle } from "@tabler/icons-react"; +import { kcSanitize } from "keycloakify/lib/kcSanitize"; import { getAppHomeUrl, getPrivacyPolicyUrl } from "../appHome"; import CivicLogo from "./CivicLogo"; @@ -19,6 +20,7 @@ type CustomTemplateProps = { }; }; displayMessage?: boolean; + displayInfo?: boolean; }; export default function CustomTemplate({ @@ -27,7 +29,8 @@ export default function CustomTemplate({ infoNode, headerNode, kcContext, - displayMessage = true + displayMessage = true, + displayInfo = true }: CustomTemplateProps) { const homeHref = getAppHomeUrl() ?? kcContext.client?.baseUrl ?? "/"; const privacyHref = getPrivacyPolicyUrl(homeHref); @@ -62,7 +65,7 @@ export default function CustomTemplate({
@@ -75,9 +78,14 @@ export default function CustomTemplate({ {socialProvidersNode} {/* Info Section (e.g., registration link) */} - {infoNode} + {displayInfo && infoNode}
+ {/* Right Panel with Logo */} diff --git a/src/login/components/PasswordRequirements.tsx b/src/login/components/PasswordRequirements.tsx new file mode 100644 index 0000000..5f6dad8 --- /dev/null +++ b/src/login/components/PasswordRequirements.tsx @@ -0,0 +1,110 @@ +import { IconCheck } from "@tabler/icons-react"; +import type { PasswordPolicies } from "keycloakify/login/KcContext"; + +type PasswordRule = { + id: string; + label: string; + met: boolean; +}; + +export function getPasswordRules(password: string, policies: PasswordPolicies | undefined): PasswordRule[] { + if (policies === undefined) { + return []; + } + + const rules: PasswordRule[] = []; + + if (policies.length) { + rules.push({ + id: "length", + label: `At least ${policies.length} characters`, + met: password.length >= policies.length + }); + } + + if (policies.upperCase) { + const count = countLetters(password, "upper"); + rules.push({ + id: "upperCase", + label: policies.upperCase === 1 ? "One uppercase letter" : `At least ${policies.upperCase} uppercase letters`, + met: count >= policies.upperCase + }); + } + + if (policies.digits) { + const count = password.split("").filter(char => !Number.isNaN(Number.parseInt(char, 10))).length; + rules.push({ + id: "digits", + label: policies.digits === 1 ? "One number" : `At least ${policies.digits} numbers`, + met: count >= policies.digits + }); + } + + if (policies.lowerCase) { + const count = countLetters(password, "lower"); + rules.push({ + id: "lowerCase", + label: policies.lowerCase === 1 ? "One lowercase letter" : `At least ${policies.lowerCase} lowercase letters`, + met: count >= policies.lowerCase + }); + } + + if (policies.specialChars) { + const count = password.split("").filter(char => !/[a-zA-Z0-9]/.test(char)).length; + rules.push({ + id: "specialChars", + label: policies.specialChars === 1 ? "One special character" : `At least ${policies.specialChars} special characters`, + met: count >= policies.specialChars + }); + } + + if (policies.maxLength) { + rules.push({ + id: "maxLength", + label: `At most ${policies.maxLength} characters`, + met: password.length > 0 && password.length <= policies.maxLength + }); + } + + return rules; +} + +export default function PasswordRequirements(props: { password: string; rules: PasswordRule[]; showInvalid: boolean }) { + const { password, rules, showInvalid } = props; + + if (rules.length === 0) { + return null; + } + + return ( +
+

Password must contain

+
    + {rules.map(rule => { + const met = password.length > 0 && rule.met; + return ( +
  • + {met ? ( + + ) : ( + + )} + {met ? "Met: " : "Not met: "} + {rule.label} +
  • + ); + })} +
+
+ ); +} + +function countLetters(password: string, kind: "upper" | "lower") { + return password.split("").filter(char => { + const isLetter = char.toUpperCase() !== char.toLowerCase(); + if (!isLetter) { + return false; + } + return kind === "upper" ? char === char.toUpperCase() : char === char.toLowerCase(); + }).length; +} diff --git a/src/login/pages/Error.stories.tsx b/src/login/pages/Error.stories.tsx index 0821d91..f54a7b3 100644 --- a/src/login/pages/Error.stories.tsx +++ b/src/login/pages/Error.stories.tsx @@ -37,3 +37,43 @@ export const AccountCreationFailed: Story = { /> ) }; + +export const InvalidRedirectUri: Story = { + render: () => ( + + ) +}; + +export const UnknownClient: Story = { + render: () => ( + + ) +}; + +export const IdentityAlreadyLinked: Story = { + render: () => ( + + ) +}; diff --git a/src/login/pages/Error.tsx b/src/login/pages/Error.tsx index 87e2e02..c15f2bd 100644 --- a/src/login/pages/Error.tsx +++ b/src/login/pages/Error.tsx @@ -1,4 +1,5 @@ import { IconArrowLeft } from "@tabler/icons-react"; +import { kcSanitize } from "keycloakify/lib/kcSanitize"; import type { PageProps } from "keycloakify/login/pages/PageProps"; import type { KcContext } from "../KcContext"; import type { I18n } from "../i18n"; @@ -7,10 +8,16 @@ function isAccountCreationError(summary: string | undefined) { return /could not create|error creating|creating (your )?account|register/i.test(summary ?? ""); } +function isIdentityProviderAuthFailure(summary: string | undefined) { + return /authenticating with identity provider|identity provider authentication/i.test(summary ?? ""); +} + export default function Error(props: PageProps, I18n>) { const { kcContext, i18n, doUseDefaultCss, Template, classes } = props; const { url, message } = kcContext; - const accountCreationFailed = isAccountCreationError(message?.summary); + const summary = message?.summary; + const accountCreationFailed = isAccountCreationError(summary); + const identityProviderFailed = !accountCreationFailed && isIdentityProviderAuthFailure(summary); return ( diff --git a/src/login/pages/IdpReviewUserProfile.stories.tsx b/src/login/pages/IdpReviewUserProfile.stories.tsx index a45a273..965795a 100644 --- a/src/login/pages/IdpReviewUserProfile.stories.tsx +++ b/src/login/pages/IdpReviewUserProfile.stories.tsx @@ -23,12 +23,19 @@ export const Default: Story = { lastName: { validators: {}, annotations: { inputType: "hidden" } }, email: { value: "jordan.rivera@gmail.com", - readOnly: true, + readOnly: false, validators: {}, annotations: {} }, password: { validators: {}, annotations: { inputType: "hidden" } }, - "password-confirm": { validators: {}, annotations: { inputType: "hidden" } } + "password-confirm": { validators: {}, annotations: { inputType: "hidden" } }, + termsAccepted: { + name: "termsAccepted", + value: "", + required: true, + validators: {}, + annotations: {} + } } } }} diff --git a/src/login/pages/IdpReviewUserProfile.tsx b/src/login/pages/IdpReviewUserProfile.tsx index 4419848..0e8af6a 100644 --- a/src/login/pages/IdpReviewUserProfile.tsx +++ b/src/login/pages/IdpReviewUserProfile.tsx @@ -48,10 +48,12 @@ export default function IdpReviewUserProfile(props: IdpReviewUserProfileProps) { AfterField={({ attribute }) => attribute.name === "email" ? ( <> - - - Verified - + {(attribute.value ?? "") !== "" && ( + + + Verified + + )} Use a different Google account diff --git a/src/login/pages/Info.stories.tsx b/src/login/pages/Info.stories.tsx index 474cc8c..7336ce8 100644 --- a/src/login/pages/Info.stories.tsx +++ b/src/login/pages/Info.stories.tsx @@ -12,13 +12,31 @@ export default meta; type Story = StoryObj; -export const AccountVerified: Story = { +export const RequiredAction: Story = { render: () => ( + ) +}; + +export const EmailAlreadyVerified: Story = { + render: () => ( + diff --git a/src/login/pages/Info.tsx b/src/login/pages/Info.tsx index d969d72..779ccfc 100644 --- a/src/login/pages/Info.tsx +++ b/src/login/pages/Info.tsx @@ -1,3 +1,4 @@ +import { kcSanitize } from "keycloakify/lib/kcSanitize"; import type { PageProps } from "keycloakify/login/pages/PageProps"; import type { KcContext } from "../KcContext"; import type { I18n } from "../i18n"; @@ -7,16 +8,89 @@ function isAccountCreated(summary: string | undefined) { return /account created|account is ready|has been created/i.test(summary ?? ""); } -function isPasswordResetEmail(summary: string | undefined) { +export function isPasswordResetEmail(summary: string | undefined) { return /further instructions|reset your password|check your email|we've sent/i.test(summary ?? ""); } +export function CheckYourEmailStatus(props: { loginUrl: string }) { + return ( + + If an account exists for this +
+ email, we've sent instructions +
+ to reset your password. + + } + action={ + + Back to Sign In + + } + /> + ); +} + export default function Info(props: PageProps, I18n>) { const { kcContext, i18n, doUseDefaultCss, Template, classes } = props; const summary = kcContext.message?.summary; const checkEmail = isPasswordResetEmail(summary); const accountCreated = isAccountCreated(summary); + if (!checkEmail && !accountCreated) { + const { advancedMsgStr } = i18n; + const { messageHeader, message, requiredActions, skipLink, pageRedirectUri, actionUri, client } = kcContext; + const messageSummary = message?.summary ?? ""; + const heading = messageHeader ? advancedMsgStr(messageHeader) : messageSummary; + const actionLabels = requiredActions + ?.map(requiredAction => advancedMsgStr(`requiredAction.${requiredAction}`)) + .filter(label => label.length > 0); + const subtitle = actionLabels?.length + ? actionLabels.join(", ") + : messageHeader && messageSummary && messageSummary !== heading + ? messageSummary + : undefined; + const link = skipLink + ? undefined + : pageRedirectUri + ? { href: pageRedirectUri, label: "Back to application" } + : actionUri + ? { href: actionUri, label: "Continue" } + : client.baseUrl + ? { href: client.baseUrl, label: "Back to application" } + : undefined; + + return ( + + ); + } + return (