@sqrzro/auth 4.0.0-alpha.7 → 4.0.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-dev.log +32 -18
  3. package/dist/components/Auth/index.d.ts +2 -2
  4. package/dist/components/Password/index.d.ts +2 -2
  5. package/dist/components/Password/index.js +1 -1
  6. package/dist/components/PasswordComplexityFormField/index.d.ts +8 -0
  7. package/dist/components/PasswordComplexityFormField/index.js +10 -0
  8. package/dist/components/PasswordComplexityInput/index.d.ts +5 -0
  9. package/dist/components/PasswordComplexityInput/index.js +9 -0
  10. package/dist/extend-repository.d.ts +0 -0
  11. package/dist/extend-repository.js +1 -0
  12. package/dist/forms/LoginForm/server.js +2 -2
  13. package/dist/forms/PasswordForm/index.d.ts +6 -1
  14. package/dist/forms/PasswordForm/index.js +19 -4
  15. package/dist/forms/PasswordForm/server.js +9 -6
  16. package/dist/forms/PasswordResetForm/index.js +5 -3
  17. package/dist/forms/PasswordResetForm/server.js +10 -7
  18. package/dist/get-auth-proxy.d.ts +6 -0
  19. package/dist/get-auth-proxy.js +17 -0
  20. package/dist/handle-auth-proxy.d.ts +5 -0
  21. package/dist/handle-auth-proxy.js +14 -0
  22. package/dist/index.d.ts +3 -1
  23. package/dist/index.js +1 -1
  24. package/dist/interfaces.d.ts +3 -0
  25. package/dist/mail/PasswordMail.d.ts +5 -0
  26. package/dist/mail/PasswordMail.js +6 -0
  27. package/dist/rules/complexity.d.ts +4 -0
  28. package/dist/rules/complexity.js +9 -0
  29. package/dist/rules/password.d.ts +3 -0
  30. package/dist/rules/password.js +6 -0
  31. package/dist/utility/create-complexity-schema.d.ts +4 -0
  32. package/dist/utility/create-complexity-schema.js +22 -0
  33. package/dist/utility/create-password-schema.d.ts +0 -0
  34. package/dist/utility/create-password-schema.js +1 -0
  35. package/dist/utility/get-complexity.d.ts +3 -0
  36. package/dist/utility/get-complexity.js +10 -0
  37. package/dist/utility/interfaces.d.ts +12 -0
  38. package/dist/utility/interfaces.js +8 -0
  39. package/dist/utility/lang.d.ts +2 -0
  40. package/dist/utility/lang.js +9 -0
  41. package/dist/utility/validate-complexity.d.ts +3 -0
  42. package/dist/utility/validate-complexity.js +33 -0
  43. package/dist/utility/validate-password-complexity.d.ts +14 -0
  44. package/dist/utility/validate-password-complexity.js +65 -0
  45. package/package.json +4 -3
  46. package/src/components/Auth/index.tsx +3 -3
  47. package/src/components/Password/index.tsx +5 -4
  48. package/src/components/PasswordComplexityFormField/index.tsx +34 -0
  49. package/src/forms/LoginForm/server.ts +3 -3
  50. package/src/forms/PasswordForm/index.tsx +86 -8
  51. package/src/forms/PasswordForm/server.ts +13 -7
  52. package/src/forms/PasswordResetForm/index.tsx +10 -4
  53. package/src/forms/PasswordResetForm/server.ts +12 -8
  54. package/src/get-auth-proxy.ts +34 -0
  55. package/src/index.ts +5 -1
  56. package/src/interfaces.ts +4 -0
  57. package/src/mail/PasswordMail.tsx +16 -0
  58. package/src/rules/complexity.ts +14 -0
  59. package/src/utility/create-complexity-schema.ts +44 -0
  60. package/src/utility/get-complexity.ts +14 -0
  61. package/src/utility/interfaces.ts +11 -0
  62. package/src/utility/lang.ts +14 -0
  63. package/src/utility/validate-complexity.ts +53 -0
  64. package/src/handle-proxy.ts +0 -23
