@proteinjs/user-ui 1.4.2 → 1.5.0

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 (73) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/generated/index.d.ts +0 -9
  3. package/dist/generated/index.d.ts.map +1 -1
  4. package/dist/generated/index.js +0 -9
  5. package/dist/generated/index.js.map +1 -1
  6. package/dist/src/auth/AuthApi.d.ts +12 -0
  7. package/dist/src/auth/AuthApi.d.ts.map +1 -0
  8. package/dist/src/auth/AuthApi.js +151 -0
  9. package/dist/src/auth/AuthApi.js.map +1 -0
  10. package/dist/src/auth/AuthButton.d.ts +13 -0
  11. package/dist/src/auth/AuthButton.d.ts.map +1 -0
  12. package/dist/src/auth/AuthButton.js +21 -0
  13. package/dist/src/auth/AuthButton.js.map +1 -0
  14. package/dist/src/auth/AuthFormError.d.ts +6 -0
  15. package/dist/src/auth/AuthFormError.d.ts.map +1 -0
  16. package/dist/src/auth/AuthFormError.js +18 -0
  17. package/dist/src/auth/AuthFormError.js.map +1 -0
  18. package/dist/src/auth/AuthLayout.d.ts +17 -0
  19. package/dist/src/auth/AuthLayout.d.ts.map +1 -0
  20. package/dist/src/auth/AuthLayout.js +52 -0
  21. package/dist/src/auth/AuthLayout.js.map +1 -0
  22. package/dist/src/auth/AuthMessagePanel.d.ts +13 -0
  23. package/dist/src/auth/AuthMessagePanel.d.ts.map +1 -0
  24. package/dist/src/auth/AuthMessagePanel.js +22 -0
  25. package/dist/src/auth/AuthMessagePanel.js.map +1 -0
  26. package/dist/src/auth/AuthTextField.d.ts +21 -0
  27. package/dist/src/auth/AuthTextField.d.ts.map +1 -0
  28. package/dist/src/auth/AuthTextField.js +60 -0
  29. package/dist/src/auth/AuthTextField.js.map +1 -0
  30. package/dist/src/auth/AuthValidation.d.ts +18 -0
  31. package/dist/src/auth/AuthValidation.d.ts.map +1 -0
  32. package/dist/src/auth/AuthValidation.js +38 -0
  33. package/dist/src/auth/AuthValidation.js.map +1 -0
  34. package/dist/src/pages/ForgotPassword.d.ts.map +1 -1
  35. package/dist/src/pages/ForgotPassword.js +77 -75
  36. package/dist/src/pages/ForgotPassword.js.map +1 -1
  37. package/dist/src/pages/Login.d.ts.map +1 -1
  38. package/dist/src/pages/Login.js +79 -97
  39. package/dist/src/pages/Login.js.map +1 -1
  40. package/dist/src/pages/PasswordReset.d.ts.map +1 -1
  41. package/dist/src/pages/PasswordReset.js +86 -134
  42. package/dist/src/pages/PasswordReset.js.map +1 -1
  43. package/dist/src/pages/Signup.d.ts.map +1 -1
  44. package/dist/src/pages/Signup.js +88 -148
  45. package/dist/src/pages/Signup.js.map +1 -1
  46. package/dist/test/authApi.test.d.ts +2 -0
  47. package/dist/test/authApi.test.d.ts.map +1 -0
  48. package/dist/test/authApi.test.js +188 -0
  49. package/dist/test/authApi.test.js.map +1 -0
  50. package/dist/test/authPages.test.d.ts +2 -0
  51. package/dist/test/authPages.test.d.ts.map +1 -0
  52. package/dist/test/authPages.test.js +52 -0
  53. package/dist/test/authPages.test.js.map +1 -0
  54. package/dist/test/authValidation.test.d.ts +2 -0
  55. package/dist/test/authValidation.test.d.ts.map +1 -0
  56. package/dist/test/authValidation.test.js +52 -0
  57. package/dist/test/authValidation.test.js.map +1 -0
  58. package/generated/index.ts +0 -9
  59. package/package.json +3 -3
  60. package/src/auth/AuthApi.ts +67 -0
  61. package/src/auth/AuthButton.tsx +38 -0
  62. package/src/auth/AuthFormError.tsx +15 -0
  63. package/src/auth/AuthLayout.tsx +69 -0
  64. package/src/auth/AuthMessagePanel.tsx +28 -0
  65. package/src/auth/AuthTextField.tsx +75 -0
  66. package/src/auth/AuthValidation.ts +39 -0
  67. package/src/pages/ForgotPassword.tsx +77 -56
  68. package/src/pages/Login.tsx +74 -78
  69. package/src/pages/PasswordReset.tsx +118 -124
  70. package/src/pages/Signup.tsx +117 -136
  71. package/test/authApi.test.ts +92 -0
  72. package/test/authPages.test.tsx +51 -0
  73. package/test/authValidation.test.ts +56 -0
