diff --git a/src/config.test.ts b/src/config.test.ts new file mode 100644 index 000000000..a1d47164d --- /dev/null +++ b/src/config.test.ts @@ -0,0 +1,19 @@ +import { convertPasswordPolicy } from "./config"; + +test("convert password policy to regular expression", () => { + const passwordPolicy = { + whiteSpace: "(?=.*\\s)", + highSecurity: "^(?=.*[a-z])(?=.*[A-Z])((?=(.*\\d){2}))", + wrong: "@[", + }; + const actual = convertPasswordPolicy(passwordPolicy); + expect(actual).toStrictEqual({ + whiteSpace: /(?=.*\s)/, + highSecurity: /^(?=.*[a-z])(?=.*[A-Z])((?=(.*\d){2}))/, + }); +}); + +test("return undefined if no password policy", () => { + const actual = convertPasswordPolicy(undefined); + expect(actual).toBeUndefined(); +}); diff --git a/src/config.ts b/src/config.ts index f83172e4b..2d62d646f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -31,6 +31,24 @@ export const defaultConfig: Config = { published: window.origin + "/p/{}/", }; +export function convertPasswordPolicy(passwordPolicy?: { + [key: string]: string; +}): { [key: string]: RegExp | undefined } | undefined { + if (!passwordPolicy) return; + return Object.fromEntries( + Object.entries(passwordPolicy) + .map(([k, v]) => { + if (typeof v !== "string") return [k, undefined]; + try { + return [k, new RegExp(v)]; + } catch { + return [k, undefined]; + } + }) + .filter(i => !!i[1]), + ); +} + export default async function loadConfig() { if (window.REEARTH_CONFIG) return; window.REEARTH_CONFIG = defaultConfig; @@ -41,14 +59,7 @@ export default async function loadConfig() { if (!window.REEARTH_CONFIG?.passwordPolicy) return; - window.REEARTH_CONFIG.passwordPolicy = Object.entries( - Object.values(window.REEARTH_CONFIG.passwordPolicy).map((k, v) => { - if (typeof v !== "string") return undefined; - try { - return [k, new RegExp(v)]; - } catch { - return undefined; - } - }), - ) as Config["passwordPolicy"]; + window.REEARTH_CONFIG.passwordPolicy = convertPasswordPolicy( + window.REEARTH_CONFIG.passwordPolicy as { [key: string]: string }, + ); }