@@ -0,0 +1,65 @@
1
+ import { formatPlural, getEntries, getKeys } from '@sqrzro/utility';
2
+ import { z } from 'zod';
3
+ export var PasswordComplexityKey;
4
+ (function (PasswordComplexityKey) {
5
+ PasswordComplexityKey["LENGTH"] = "LENGTH";
6
+ PasswordComplexityKey["UPPERCASE"] = "UPPERCASE";
7
+ PasswordComplexityKey["LOWERCASE"] = "LOWERCASE";
8
+ PasswordComplexityKey["NUMBER"] = "NUMBER";
9
+ PasswordComplexityKey["SPECIAL"] = "SPECIAL";
10
+ })(PasswordComplexityKey || (PasswordComplexityKey = {}));
11
+ const lang = {
12
+ [PasswordComplexityKey.LENGTH]: (value) => `At least ${formatPlural('character', value)} long`,
13
+ [PasswordComplexityKey.UPPERCASE]: (value) => `Contain at least ${formatPlural('uppercase letter', value)}`,
14
+ [PasswordComplexityKey.LOWERCASE]: (value) => `Contain at least ${formatPlural('lowercase letter', value)}`,
15
+ [PasswordComplexityKey.NUMBER]: (value) => `Contain at least ${formatPlural('number', value)}`,
16
+ [PasswordComplexityKey.SPECIAL]: (value) => `Contain at least ${formatPlural('special character', value)}`,
17
+ };
18
+ function createSchema(complexity) {
19
+ let result = z.string();
20
+ if (complexity.LENGTH) {
21
+ result = result.min(complexity.LENGTH, PasswordComplexityKey.LENGTH);
22
+ }
23
+ if (complexity.UPPERCASE) {
24
+ result = result.regex(new RegExp(`(?:.*[A-Z]){${complexity.UPPERCASE}}`), PasswordComplexityKey.UPPERCASE);
25
+ }
26
+ if (complexity.LOWERCASE) {
27
+ result = result.regex(new RegExp(`(?:.*[a-z]){${complexity.LOWERCASE}}`), PasswordComplexityKey.LOWERCASE);
28
+ }
29
+ if (complexity.NUMBER) {
30
+ result = result.regex(new RegExp(`(?:.*\\d){${complexity.NUMBER}}`), PasswordComplexityKey.NUMBER);
31
+ }
32
+ if (complexity.SPECIAL) {
33
+ result = result.regex(new RegExp(`(?:.*[@$!%*?&]){${complexity.SPECIAL}}`), PasswordComplexityKey.SPECIAL);
34
+ }
35
+ return result;
36
+ }
37
+ function getDefaultComplexityResult(complexity) {
38
+ return getEntries(complexity).map(([key, value]) => ({
39
+ status: false,
40
+ value: lang[key](value),
41
+ }));
42
+ }
43
+ function transformResult(complexity, errors) {
44
+ // If there are errors that don't match the complexity keys (for example, the initial state), return the default result
45
+ if (errors.find((error) => !getKeys(complexity).includes(error))) {
46
+ return getDefaultComplexityResult(complexity);
47
+ }
48
+ return getEntries(complexity).map(([key, value]) => ({
49
+ status: !errors.includes(key),
50
+ value: lang[key](value),
51
+ }));
52
+ }
53
+ function validatePasswordComplexity(complexity, password) {
54
+ try {
55
+ createSchema(complexity).parse(password);
56
+ return transformResult(complexity, []);
57
+ }
58
+ catch (error) {
59
+ if (error instanceof z.ZodError) {
60
+ return transformResult(complexity, error.issues.map((issue) => issue.message));
61
+ }
62
+ return getDefaultComplexityResult(complexity);
63
+ }
64
+ }
65
+ export default validatePasswordComplexity;
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@sqrzro/auth",
3
3
  "type": "module",