@@ -1,129 +1,144 @@
1
1
  import React, { useEffect, useState } from 'react';
2
- import { Page, Form, Fields, textField, FormButtons, FormPage } from '@proteinjs/ui';
3
- import { routes, uiRoutes } from '@proteinjs/user';
4
- import { Button, Stack, Typography } from '@mui/material';
2
+ import { Box, CircularProgress, Typography } from '@mui/material';
3
+ import { Page } from '@proteinjs/ui';
4
+ import { uiRoutes } from '@proteinjs/user';
5
+ import { Helmet } from 'react-helmet';
6
+ import { AuthLayout } from '../auth/AuthLayout';
7
+ import { AuthTextField } from '../auth/AuthTextField';
8
+ import { AuthButton } from '../auth/AuthButton';
9
+ import { AuthFormError } from '../auth/AuthFormError';
10
+ import { AuthMessagePanel } from '../auth/AuthMessagePanel';
11
+ import { AuthApi } from '../auth/AuthApi';
12
+ import { AuthValidation } from '../auth/AuthValidation';
13
+
14
+ function resetTokenFromUrl(): string {
15
+ if (typeof window === 'undefined') {
16
+ return '';
17
+ }
5
18
 
6
- const PasswordResetComponent: React.FC = () => {
7
- const [token, setToken] = useState('');
8
- const [isValidating, setIsValidating] = useState(false);
9
- const [validationError, setValidationError] = useState<string | null>(null);
10
- const [resetSuccess, setResetSuccess] = useState(false);
19
+ return new URLSearchParams(window.location.search).get('token') || '';
20
+ }
11
21
 
12
- const buttons: FormButtons<ResetPasswordFields> = {
13
- submit: {
14
- name: 'Reset Password',
15
- style: {
16
- color: 'primary',
17
- variant: 'contained',
18
- },
19
- onClick: async (fields: ResetPasswordFields) => {
20
- if (fields.newPassword.field.value !== fields.confirmPassword.field.value) {
21
- throw new Error('Passwords do not match');
22
- }
22
+ const PasswordResetComponent: React.FC = () => {
23
+ // The token is read synchronously so the first paint is already the right state
24
+ // (validating vs invalid) — never a flash of the form for a dead link.
25
+ const [token] = useState(resetTokenFromUrl);
26
+ const [validating, setValidating] = useState(!!token);
27
+ const [invalid, setInvalid] = useState(!token);
28
+ const [newPassword, setNewPassword] = useState('');
29
+ const [confirmPassword, setConfirmPassword] = useState('');
30
+ const [error, setError] = useState<string | undefined>();
31
+ const [busy, setBusy] = useState(false);
32
+ const [resetComplete, setResetComplete] = useState(false);
23
33
 
24
- const response = await fetch(routes.executePasswordReset.path, {
25
- method: routes.executePasswordReset.method,
26
- body: JSON.stringify({
27
- token: fields.token.field.value,
28
- newPassword: fields.newPassword.field.value,
29
- }),
30
- credentials: 'same-origin',
31
- headers: {
32
- 'Content-Type': 'application/json',
33
- },
34
- });
34
+ useEffect(() => {
35
+ if (!token) {
36
+ return;
37
+ }
35
38
 
36
- if (response.status !== 200) {
37
- throw new Error('Failed to reset password');
39
+ let active = true;
40
+ new AuthApi()
41
+ .validateResetToken(token)
42
+ .then((errorMessage) => {
43
+ if (active && errorMessage) {
44
+ setInvalid(true);
38
45
  }
39
-
40
- setResetSuccess(true);
41
- return 'Your password has been successfully reset. You can now log in with your new password.';
42
- },
43
- },
44
- };
45
-
46
- useEffect(() => {
47
- const searchParams = new URLSearchParams(window.location.search);
48
- const resetToken = searchParams.get('token');
49
- if (resetToken) {
50
- setToken(resetToken);
51
- validateToken(resetToken);
52
- } else {
53
- setValidationError('No reset token provided');
46
+ })
47
+ .catch(() => {
48
+ if (active) {
49
+ setInvalid(true);
50
+ }
51
+ })
52
+ .finally(() => {
53
+ if (active) {
54
+ setValidating(false);
55
+ }
56
+ });
57
+ return () => {
58
+ active = false;
59
+ };
60
+ }, [token]);
61
+
62
+ const onSubmit = async (event: React.FormEvent) => {
63
+ event.preventDefault();
64
+ const validationError = AuthValidation.passwordReset({ newPassword, confirmPassword });
65
+ if (validationError) {
66
+ setError(validationError);
67
+ return;
54
68
  }
55
- }, []);
56
69
 
57
- const validateToken = async (token: string) => {
58
- setIsValidating(true);
70
+ setError(undefined);
71
+ setBusy(true);
59
72
  try {
60
- const response = await fetch(`${routes.validateResetToken.path}?token=${token}`, {
61
- method: routes.validateResetToken.method,
62
- credentials: 'same-origin',
63
- });
64
- const data = await response.json();
65
- if (!data.isValid) {
66
- setValidationError(data.message || 'Invalid or expired token');
67
- }
68
- } catch (error) {
69
- setValidationError('An error occurred while validating the token');
70
- } finally {
71
- setIsValidating(false);
73
+ await new AuthApi().executePasswordReset(token, newPassword);
74
+ setResetComplete(true);
75
+ } catch (error: any) {
76
+ setError(error.message);
77
+ setBusy(false);
72
78
  }
73
79
  };
74
80
 
75
- if (isValidating) {
76
- return <FormPage>Validating reset token...</FormPage>;
81
+ if (validating) {
82
+ return (
83
+ <AuthLayout title='Reset your password'>
84
+ <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, color: 'text.secondary' }}>
85
+ <CircularProgress size={18} sx={{ color: 'inherit' }} />
86
+ <Typography sx={{ fontSize: '0.875rem', color: 'inherit' }}>Checking your reset link…</Typography>
87
+ </Box>
88
+ </AuthLayout>
89
+ );
77
90
  }
78
91
 
79
- if (validationError) {
92
+ if (invalid) {
80
93
  return (
81
- <FormPage>
82
- <Stack alignItems='center' spacing={3}>
83
- <Typography variant='h1' gutterBottom>
84
- Invalid password reset link
85
- </Typography>
86
- <Typography variant='body1' gutterBottom>
87
- The password reset link is invalid or has expired. Please request a new password reset.
88
- </Typography>
89
- <Button variant='contained' color='primary' href={`/${uiRoutes.auth.login}`}>
90
- Go to login page
91
- </Button>
92
- </Stack>
93
- </FormPage>
94
+ <AuthMessagePanel
95
+ title='This reset link is invalid'
96
+ body='The link is invalid or has expired. Request a new one from the log in page.'
97
+ actionName='Go to log in'
98
+ actionHref={`/${uiRoutes.auth.login}`}
99
+ />
94
100
  );
95
101
  }
96
102
 
97
- if (resetSuccess) {
103
+ if (resetComplete) {
98
104
  return (
99
- <FormPage>
100
- <Stack alignItems='center' spacing={3}>
101
- <Typography variant='h6' gutterBottom>
102
- Password reset successful
103
- </Typography>
104
- <Typography variant='body1' gutterBottom>
105
- Your password has been successfully reset. You can now log in with your new password.
106
- </Typography>
107
- <Button variant='contained' color='primary' href={`/${uiRoutes.auth.login}`}>
108
- Go to login page
109
- </Button>
110
- </Stack>
111
- </FormPage>
105
+ <AuthMessagePanel
106
+ title='Password reset'
107
+ body='You can now log in with your new password.'
108
+ actionName='Go to log in'
109
+ actionHref={`/${uiRoutes.auth.login}`}
110
+ />
112
111
  );
113
112
  }
114
113
 
115
114
  return (
116
- <FormPage>
117
- <Form<ResetPasswordFields, typeof buttons>
118
- name='Reset Password'
119
- createFields={() => new ResetPasswordFields()}
120
- fieldLayout={['newPassword', 'confirmPassword']}
121
- buttons={buttons}
122
- onLoad={async (fields) => {
123
- fields.token.field.value = token;
124
- }}
125
- />
126
- </FormPage>
115
+ <>
116
+ <Helmet>
117
+ <title>Reset your password</title>
118
+ </Helmet>
119
+ <AuthLayout title='Choose a new password'>
120
+ <form onSubmit={onSubmit} noValidate>
121
+ <AuthTextField
122
+ label='New password'
123
+ value={newPassword}
124
+ onChange={setNewPassword}
125
+ password
126
+ autoComplete='new-password'
127
+ disabled={busy}
128
+ />
129
+ <AuthTextField
130
+ label='Confirm new password'
131
+ value={confirmPassword}
132
+ onChange={setConfirmPassword}
133
+ password
134
+ autoComplete='new-password'
135
+ disabled={busy}
136
+ />
137
+ <AuthFormError message={error} />
138
+ <AuthButton busy={busy}>Reset password</AuthButton>
139
+ </form>
140
+ </AuthLayout>
141
+ </>
127
142
  );
128
143
  };
129
144
 
@@ -135,24 +150,3 @@ export const passwordResetPage: Page = {
135
150
  },
136
151
  component: PasswordResetComponent,
137
152
  };
138
-
139
- class ResetPasswordFields extends Fields {
140
- static create() {
141
- return new ResetPasswordFields();
142
- }
143
-
144
- token = textField<ResetPasswordFields>({
145
- name: 'token',
146
- accessibility: { hidden: true },
147
- });
148
-
149
- newPassword = textField<ResetPasswordFields>({
150
- name: 'New Password',
151
- isPassword: true,
152
- });
153
-
154
- confirmPassword = textField<ResetPasswordFields>({
155
- name: 'Confirm New Password',
156
- isPassword: true,
157
- });
158
- }
@@ -1,134 +1,144 @@
1
1
  import React, { useEffect, useState } from 'react';
2
- import { Page, Form, Fields, textField, FormButtons, clearButton, FormPage } from '@proteinjs/ui';
2
+ import { Skeleton, Stack } from '@mui/material';
3
+ import { Page } from '@proteinjs/ui';
3
4
  import { getSignupService, uiRoutes } from '@proteinjs/user';
4
- import { Button, Skeleton, Stack, Typography } from '@mui/material';
5
- import { emailRegex } from '@proteinjs/util';
6
5
  import { Helmet } from 'react-helmet';
7
6
  import { useNavigate } from 'react-router-dom';
7
+ import { AuthLayout } from '../auth/AuthLayout';
8
+ import { AuthTextField } from '../auth/AuthTextField';
9
+ import { AuthButton } from '../auth/AuthButton';
10
+ import { AuthFormError } from '../auth/AuthFormError';
11
+ import { AuthMessagePanel } from '../auth/AuthMessagePanel';
12
+ import { AuthValidation } from '../auth/AuthValidation';
13
+
14
+ function inviteTokenFromUrl(): string {
15
+ if (typeof window === 'undefined') {
16
+ return '';
17
+ }
18
+
19
+ return new URLSearchParams(window.location.search).get('token') || '';
20
+ }
8
21
 
9
22
  const SignupComponent: React.FC = () => {
10
23
  const navigate = useNavigate();
11
- const [token, setToken] = useState('');
12
- const [isInviteOnly, setIsInviteOnly] = useState<boolean>(false);
13
- const [isInitializing, setIsInitializing] = useState(false);
24
+ const [token] = useState(inviteTokenFromUrl);
25
+ const [initializing, setInitializing] = useState(true);
14
26
  const [initializationError, setInitializationError] = useState<string | null>(null);
27
+ const [name, setName] = useState('');
28
+ const [email, setEmail] = useState('');
29
+ const [password, setPassword] = useState('');
30
+ const [confirmPassword, setConfirmPassword] = useState('');
31
+ const [error, setError] = useState<string | undefined>();
32
+ const [busy, setBusy] = useState(false);
15
33
 
16
- const buttons: FormButtons<SignupFields> = {
17
- clear: clearButton,
18
- signup: {
19
- name: 'Sign up',
20
- style: {
21
- color: 'primary',
22
- variant: 'contained',
23
- },
24
- onClick: async (fields: SignupFields, buttons: FormButtons<SignupFields>) => {
25
- if (!fields.name.field.value) {
26
- return 'Please enter your name.';
34
+ useEffect(() => {
35
+ let active = true;
36
+ getSignupService()
37
+ .initializeSignup(token || undefined)
38
+ .then((response) => {
39
+ if (active && !response.isReady && response.error) {
40
+ setInitializationError(response.error);
27
41
  }
28
-
29
- const email = fields.email.field.value && fields.email.field.value.trim();
30
-
31
- // invited users don't enter an email
32
- if (!token && (!email || !emailRegex.test(email))) {
33
- return 'Please enter a valid email address.';
42
+ })
43
+ .catch(() => {
44
+ if (active) {
45
+ setInitializationError('An error occurred while initializing sign up.');
34
46
  }
35
-
36
- if (!fields.password.field.value) {
37
- return 'Please enter a password.';
47
+ })
48
+ .finally(() => {
49
+ if (active) {
50
+ setInitializing(false);
38
51
  }
39
-
40
- try {
41
- await getSignupService().createUser(
42
- {
43
- name: fields.name.field.value,
44
- email,
45
- password: fields.password.field.value,
46
- },
47
- token
48
- );
49
- } catch {
50
- return 'Sign up failed.';
51
- }
52
-
53
- navigate(uiRoutes.auth.login.startsWith('/') ? uiRoutes.auth.login : '/' + uiRoutes.auth.login);
54
- },
55
- },
56
- };
57
-
58
- useEffect(() => {
59
- const searchParams = new URLSearchParams(window.location.search);
60
- const inviteToken = searchParams.get('token');
61
- if (inviteToken) {
62
- setToken(inviteToken);
63
- initializeSignup(inviteToken);
64
- } else {
65
- initializeSignup();
52
+ });
53
+ return () => {
54
+ active = false;
55
+ };
56
+ }, [token]);
57
+
58
+ const onSubmit = async (event: React.FormEvent) => {
59
+ event.preventDefault();
60
+ const validationError = AuthValidation.signup({ name, email, password, confirmPassword }, !!token);
61
+ if (validationError) {
62
+ setError(validationError);
63
+ return;
66
64
  }
67
- }, []);
68
65
 
69
- const initializeSignup = async (token?: string) => {
70
- setIsInitializing(true);
66
+ setError(undefined);
67
+ setBusy(true);
71
68
  try {
72
- const response = await getSignupService().initializeSignup(token);
73
-
74
- if (response.isInviteOnly !== undefined) {
75
- setIsInviteOnly(response.isInviteOnly);
76
- }
77
-
78
- if (!response.isReady && response.error) {
79
- setInitializationError(response.error);
80
- }
81
- } catch (error) {
82
- setInitializationError('An error occurred while initializing sign up.');
83
- } finally {
84
- setIsInitializing(false);
69
+ // invited users don't enter an email (the invite token carries it)
70
+ await getSignupService().createUser({ name, email: token ? undefined : email.trim(), password }, token);
71
+ } catch {
72
+ setError('Sign up failed.');
73
+ setBusy(false);
74
+ return;
85
75
  }
76
+
77
+ navigate(uiRoutes.auth.login.startsWith('/') ? uiRoutes.auth.login : '/' + uiRoutes.auth.login);
86
78
  };
87
79
 
80
+ if (initializing) {
81
+ return (
82
+ <AuthLayout title='Create your account'>
83
+ <Stack spacing={2.5}>
84
+ <Skeleton variant='rounded' height={48} sx={{ borderRadius: '12px' }} />
85
+ <Skeleton variant='rounded' height={48} sx={{ borderRadius: '12px' }} />
86
+ <Skeleton variant='rounded' height={48} sx={{ borderRadius: '12px' }} />
87
+ <Skeleton variant='rounded' height={48} sx={{ borderRadius: '999px' }} />
88
+ </Stack>
89
+ </AuthLayout>
90
+ );
91
+ }
92
+
93
+ if (initializationError) {
94
+ return (
95
+ <AuthMessagePanel
96
+ title='Sign up is not available'
97
+ body={initializationError}
98
+ actionName='Go to log in'
99
+ actionHref={`/${uiRoutes.auth.login}`}
100
+ />
101
+ );
102
+ }
103
+
88
104
  return (
89
105
  <>
90
106
  <Helmet>
91
107
  <title>Sign up</title>
92
108
  </Helmet>
93
- <FormPage>
94
- {isInitializing ? (
95
- <Stack direction='column' spacing={2} sx={{ px: 2, py: 1 }}>
96
- <Skeleton variant='text' width='500px' height='60px' />
97
- <Skeleton variant='text' width='500px' height='60px' />
98
- <Skeleton variant='text' width='500px' height='60px' />
99
- <Skeleton variant='text' width='500px' height='60px' />
100
- <Stack direction='row' spacing={2} justifyContent='flex-end'>
101
- <Skeleton variant='text' width='100px' height='60px' />
102
- <Skeleton variant='text' width='100px' height='60px' />
103
- </Stack>
104
- </Stack>
105
- ) : initializationError ? (
106
- <Stack alignItems='center' spacing={3} sx={{ p: 4 }}>
107
- <Typography variant='h1' gutterBottom>
108
- Sign up is not available
109
- </Typography>
110
- <Typography variant='body1' gutterBottom>
111
- {initializationError}
112
- </Typography>
113
- <Button variant='contained' color='primary' href={`/${uiRoutes.auth.login}`}>
114
- Go to login page
115
- </Button>
116
- </Stack>
117
- ) : (
118
- <Form<SignupFields, typeof buttons>
119
- name='Sign Up'
120
- createFields={() => new SignupFields()}
121
- fieldLayout={['name', 'email', 'password', 'confirmPassword']}
122
- buttons={buttons}
123
- onLoad={async (fields) => {
124
- fields.token.field.value = token;
125
- if (token) {
126
- fields.email.field.accessibility = { hidden: true };
127
- }
128
- }}
109
+ <AuthLayout title='Create your account'>
110
+ <form onSubmit={onSubmit} noValidate>
111
+ <AuthTextField label='Name' value={name} onChange={setName} autoComplete='name' disabled={busy} />
112
+ {!token && (
113
+ <AuthTextField
114
+ label='Email'
115
+ value={email}
116
+ onChange={setEmail}
117
+ type='email'
118
+ autoComplete='email'
119
+ disabled={busy}
120
+ />
121
+ )}
122
+ <AuthTextField
123
+ label='Password'
124
+ value={password}
125
+ onChange={setPassword}
126
+ password
127
+ autoComplete='new-password'
128
+ disabled={busy}
129
+ />
130
+ <AuthTextField
131
+ label='Confirm password'
132
+ value={confirmPassword}
133
+ onChange={setConfirmPassword}
134
+ password
135
+ autoComplete='new-password'
136
+ disabled={busy}
129
137
  />
130
- )}
131
- </FormPage>
138
+ <AuthFormError message={error} />
139
+ <AuthButton busy={busy}>Sign up</AuthButton>
140
+ </form>
141
+ </AuthLayout>
132
142
  </>
133
143
  );
134
144
  };
@@ -141,32 +151,3 @@ export const signupPage: Page = {
141
151
  },
142
152
  component: SignupComponent,
143
153
  };
144
-
145
- class SignupFields extends Fields {
146
- static create() {
147
- return new SignupFields();
148
- }
149
-
150
- token = textField<SignupFields>({
151
- name: 'token',
152
- accessibility: { hidden: true },
153
- });
154
-
155
- name = textField<SignupFields>({
156
- name: 'name',
157
- });
158
-
159
- email = textField<SignupFields>({
160
- name: 'email',
161
- });
162
-
163
- password = textField<SignupFields>({
164
- name: 'password',
165
- isPassword: true,
166
- });
167
-
168
- confirmPassword = textField<SignupFields>({
169
- name: 'confirmPassword',
170
- isPassword: true,
171
- });
172
- }
@@ -0,0 +1,92 @@
1
+ import { AuthApi } from '../src/auth/AuthApi';
2
+ import { routes } from '@proteinjs/user';
3
+
4
+ function mockFetch(response: { status?: number; statusText?: string; body?: any }) {
5
+ const fetchMock = jest.fn().mockResolvedValue({
6
+ status: response.status ?? 200,
7
+ statusText: response.statusText ?? 'OK',
8
+ json: async () => response.body ?? {},
9
+ });
10
+ (global as any).fetch = fetchMock;
11
+ return fetchMock;
12
+ }
13
+
14
+ afterEach(() => {
15
+ delete (global as any).fetch;
16
+ });
17
+
18
+ describe('AuthApi.login', () => {
19
+ it('posts the credentials to the login route and resolves on success', async () => {
20
+ const fetchMock = mockFetch({ body: {} });
21
+ await new AuthApi().login('ada@example.com', 'hunter22');
22
+ expect(fetchMock).toHaveBeenCalledWith(
23
+ routes.login.path,
24
+ expect.objectContaining({
25
+ method: routes.login.method,
26
+ body: JSON.stringify({ email: 'ada@example.com', password: 'hunter22' }),
27
+ })
28
+ );
29
+ });
30
+
31
+ it('throws on a non-200 response', async () => {
32
+ mockFetch({ status: 401, statusText: 'Unauthorized' });
33
+ await expect(new AuthApi().login('ada@example.com', 'nope')).rejects.toThrow('Unauthorized');
34
+ });
35
+
36
+ it('throws the server-provided error from a 200 response body', async () => {
37
+ mockFetch({ body: { error: 'Incorrect email or password' } });
38
+ await expect(new AuthApi().login('ada@example.com', 'nope')).rejects.toThrow('Incorrect email or password');
39
+ });
40
+ });
41
+
42
+ describe('AuthApi.initiatePasswordReset', () => {
43
+ it('posts the email and resolves on success', async () => {
44
+ const fetchMock = mockFetch({ body: {} });
45
+ await new AuthApi().initiatePasswordReset('ada@example.com');
46
+ expect(fetchMock).toHaveBeenCalledWith(
47
+ routes.initiatePasswordReset.path,
48
+ expect.objectContaining({
49
+ method: routes.initiatePasswordReset.method,
50
+ body: JSON.stringify({ email: 'ada@example.com' }),
51
+ })
52
+ );
53
+ });
54
+
55
+ it('throws a user-readable error on failure', async () => {
56
+ mockFetch({ status: 500, statusText: 'Internal Server Error' });
57
+ await expect(new AuthApi().initiatePasswordReset('ada@example.com')).rejects.toThrow(
58
+ 'Failed to send the reset email. Please try again.'
59
+ );
60
+ });
61
+ });
62
+
63
+ describe('AuthApi.validateResetToken', () => {
64
+ it('returns undefined for a valid token', async () => {
65
+ mockFetch({ body: { isValid: true } });
66
+ await expect(new AuthApi().validateResetToken('tok')).resolves.toBeUndefined();
67
+ });
68
+
69
+ it('returns the server message for an invalid token', async () => {
70
+ mockFetch({ body: { isValid: false, message: 'Token expired' } });
71
+ await expect(new AuthApi().validateResetToken('tok')).resolves.toBe('Token expired');
72
+ });
73
+ });
74
+
75
+ describe('AuthApi.executePasswordReset', () => {
76
+ it('posts the token and new password', async () => {
77
+ const fetchMock = mockFetch({ body: {} });
78
+ await new AuthApi().executePasswordReset('tok', 'hunter22');
79
+ expect(fetchMock).toHaveBeenCalledWith(
80
+ routes.executePasswordReset.path,
81
+ expect.objectContaining({
82
+ method: routes.executePasswordReset.method,
83
+ body: JSON.stringify({ token: 'tok', newPassword: 'hunter22' }),
84
+ })
85
+ );
86
+ });
87
+
88
+ it('throws on a non-200 response', async () => {
89
+ mockFetch({ status: 400 });
90
+ await expect(new AuthApi().executePasswordReset('tok', 'hunter22')).rejects.toThrow('Failed to reset password');
91
+ });
92
+ });