From 5d57c4fcdf39828c4403d81138a0fb3188fd882c Mon Sep 17 00:00:00 2001 From: KaWaite <34051327+KaWaite@users.noreply.github.com> Date: Thu, 28 Oct 2021 14:57:35 +0900 Subject: [PATCH] fix: password policy conversion in config (#113) * fix: passpolicy conversion in config * chore: make unit test * fix: type error * fix: add wrong field to test * fix: filter Co-authored-by: KaWaite --- src/config.test.ts | 19 +++++++++++++++++++ src/config.ts | 31 +++++++++++++++++++++---------- 2 files changed, 40 insertions(+), 10 deletions(-) create mode 100644 src/config.test.ts 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 }, + ); }