4
- "version": "4.0.0-alpha.7",
4
+ "version": "4.0.0-alpha.9",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "dependencies": {
8
8
  "zod": "^4.3.6",
9
- "@sqrzro/server": "^4.0.0-alpha.16",
10
- "@sqrzro/ui": "^4.0.0-alpha.13"
9
+ "@sqrzro/server": "^4.0.0-alpha.18",
10
+ "@sqrzro/utility": "^4.0.0-alpha.3",
11
+ "@sqrzro/ui": "^4.0.0-alpha.14"
11
12
  },
12
13
  "devDependencies": {
13
14
  "@types/react": "^19.2.7",
@@ -8,7 +8,7 @@ import type { AuthClassNameProps } from '../../interfaces';
8
8
 
9
9
  import Password from '../Password';
10
10
 
11
- interface AuthPageProps extends AuthClassNameProps, NextPageProps {
11
+ export interface AuthProps extends AuthClassNameProps, NextPageProps {
12
12
  logo?: React.ReactElement;
13
13
  }
14
14
 
@@ -16,7 +16,7 @@ async function AuthComponent({
16
16
  classNames,
17
17
  params,
18
18
  searchParams,
19
- }: AuthPageProps): Promise<React.ReactElement> {
19
+ }: AuthProps): Promise<React.ReactElement> {
20
20
  const awaitedParams = await params;
21
21
 
22
22
  if (!awaitedParams || !Array.isArray(awaitedParams.auth) || awaitedParams.auth.length !== 1) {
@@ -38,7 +38,7 @@ async function AuthComponent({
38
38
  return notFound();
39
39
  }
40
40
 
41
- function Auth({ classNames, logo, ...props }: AuthPageProps): React.ReactElement {
41
+ function Auth({ classNames, logo, ...props }: AuthProps): React.ReactElement {
42
42
  return (
43
43
  <div className={classNames?.root}>
44
44
  <div className={classNames?.logo}>{logo}</div>
@@ -1,12 +1,11 @@
1
1
  import { validateReset } from '@sqrzro/server/auth';
2
+ import { NextPageProps } from '@sqrzro/ui/utility';
2
3
 
3
4
  import PasswordForm from '../../forms/PasswordForm';
4
5
  import PasswordResetForm from '../../forms/PasswordResetForm';
5
6
  import type { AuthClassNameProps } from '../../interfaces';
6
7
 
7
- interface PasswordProps extends AuthClassNameProps {
8
- searchParams?: Promise<Record<string, string>> | null;
9
- }
8
+ interface PasswordProps extends AuthClassNameProps, NextPageProps {}
10
9
 
11
10
  async function Password({
12
11
  classNames,
@@ -24,7 +23,9 @@ async function Password({
24
23
  }
25
24
  }
26
25
 
27
- return <PasswordForm classNames={classNames} />;
26
+ return (
27
+ <PasswordForm classNames={classNames} defaults={{ email: awaitedSearchParams?.email }} />
28
+ );
28
29
  }
29
30
 
30
31
  export default Password;
@@ -0,0 +1,34 @@
1
+ 'use client';
2
+
3
+ import { Fragment } from 'react';
4
+
5
+ import { PasswordComplexity, PasswordFormField } from '@sqrzro/ui/forms';
6
+ import type { PasswordFormFieldProps } from '@sqrzro/ui/forms';
7
+
8
+ import getComplexity from '../../utility/get-complexity';
9
+ import validatePasswordComplexity from '../../utility/validate-complexity';
10
+ import type { PasswordComplexityObject } from '../../utility/interfaces';
11
+
12
+ interface PasswordComplexityFormFieldProps extends PasswordFormFieldProps {
13
+ complexity?: PasswordComplexityObject;
14
+ onComplexity?: (isValid: boolean) => void;
15
+ }
16
+
17
+ function PasswordComplexityFormField({
18
+ complexity,
19
+ onComplexity,
20
+ value,
21
+ ...props
22
+ }: PasswordComplexityFormFieldProps): React.ReactElement {
23
+ return (
24
+ <Fragment>
25
+ <PasswordFormField value={value} {...props} />
26
+ <PasswordComplexity
27
+ data={validatePasswordComplexity(getComplexity(complexity), value)}
28
+ onComplexity={onComplexity}
29
+ />
30
+ </Fragment>
31
+ );
32
+ }
33
+
34
+ export default PasswordComplexityFormField;
@@ -10,13 +10,13 @@ import type { LoginFormFields } from './interfaces';
10
10
 
11
11
  const schema = z
12
12
  .object({
13
- email: z.email(),
14
- password: z.string(),
13
+ email: z.email().nonempty(),
14
+ password: z.string().nonempty(),
15
15
  redirect: z.string().optional(),
16
16
  })
17
17
  .required({ email: true, password: true });
18
18
 
19
- async function fn(data: LoginFormFields): Promise<void> {
19
+ async function fn(data: z.infer<typeof schema>): Promise<void> {
20
20
  log('auth', 'LoginForm', `Login for email ${data.email}`);
21
21
 
22
22
  const userID = await validateUser(data.email, data.password);
@@ -1,24 +1,102 @@
1
1
  'use client';
2
2
 
3
- import { Fragment } from 'react';
3
+ import { Fragment, useState } from 'react';
4
4
 
5
- import { Form, FormSubmit, TextFormField, useForm } from '@sqrzro/ui/forms';
5
+ import { Link } from '@sqrzro/ui/components';
6
+ import { Default, Form, FormSubmit, TextFormField, useForm } from '@sqrzro/ui/forms';
6
7
 
7
8
  import type { AuthClassNameProps } from '../../interfaces';
8
9
 
9
10
  import submit from './server';
11
+ import type { PasswordFormFields } from './interfaces';
10
12
 
11
- function PasswordForm({ classNames }: AuthClassNameProps): React.ReactElement | null {
12
- const { fieldProps, formProps } = useForm({
13
+ interface PasswordFormProps extends AuthClassNameProps {
14
+ defaults?: Default<PasswordFormFields>;
15
+ }
16
+
17
+ function PasswordForm({ classNames, defaults }: PasswordFormProps): React.ReactElement | null {
18
+ const [sentCount, setSentCount] = useState(0);
19
+
20
+ const { fieldProps, formData, formProps, setFormData, submitForm } = useForm({
21
+ defaults,
13
22
  onSubmit: submit,
23
+ onSuccess: () => {
24
+ setSentCount(sentCount + 1);
25
+ },
14
26
  });
15
27
 
28
+ function handleResend(event: React.MouseEvent<HTMLAnchorElement>): void {
29
+ event.preventDefault();
30
+ submitForm();
31
+ }
32
+
33
+ function handleReset(event: React.MouseEvent<HTMLAnchorElement>): void {
34
+ event.preventDefault();
35
+
36
+ setFormData('email', '');
37
+ setSentCount(0);
38
+ }
39
+
16
40
  return (
17
41
  <Fragment>
18
- <Form {...formProps}>
19
- <TextFormField {...fieldProps('email')} hasAssistiveError />
20
- <FormSubmit isFullWidth>Send Email</FormSubmit>
21
- </Form>
42
+ <div style={{ display: sentCount === 0 ? 'block' : 'none' }}>
43
+ <Form {...formProps}>
44
+ <h1 className={classNames?.title}>Reset Your Password</h1>
45
+ <p className="text-sm">
46
+ Enter the email address associated with your account and we&#39;ll send you
47
+ a link to reset your password.
48
+ </p>
49
+ <TextFormField {...fieldProps('email')} hasAssistiveError />
50
+ <div className={classNames?.actions}>
51
+ <FormSubmit isFullWidth>Send Email</FormSubmit>
52
+ </div>
53
+ <footer className={classNames?.footer}>
54
+ <Link className={classNames?.link} href="/auth/login">
55
+ Back
56
+ </Link>
57
+ </footer>
58
+ </Form>
59
+ </div>
60
+ <div style={{ display: sentCount === 0 ? 'none' : 'block' }}>
61
+ <div className={classNames?.form}>
62
+ <h1 className={classNames?.title}>Check Your Email</h1>
63
+ {sentCount === 1 ? (
64
+ <Fragment>
65
+ <p className="text-sm">
66
+ If <strong>{formData.email}</strong> matches an email we have on
67
+ file, then we&#39;ve sent you an email containing further
68
+ instructions for resetting your password.
69
+ </p>
70
+ <p className="text-sm">
71
+ If you haven&#39;t received an email in 5 minutes, check your spam,{' '}
72
+ <Link className={classNames?.link} onClick={handleResend}>
73
+ resend
74
+ </Link>
75
+ , or{' '}
76
+ <Link className={classNames?.link} onClick={handleReset}>
77
+ try a different email address
78
+ </Link>
79
+ .
80
+ </p>
81
+ </Fragment>
82
+ ) : (
83
+ <Fragment>
84
+ <p className="text-sm">
85
+ We&#39;ve resent password reset instructions to{' '}
86
+ <strong>{formData.email}</strong>, if it is an email we have on
87
+ file.
88
+ </p>
89
+ <p className="text-sm">
90
+ Please check again. If you still haven&#39;t received an email,{' '}
91
+ <Link className={classNames?.link} onClick={handleReset}>
92
+ try a different email address
93
+ </Link>
94
+ .
95
+ </p>
96
+ </Fragment>
97
+ )}
98
+ </div>
99
+ </div>
22
100
  </Fragment>
23
101
  );
24
102
  }
@@ -2,19 +2,25 @@
2
2
 
3
3
  import { createReset } from '@sqrzro/server/auth';
4
4
  import { FormResponse, submitForm } from '@sqrzro/server/forms';
5
+ import { sendMail } from '@sqrzro/server/mail';
5
6
  import { z } from 'zod';
6
7
 
8
+ import PasswordMail from '../../mail/PasswordMail';
9
+
7
10
  import type { PasswordFormFields } from './interfaces';
8
11
 
9
- const schema = z
10
- .object({
11
- email: z.email(),
12
- })
13
- .required({ email: true });
12
+ const schema = z.object({
13
+ email: z.email().nonempty(),
14
+ });
14
15
 
15
- async function fn(data: PasswordFormFields): Promise<void> {
16
+ async function fn(data: z.infer<typeof schema>): Promise<void> {
16
17
  const token = await createReset('PASSWORD', data.email);
17
- console.log(token);
18
+
19
+ if (!token) {
20
+ return;
21
+ }
22
+
23
+ await sendMail(data.email, PasswordMail, { token });
18
24
  }
19
25
 
20
26
  async function submit(formData: PasswordFormFields): FormResponse<void> {
@@ -1,9 +1,10 @@
1
1
  'use client';
2
2
 
3
- import { Fragment } from 'react';
3
+ import { Fragment, useState } from 'react';
4
4
 
5
- import { Form, FormSubmit, PasswordFormField, useForm } from '@sqrzro/ui/forms';
5
+ import { Form, FormSubmit, useForm } from '@sqrzro/ui/forms';
6
6
 
7
+ import PasswordComplexityFormField from '../../components/PasswordComplexityFormField';
7
8
  import type { AuthClassNameProps } from '../../interfaces';
8
9
 
9
10
  import submit from './server';
@@ -16,6 +17,8 @@ function PasswordResetForm({
16
17
  classNames,
17
18
  token,
18
19
  }: Readonly<PasswordResetFormProps>): React.ReactElement | null {
20
+ const [isDisabled, setIsDisabled] = useState(true);
21
+
19
22
  const { fieldProps, formProps } = useForm({
20
23
  defaults: { token },
21
24
  onSubmit: submit,
@@ -24,8 +27,11 @@ function PasswordResetForm({
24
27
  return (
25
28
  <Fragment>
26
29
  <Form {...formProps}>
27
- <PasswordFormField {...fieldProps('password')} />
28
- <FormSubmit isFullWidth>Reset Password</FormSubmit>
30
+ <PasswordComplexityFormField
31
+ {...fieldProps('password')}
32
+ onComplexity={(isValid) => setIsDisabled(!isValid)}
33
+ />
34
+ <FormSubmit isDisabled={isDisabled}>Reset Password</FormSubmit>
29
35
  </Form>
30
36
  </Fragment>
31
37
  );
@@ -5,17 +5,21 @@ import { FormResponse, submitForm } from '@sqrzro/server/forms';
5
5
  import { redirect } from 'next/navigation';
6
6
  import { z } from 'zod';
7
7
 
8
+ import getComplexityRule from '../../rules/complexity';
9
+ import getComplexity from '../../utility/get-complexity';
10
+
8
11
  import type { PasswordResetFormFields } from './interfaces';
9
12
 
10
- const schema = z
11
- .object({
12
- password: z.string(),
13
- token: z.string().regex(/[A-Za-z0-9]{48}/u),
14
- })
15
- .required({ password: true, token: true });
13
+ const schema = z.object({
14
+ password: getComplexityRule(getComplexity()).nonempty(),
15
+ token: z
16
+ .string()
17
+ .regex(/[A-Za-z0-9]{48}/u)
18
+ .nonempty(),
19
+ });
16
20
 
17
- async function fn(data: PasswordResetFormFields): Promise<void> {
18
- await updatePasswordWithToken(data.token, data.password);
21
+ async function fn(data: z.infer<typeof schema>): Promise<void> {
22
+ await updatePasswordWithToken('PASSWORD', data.token, data.password);
19
23
  return redirect('/auth/login');
20
24
  }
21
25
 
@@ -0,0 +1,34 @@
1
+ import type { AuthSession } from '@sqrzro/server/auth';
2
+ import type { ProxyRedirect } from '@sqrzro/server/proxy';
3
+ import type { NextRequest } from 'next/server';
4
+
5
+ import type { AuthConfigObject } from './interfaces';
6
+
7
+ async function handleAuthProxy(
8
+ session: AuthSession | null,
9
+ request: NextRequest,
10
+ config?: AuthConfigObject
11
+ ): Promise<ProxyRedirect | null> {
12
+ const pathname = request.nextUrl.pathname;
13
+
14
+ if (session) {
15
+ if (pathname.startsWith('/auth')) {
16
+ return { redirect: '/' };
17
+ }
18
+ return null;
19
+ }
20
+
21
+ if (pathname.startsWith('/auth') || config?.allow?.includes(pathname)) {
22
+ return null;
23
+ }
24
+
25
+ return { redirect: '/auth/login' };
26
+ }
27
+
28
+ function getAuthProxy(
29
+ config?: AuthConfigObject
30
+ ): (session: AuthSession | null, request: NextRequest) => Promise<ProxyRedirect | null> {
31
+ return (session, request) => handleAuthProxy(session, request, config);
32
+ }
33
+
34
+ export default getAuthProxy;
package/src/index.ts CHANGED
@@ -1,4 +1,8 @@
1
+ export type { AuthClassNames, AuthConfigObject } from './interfaces';
2
+
3
+ export type { AuthProps } from './components/Auth';
1
4
  export { default as Auth } from './components/Auth';
5
+
2
6
  export { default as LogoutButton } from './components/LogoutButton';
3
7
 
4
- export { default as handleProxy } from './handle-proxy';
8
+ export { default as getAuthProxy } from './get-auth-proxy';
package/src/interfaces.ts CHANGED
@@ -1,3 +1,7 @@
1
+ export interface AuthConfigObject {
2
+ allow?: string[];
3
+ }
4
+
1
5
  export interface AuthClassNames {
2
6
  actions: string;
3
7
  footer: string;
@@ -0,0 +1,16 @@
1
+ import { createMail } from '@sqrzro/server/mail';
2
+
3
+ interface PasswordMailProps {
4
+ readonly token: string;
5
+ }
6
+
7
+ function PasswordMail({ token }: PasswordMailProps): React.ReactElement {
8
+ return (
9
+ <div>
10
+ PasswordMail
11
+ <a href={`http://localhost:8000/auth/password?token=${token}`}>Reset Password</a>
12
+ </div>
13
+ );
14
+ }
15
+
16
+ export default createMail('PASSWORD', PasswordMail);
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+
3
+ import createComplexitySchema from '../utility/create-complexity-schema';
4
+ import type { PasswordComplexityObject } from '../utility/interfaces';
5
+
6
+ function getComplexityRule(complexity: PasswordComplexityObject) {
7
+ const schema = createComplexitySchema(complexity);
8
+
9
+ return z.string().refine((value) => schema.safeParse(value).success, {
10
+ message: 'Password does not meet complexity requirements',
11
+ });
12
+ }
13
+
14
+ export default getComplexityRule;
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+
3
+ import { PasswordComplexityKey } from './interfaces';
4
+ import type { PasswordComplexityObject } from './interfaces';
5
+
6
+ function createComplexitySchema(complexity: PasswordComplexityObject): z.ZodString {
7
+ let result = z.string();
8
+
9
+ if (complexity.LENGTH) {
10
+ result = result.min(complexity.LENGTH, PasswordComplexityKey.LENGTH);
11
+ }
12
+
13
+ if (complexity.UPPERCASE) {
14
+ result = result.regex(
15
+ new RegExp(`(?:.*[A-Z]){${complexity.UPPERCASE}}`),
16
+ PasswordComplexityKey.UPPERCASE
17
+ );
18
+ }
19
+
20
+ if (complexity.LOWERCASE) {
21
+ result = result.regex(
22
+ new RegExp(`(?:.*[a-z]){${complexity.LOWERCASE}}`),
23
+ PasswordComplexityKey.LOWERCASE
24
+ );
25
+ }
26
+
27
+ if (complexity.NUMBER) {
28
+ result = result.regex(
29
+ new RegExp(`(?:.*\\d){${complexity.NUMBER}}`),
30
+ PasswordComplexityKey.NUMBER
31
+ );
32
+ }
33
+
34
+ if (complexity.SPECIAL) {
35
+ result = result.regex(
36
+ new RegExp(`(?:.*[@$!%*?&]){${complexity.SPECIAL}}`),
37
+ PasswordComplexityKey.SPECIAL
38
+ );
39
+ }
40
+
41
+ return result;
42
+ }
43
+
44
+ export default createComplexitySchema;
@@ -0,0 +1,14 @@
1
+ import type { PasswordComplexityObject } from './interfaces';
2
+
3
+ const DEFAULT_COMPLEXITY: PasswordComplexityObject = {
4
+ LENGTH: 8,
5
+ LOWERCASE: 1,
6
+ UPPERCASE: 1,
7
+ NUMBER: 1,
8
+ };
9
+
10
+ function getComplexity(complexity?: PasswordComplexityObject): PasswordComplexityObject {
11
+ return complexity ?? DEFAULT_COMPLEXITY;
12
+ }
13
+
14
+ export default getComplexity;
@@ -0,0 +1,11 @@
1
+ export enum PasswordComplexityKey {
2
+ LENGTH = 'LENGTH',
3
+ UPPERCASE = 'UPPERCASE',
4
+ LOWERCASE = 'LOWERCASE',
5
+ NUMBER = 'NUMBER',
6
+ SPECIAL = 'SPECIAL',
7
+ }
8
+
9
+ export type PasswordComplexityObject = Partial<Record<PasswordComplexityKey, number>>;
10
+
11
+ export type PasswordComplexityResult = { status: boolean; value: string }[];
@@ -0,0 +1,14 @@
1
+ import { formatPlural } from '@sqrzro/utility';
2
+
3
+ import { PasswordComplexityKey } from './interfaces';
4
+
5
+ export const complexities: Record<PasswordComplexityKey, (value?: number) => string> = {
6
+ [PasswordComplexityKey.LENGTH]: (value) => `At least ${formatPlural('character', value)} long`,
7
+ [PasswordComplexityKey.UPPERCASE]: (value) =>
8
+ `Contain at least ${formatPlural('uppercase letter', value)}`,
9
+ [PasswordComplexityKey.LOWERCASE]: (value) =>
10
+ `Contain at least ${formatPlural('lowercase letter', value)}`,
11
+ [PasswordComplexityKey.NUMBER]: (value) => `Contain at least ${formatPlural('number', value)}`,
12
+ [PasswordComplexityKey.SPECIAL]: (value) =>
13
+ `Contain at least ${formatPlural('special character', value)}`,
14
+ };
@@ -0,0 +1,53 @@
1
+ import { getEntries, getKeys } from '@sqrzro/utility';
2
+ import { z } from 'zod';
3
+
4
+ import createComplexitySchema from './create-complexity-schema';
5
+ import { complexities } from './lang';
6
+
7
+ import { PasswordComplexityKey } from './interfaces';
8
+ import type { PasswordComplexityObject, PasswordComplexityResult } from './interfaces';
9
+
10
+ function getDefaultComplexityResult(
11
+ complexity: PasswordComplexityObject
12
+ ): PasswordComplexityResult {
13
+ return getEntries(complexity).map(([key, value]) => ({
14
+ status: false,
15
+ value: complexities[key](value),
16
+ }));
17
+ }
18
+
19
+ function transformResult(
20
+ complexity: PasswordComplexityObject,
21
+ errors: PasswordComplexityKey[]
22
+ ): PasswordComplexityResult {
23
+ // If there are errors that don't match the complexity keys (for example, the initial state), return the default result
24
+
25
+ if (errors.find((error) => !getKeys(complexity).includes(error))) {
26
+ return getDefaultComplexityResult(complexity);
27
+ }
28
+
29
+ return getEntries(complexity).map(([key, value]) => ({
30
+ status: !errors.includes(key),
31
+ value: complexities[key](value),
32
+ }));
33
+ }
34
+
35
+ function validateComplexity(
36
+ complexity: PasswordComplexityObject,
37
+ password?: string
38
+ ): PasswordComplexityResult {
39
+ try {
40
+ createComplexitySchema(complexity).parse(password);
41
+ return transformResult(complexity, []);
42
+ } catch (error) {
43
+ if (error instanceof z.ZodError) {
44
+ return transformResult(
45
+ complexity,
46
+ error.issues.map((issue) => issue.message as PasswordComplexityKey)
47
+ );
48
+ }
49
+ return getDefaultComplexityResult(complexity);
50
+ }
51
+ }
52
+
53
+ export default validateComplexity;
@@ -1,23 +0,0 @@
1
- import { validateSession } from '@sqrzro/server/auth';
2
- import { NextResponse } from 'next/server';
3
- import type { NextRequest } from 'next/server';
4
-
5
- async function handleProxy(request: NextRequest): Promise<NextResponse> {
6
- const pathname = request.nextUrl.pathname;
7
- const validated = await validateSession(request.cookies);
8
-
9
- if (validated) {
10
- if (pathname.startsWith('/auth')) {
11
- return NextResponse.redirect(new URL('/', request.url));
12
- }
13
- return NextResponse.next();
14
- }
15
-
16
- if (pathname.startsWith('/auth')) {
17
- return NextResponse.next();
18
- }
19
-
20
- return NextResponse.redirect(new URL('/auth/login', request.url));
21
- }
22
-
23
- export default handleProxy;