@main12/auth-login 0.1.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 (59) hide show
  1. package/README.md +218 -0
  2. package/dist/auth/application/hooks/useForgotPasswordFlow.d.ts +10 -0
  3. package/dist/auth/application/hooks/useForgotPasswordFlow.js +45 -0
  4. package/dist/auth/application/hooks/useLoginFlow.d.ts +30 -0
  5. package/dist/auth/application/hooks/useLoginFlow.js +105 -0
  6. package/dist/auth/application/hooks/useSetPasswordFlow.d.ts +18 -0
  7. package/dist/auth/application/hooks/useSetPasswordFlow.js +59 -0
  8. package/dist/auth/application/hooks/useVerifyOtpFlow.d.ts +18 -0
  9. package/dist/auth/application/hooks/useVerifyOtpFlow.js +84 -0
  10. package/dist/auth/application/services/authService.d.ts +26 -0
  11. package/dist/auth/application/services/authService.js +90 -0
  12. package/dist/auth/domain/otp.d.ts +25 -0
  13. package/dist/auth/domain/otp.js +41 -0
  14. package/dist/auth/domain/passwordRules.d.ts +12 -0
  15. package/dist/auth/domain/passwordRules.js +34 -0
  16. package/dist/auth/domain/types.d.ts +35 -0
  17. package/dist/auth/domain/types.js +2 -0
  18. package/dist/components/AuthLayout.d.ts +20 -0
  19. package/dist/components/AuthLayout.js +49 -0
  20. package/dist/components/PoweredBy.d.ts +10 -0
  21. package/dist/components/PoweredBy.js +50 -0
  22. package/dist/components/email/baseTemplate.d.ts +13 -0
  23. package/dist/components/email/baseTemplate.js +69 -0
  24. package/dist/components/email/constants.d.ts +26 -0
  25. package/dist/components/email/constants.js +30 -0
  26. package/dist/components/email/index.d.ts +7 -0
  27. package/dist/components/email/index.js +7 -0
  28. package/dist/components/email/templates/otp.d.ts +16 -0
  29. package/dist/components/email/templates/otp.js +38 -0
  30. package/dist/components/email/templates/passwordChanged.d.ts +15 -0
  31. package/dist/components/email/templates/passwordChanged.js +33 -0
  32. package/dist/components/email/templates/passwordReset.d.ts +15 -0
  33. package/dist/components/email/templates/passwordReset.js +36 -0
  34. package/dist/components/email/templates/welcome.d.ts +16 -0
  35. package/dist/components/email/templates/welcome.js +38 -0
  36. package/dist/components/email/translations.d.ts +45 -0
  37. package/dist/components/email/translations.js +88 -0
  38. package/dist/components/pages/ForgotPasswordPage.d.ts +5 -0
  39. package/dist/components/pages/ForgotPasswordPage.js +45 -0
  40. package/dist/components/pages/LoginPage.d.ts +11 -0
  41. package/dist/components/pages/LoginPage.js +222 -0
  42. package/dist/components/pages/SetPasswordPage.d.ts +5 -0
  43. package/dist/components/pages/SetPasswordPage.js +74 -0
  44. package/dist/components/pages/SignupPage.d.ts +10 -0
  45. package/dist/components/pages/SignupPage.js +129 -0
  46. package/dist/components/pages/VerifyOtpPage.d.ts +5 -0
  47. package/dist/components/pages/VerifyOtpPage.js +87 -0
  48. package/dist/components/ui/index.d.ts +57 -0
  49. package/dist/components/ui/index.js +121 -0
  50. package/dist/css.d.js +0 -0
  51. package/dist/endpoints/authEndpoints.d.ts +22 -0
  52. package/dist/endpoints/authEndpoints.js +422 -0
  53. package/dist/exports/client.d.ts +24 -0
  54. package/dist/exports/client.js +22 -0
  55. package/dist/exports/rsc.d.ts +6 -0
  56. package/dist/exports/rsc.js +5 -0
  57. package/dist/index.d.ts +12 -0
  58. package/dist/index.js +16 -0
  59. package/package.json +115 -0
package/README.md ADDED
@@ -0,0 +1,218 @@
1
+ # Payload Plugin Template
2
+
3
+ A template repo to create a [Payload CMS](https://payloadcms.com) plugin.
4
+
5
+ Payload is built with a robust infrastructure intended to support Plugins with ease. This provides a simple, modular, and reusable way for developers to extend the core capabilities of Payload.
6
+
7
+ To build your own Payload plugin, all you need is:
8
+
9
+ - An understanding of the basic Payload concepts
10
+ - And some JavaScript/Typescript experience
11
+
12
+ ## Background
13
+
14
+ Here is a short recap on how to integrate plugins with Payload, to learn more visit the [plugin overview page](https://payloadcms.com/docs/plugins/overview).
15
+
16
+ ### How to install a plugin
17
+
18
+ To install any plugin, simply add it to your payload.config() in the Plugin array.
19
+
20
+ ```ts
21
+ import myPlugin from 'my-plugin'
22
+
23
+ export const config = buildConfig({
24
+ plugins: [
25
+ // You can pass options to the plugin
26
+ myPlugin({
27
+ enabled: true,
28
+ }),
29
+ ],
30
+ })
31
+ ```
32
+
33
+ ### Initialization
34
+
35
+ The initialization process goes in the following order:
36
+
37
+ 1. Incoming config is validated
38
+ 2. **Plugins execute**
39
+ 3. Default options are integrated
40
+ 4. Sanitization cleans and validates data
41
+ 5. Final config gets initialized
42
+
43
+ ## Building the Plugin
44
+
45
+ When you build a plugin, you are purely building a feature for your project and then abstracting it outside of the project.
46
+
47
+ ### Template Files
48
+
49
+ In the Payload [plugin template](https://github.com/payloadcms/payload/tree/main/templates/plugin), you will see a common file structure that is used across all plugins:
50
+
51
+ 1. root folder
52
+ 2. /src folder
53
+ 3. /dev folder
54
+
55
+ #### Root
56
+
57
+ In the root folder, you will see various files that relate to the configuration of the plugin. We set up our environment in a similar manner in Payload core and across other projects, so hopefully these will look familiar:
58
+
59
+ - **README**.md\* - This contains instructions on how to use the template. When you are ready, update this to contain instructions on how to use your Plugin.
60
+ - **package**.json\* - Contains necessary scripts and dependencies. Overwrite the metadata in this file to describe your Plugin.
61
+ - .**eslint**.config.js - Eslint configuration for reporting on problematic patterns.
62
+ - .**gitignore** - List specific untracked files to omit from Git.
63
+ - .**prettierrc**.json - Configuration for Prettier code formatting.
64
+ - **tsconfig**.json - Configures the compiler options for TypeScript
65
+ - .**swcrc** - Configuration for SWC, a fast compiler that transpiles and bundles TypeScript.
66
+ - **vitest**.config.js - Config file for Vitest, defining how tests are run and how modules are resolved
67
+
68
+ **IMPORTANT\***: You will need to modify these files.
69
+
70
+ #### Dev
71
+
72
+ In the dev folder, you’ll find a basic payload project, created with `npx create-payload-app` and the blank template.
73
+
74
+ **IMPORTANT**: Make a copy of the `.env.example` file and rename it to `.env`. Update the `DATABASE_URL` to match the database you are using and your plugin name. Update `PAYLOAD_SECRET` to a unique string.
75
+ **You will not be able to run `pnpm/yarn dev` until you have created this `.env` file.**
76
+
77
+ `myPlugin` has already been added to the `payload.config()` file in this project.
78
+
79
+ ```ts
80
+ plugins: [
81
+ myPlugin({
82
+ collections: {
83
+ posts: true,
84
+ },
85
+ }),
86
+ ]
87
+ ```
88
+
89
+ Later when you rename the plugin or add additional options, **make sure to update it here**.
90
+
91
+ You may wish to add collections or expand the test project depending on the purpose of your plugin. Just make sure to keep this dev environment as simplified as possible - users should be able to install your plugin without additional configuration required.
92
+
93
+ When you’re ready to start development, initiate the project with `pnpm/npm/yarn dev` and pull up [http://localhost:3000](http://localhost:3000) in your browser.
94
+
95
+ #### Src
96
+
97
+ Now that we have our environment setup and we have a dev project ready to - it’s time to build the plugin!
98
+
99
+ **index.ts**
100
+
101
+ The essence of a Payload plugin is simply to extend the payload config - and that is exactly what we are doing in this file.
102
+
103
+ ```ts
104
+ export const myPlugin =
105
+ (pluginOptions: MyPluginConfig) =>
106
+ (config: Config): Config => {
107
+ // do cool stuff with the config here
108
+
109
+ return config
110
+ }
111
+ ```
112
+
113
+ First, we receive the existing payload config along with any plugin options.
114
+
115
+ From here, you can extend the config as you wish.
116
+
117
+ Finally, you return the config and that is it!
118
+
119
+ ##### Spread Syntax
120
+
121
+ Spread syntax (or the spread operator) is a feature in JavaScript that uses the dot notation **(...)** to spread elements from arrays, strings, or objects into various contexts.
122
+
123
+ We are going to use spread syntax to allow us to add data to existing arrays without losing the existing data. It is crucial to spread the existing data correctly – else this can cause adverse behavior and conflicts with Payload config and other plugins.
124
+
125
+ Let’s say you want to build a plugin that adds a new collection:
126
+
127
+ ```ts
128
+ config.collections = [
129
+ ...(config.collections || []),
130
+ // Add additional collections here
131
+ ]
132
+ ```
133
+
134
+ First we spread the `config.collections` to ensure that we don’t lose the existing collections, then you can add any additional collections just as you would in a regular payload config.
135
+
136
+ This same logic is applied to other properties like admin, hooks, globals:
137
+
138
+ ```ts
139
+ config.globals = [
140
+ ...(config.globals || []),
141
+ // Add additional globals here
142
+ ]
143
+
144
+ config.hooks = {
145
+ ...(incomingConfig.hooks || {}),
146
+ // Add additional hooks here
147
+ }
148
+ ```
149
+
150
+ Some properties will be slightly different to extend, for instance the onInit property:
151
+
152
+ ```ts
153
+ import { onInitExtension } from './onInitExtension' // example file
154
+
155
+ config.onInit = async (payload) => {
156
+ if (incomingConfig.onInit) await incomingConfig.onInit(payload)
157
+ // Add additional onInit code by defining an onInitExtension function
158
+ onInitExtension(pluginOptions, payload)
159
+ }
160
+ ```
161
+
162
+ If you wish to add to the onInit, you must include the **async/await**. We don’t use spread syntax in this case, instead you must await the existing `onInit` before running additional functionality.
163
+
164
+ In the template, we have stubbed out some addition `onInit` actions that seeds in a document to the `plugin-collection`, you can use this as a base point to add more actions - and if not needed, feel free to delete it.
165
+
166
+ ##### Types.ts
167
+
168
+ If your plugin has options, you should define and provide types for these options.
169
+
170
+ ```ts
171
+ export type MyPluginConfig = {
172
+ /**
173
+ * List of collections to add a custom field
174
+ */
175
+ collections?: Partial<Record<CollectionSlug, true>>
176
+ /**
177
+ * Disable the plugin
178
+ */
179
+ disabled?: boolean
180
+ }
181
+ ```
182
+
183
+ If possible, include JSDoc comments to describe the options and their types. This allows a developer to see details about the options in their editor.
184
+
185
+ ##### Testing
186
+
187
+ Having a test suite for your plugin is essential to ensure quality and stability. **Vitest** is a fast, modern testing framework that works seamlessly with Vite and supports TypeScript out of the box.
188
+
189
+ Vitest organizes tests into test suites and cases, similar to other testing frameworks. We recommend creating individual tests based on the expected behavior of your plugin from start to finish.
190
+
191
+ Writing tests with Vitest is very straightforward, and you can learn more about how it works in the [Vitest documentation.](https://vitest.dev/)
192
+
193
+ For this template, we stubbed out `int.spec.ts` in the `dev` folder where you can write your tests.
194
+
195
+ ```ts
196
+ describe('Plugin tests', () => {
197
+ // Create tests to ensure expected behavior from the plugin
198
+ it('some condition that must be met', () => {
199
+ // Write your test logic here
200
+ expect(...)
201
+ })
202
+ })
203
+ ```
204
+
205
+ ## Best practices
206
+
207
+ With this tutorial and the plugin template, you should have everything you need to start building your own plugin.
208
+ In addition to the setup, here are other best practices aim we follow:
209
+
210
+ - **Providing an enable / disable option:** For a better user experience, provide a way to disable the plugin without uninstalling it. This is especially important if your plugin adds additional webpack aliases, this will allow you to still let the webpack run to prevent errors.
211
+ - **Include tests in your GitHub CI workflow**: If you’ve configured tests for your package, integrate them into your workflow to run the tests each time you commit to the plugin repository. Learn more about [how to configure tests into your GitHub CI workflow.](https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs)
212
+ - **Publish your finished plugin to NPM**: The best way to share and allow others to use your plugin once it is complete is to publish an NPM package. This process is straightforward and well documented, find out more [creating and publishing a NPM package here.](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/).
213
+ - **Add payload-plugin topic tag**: Apply the tag **payload-plugin **to your GitHub repository. This will boost the visibility of your plugin and ensure it gets listed with [existing payload plugins](https://github.com/topics/payload-plugin).
214
+ - **Use [Semantic Versioning](https://semver.org/) (SemVar)** - With the SemVar system you release version numbers that reflect the nature of changes (major, minor, patch). Ensure all major versions reference their Payload compatibility.
215
+
216
+ # Questions
217
+
218
+ Please contact [Payload](mailto:dev@payloadcms.com) with any questions about using this plugin template.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Forgot password flow: enter email → check exists → send OTP → redirect to verify-otp.
3
+ */
4
+ export declare function useForgotPasswordFlow(): {
5
+ email: string;
6
+ error: string | null;
7
+ isLoading: boolean;
8
+ setEmail: import("react").Dispatch<import("react").SetStateAction<string>>;
9
+ handleSubmit: (e: React.FormEvent) => Promise<void>;
10
+ };
@@ -0,0 +1,45 @@
1
+ 'use client';
2
+ import { useState, useCallback } from 'react';
3
+ import { useRouter } from 'next/navigation';
4
+ import { sendOtp, checkEmail } from '../services/authService.js';
5
+ /**
6
+ * Forgot password flow: enter email → check exists → send OTP → redirect to verify-otp.
7
+ */ export function useForgotPasswordFlow() {
8
+ const router = useRouter();
9
+ const [email, setEmail] = useState('');
10
+ const [isLoading, setIsLoading] = useState(false);
11
+ const [error, setError] = useState(null);
12
+ const handleSubmit = useCallback(async (e)=>{
13
+ e.preventDefault();
14
+ if (!email.trim()) return;
15
+ setIsLoading(true);
16
+ setError(null);
17
+ try {
18
+ const check = await checkEmail(email);
19
+ if (!check.exists) {
20
+ setError('noAccountFound');
21
+ return;
22
+ }
23
+ const data = await sendOtp(email, 'password-reset');
24
+ if (data.success) {
25
+ router.push(`/verify-otp?email=${encodeURIComponent(email.trim())}&purpose=password-reset`);
26
+ } else {
27
+ setError(data.message || 'error');
28
+ }
29
+ } catch {
30
+ setError('error');
31
+ } finally{
32
+ setIsLoading(false);
33
+ }
34
+ }, [
35
+ email,
36
+ router
37
+ ]);
38
+ return {
39
+ email,
40
+ error,
41
+ isLoading,
42
+ setEmail,
43
+ handleSubmit
44
+ };
45
+ }
@@ -0,0 +1,30 @@
1
+ import type { LoginStep } from '../../domain/types.js';
2
+ export interface UseLoginFlowOptions {
3
+ redirectTo: string;
4
+ /** Called after successful password login with { email, password } */
5
+ onPasswordLogin: (credentials: {
6
+ email: string;
7
+ password: string;
8
+ }) => Promise<void>;
9
+ }
10
+ /**
11
+ * State machine for the multi-step login flow: email → password | otp-prompt.
12
+ * The page component owns the UI; this hook owns the logic.
13
+ */
14
+ export declare function useLoginFlow({ redirectTo, onPasswordLogin }: UseLoginFlowOptions): {
15
+ step: LoginStep;
16
+ email: string;
17
+ password: string;
18
+ error: string | null;
19
+ isLoading: boolean;
20
+ isSendingOtp: boolean;
21
+ showPassword: boolean;
22
+ setEmail: import("react").Dispatch<import("react").SetStateAction<string>>;
23
+ setPassword: import("react").Dispatch<import("react").SetStateAction<string>>;
24
+ setShowPassword: import("react").Dispatch<import("react").SetStateAction<boolean>>;
25
+ handleEmailSubmit: (e: React.FormEvent) => Promise<void>;
26
+ handlePasswordSubmit: (e: React.FormEvent) => Promise<void>;
27
+ handleSendOtp: () => Promise<void>;
28
+ handleEditEmail: () => void;
29
+ handleGoogleLogin: () => void;
30
+ };
@@ -0,0 +1,105 @@
1
+ 'use client';
2
+ import { useState, useCallback } from 'react';
3
+ import { useRouter } from 'next/navigation';
4
+ import { checkEmail, sendOtp, initiateGoogleLogin } from '../services/authService.js';
5
+ /**
6
+ * State machine for the multi-step login flow: email → password | otp-prompt.
7
+ * The page component owns the UI; this hook owns the logic.
8
+ */ export function useLoginFlow({ redirectTo, onPasswordLogin }) {
9
+ const router = useRouter();
10
+ const [step, setStep] = useState('email');
11
+ const [email, setEmail] = useState('');
12
+ const [password, setPassword] = useState('');
13
+ const [isLoading, setIsLoading] = useState(false);
14
+ const [error, setError] = useState(null);
15
+ const [showPassword, setShowPassword] = useState(false);
16
+ const [isSendingOtp, setIsSendingOtp] = useState(false);
17
+ const handleEmailSubmit = useCallback(async (e)=>{
18
+ e.preventDefault();
19
+ if (!email.trim()) return;
20
+ setIsLoading(true);
21
+ setError(null);
22
+ try {
23
+ const data = await checkEmail(email);
24
+ if (!data.exists) {
25
+ setError('noAccountFound');
26
+ return;
27
+ }
28
+ setStep(data.hasPassword ? 'password' : 'otp-prompt');
29
+ } catch {
30
+ setError('genericError');
31
+ } finally{
32
+ setIsLoading(false);
33
+ }
34
+ }, [
35
+ email
36
+ ]);
37
+ const handlePasswordSubmit = useCallback(async (e)=>{
38
+ e.preventDefault();
39
+ setIsLoading(true);
40
+ setError(null);
41
+ try {
42
+ await onPasswordLogin({
43
+ email,
44
+ password
45
+ });
46
+ window.location.href = redirectTo;
47
+ } catch {
48
+ setError('error');
49
+ } finally{
50
+ setIsLoading(false);
51
+ }
52
+ }, [
53
+ email,
54
+ password,
55
+ onPasswordLogin,
56
+ redirectTo
57
+ ]);
58
+ const handleSendOtp = useCallback(async ()=>{
59
+ setIsSendingOtp(true);
60
+ setError(null);
61
+ try {
62
+ const data = await sendOtp(email, 'login');
63
+ if (data.success) {
64
+ const redirectParam = redirectTo !== '/' ? `&redirect=${encodeURIComponent(redirectTo)}` : '';
65
+ router.push(`/verify-otp?email=${encodeURIComponent(email.trim())}${redirectParam}`);
66
+ } else {
67
+ setError(data.message || 'otpSendFailed');
68
+ }
69
+ } catch {
70
+ setError('otpSendFailed');
71
+ } finally{
72
+ setIsSendingOtp(false);
73
+ }
74
+ }, [
75
+ email,
76
+ redirectTo,
77
+ router
78
+ ]);
79
+ const handleEditEmail = useCallback(()=>{
80
+ setStep('email');
81
+ setError(null);
82
+ }, []);
83
+ const handleGoogleLogin = useCallback(()=>{
84
+ initiateGoogleLogin(redirectTo);
85
+ }, [
86
+ redirectTo
87
+ ]);
88
+ return {
89
+ step,
90
+ email,
91
+ password,
92
+ error,
93
+ isLoading,
94
+ isSendingOtp,
95
+ showPassword,
96
+ setEmail,
97
+ setPassword,
98
+ setShowPassword,
99
+ handleEmailSubmit,
100
+ handlePasswordSubmit,
101
+ handleSendOtp,
102
+ handleEditEmail,
103
+ handleGoogleLogin
104
+ };
105
+ }
@@ -0,0 +1,18 @@
1
+ export interface UseSetPasswordFlowOptions {
2
+ redirectTo?: string;
3
+ }
4
+ /**
5
+ * Set password flow: enter new password + confirm → validate → submit.
6
+ */
7
+ export declare function useSetPasswordFlow({ redirectTo }?: UseSetPasswordFlowOptions): {
8
+ password: string;
9
+ confirmPassword: string;
10
+ error: string | null;
11
+ isLoading: boolean;
12
+ showPassword: boolean;
13
+ strength: import("../../domain/types.js").PasswordStrengthResult;
14
+ setPassword: import("react").Dispatch<import("react").SetStateAction<string>>;
15
+ setConfirmPassword: import("react").Dispatch<import("react").SetStateAction<string>>;
16
+ setShowPassword: import("react").Dispatch<import("react").SetStateAction<boolean>>;
17
+ handleSubmit: (e: React.FormEvent) => Promise<void>;
18
+ };
@@ -0,0 +1,59 @@
1
+ 'use client';
2
+ import { useState, useCallback } from 'react';
3
+ import { useRouter } from 'next/navigation';
4
+ import { setUserPassword } from '../services/authService.js';
5
+ import { evaluatePasswordStrength } from '../../domain/passwordRules.js';
6
+ /**
7
+ * Set password flow: enter new password + confirm → validate → submit.
8
+ */ export function useSetPasswordFlow({ redirectTo = '/' } = {}) {
9
+ const router = useRouter();
10
+ const [password, setPassword] = useState('');
11
+ const [confirmPassword, setConfirmPassword] = useState('');
12
+ const [isLoading, setIsLoading] = useState(false);
13
+ const [error, setError] = useState(null);
14
+ const [showPassword, setShowPassword] = useState(false);
15
+ const strength = evaluatePasswordStrength(password);
16
+ const handleSubmit = useCallback(async (e)=>{
17
+ e.preventDefault();
18
+ setError(null);
19
+ if (password !== confirmPassword) {
20
+ setError('passwordMismatch');
21
+ return;
22
+ }
23
+ if (!strength.isValid) {
24
+ setError('passwordTooWeak');
25
+ return;
26
+ }
27
+ setIsLoading(true);
28
+ try {
29
+ const data = await setUserPassword(password, confirmPassword);
30
+ if (data.success) {
31
+ window.location.href = redirectTo;
32
+ } else {
33
+ setError(data.message || 'error');
34
+ }
35
+ } catch {
36
+ setError('error');
37
+ } finally{
38
+ setIsLoading(false);
39
+ }
40
+ }, [
41
+ password,
42
+ confirmPassword,
43
+ strength.isValid,
44
+ redirectTo,
45
+ router
46
+ ]);
47
+ return {
48
+ password,
49
+ confirmPassword,
50
+ error,
51
+ isLoading,
52
+ showPassword,
53
+ strength,
54
+ setPassword,
55
+ setConfirmPassword,
56
+ setShowPassword,
57
+ handleSubmit
58
+ };
59
+ }
@@ -0,0 +1,18 @@
1
+ export interface UseVerifyOtpFlowOptions {
2
+ email: string;
3
+ purpose: 'login' | 'signup' | 'password-reset';
4
+ redirectTo?: string;
5
+ }
6
+ /**
7
+ * State machine for OTP verification: input → verify → redirect | resend.
8
+ */
9
+ export declare function useVerifyOtpFlow({ email, purpose, redirectTo }: UseVerifyOtpFlowOptions): {
10
+ otp: string;
11
+ error: string | null;
12
+ isLoading: boolean;
13
+ isResending: boolean;
14
+ resendCooldown: number;
15
+ setOtp: import("react").Dispatch<import("react").SetStateAction<string>>;
16
+ handleSubmit: () => Promise<void>;
17
+ handleResendCode: () => Promise<void>;
18
+ };
@@ -0,0 +1,84 @@
1
+ 'use client';
2
+ import { useState, useCallback, useEffect } from 'react';
3
+ import { useRouter } from 'next/navigation';
4
+ import { verifyOtp, sendOtp } from '../services/authService.js';
5
+ /**
6
+ * State machine for OTP verification: input → verify → redirect | resend.
7
+ */ export function useVerifyOtpFlow({ email, purpose, redirectTo = '/' }) {
8
+ const router = useRouter();
9
+ const [otp, setOtp] = useState('');
10
+ const [isLoading, setIsLoading] = useState(false);
11
+ const [error, setError] = useState(null);
12
+ const [isResending, setIsResending] = useState(false);
13
+ const [resendCooldown, setResendCooldown] = useState(0);
14
+ useEffect(()=>{
15
+ if (resendCooldown > 0) {
16
+ const timer = setTimeout(()=>setResendCooldown((c)=>c - 1), 1000);
17
+ return ()=>clearTimeout(timer);
18
+ }
19
+ }, [
20
+ resendCooldown
21
+ ]);
22
+ const handleSubmit = useCallback(async ()=>{
23
+ if (otp.length !== 6) return;
24
+ setIsLoading(true);
25
+ setError(null);
26
+ try {
27
+ const data = await verifyOtp(email, otp);
28
+ if (data.success) {
29
+ if (purpose === 'password-reset') {
30
+ router.push(`/set-password?redirect=${encodeURIComponent(redirectTo)}`);
31
+ } else if (data.isNewUser) {
32
+ router.push(`/set-password?redirect=${encodeURIComponent(redirectTo)}`);
33
+ } else {
34
+ window.location.href = redirectTo;
35
+ }
36
+ } else {
37
+ setError(data.error || 'error');
38
+ setOtp('');
39
+ }
40
+ } catch {
41
+ setError('error');
42
+ setOtp('');
43
+ } finally{
44
+ setIsLoading(false);
45
+ }
46
+ }, [
47
+ otp,
48
+ email,
49
+ purpose,
50
+ redirectTo,
51
+ router
52
+ ]);
53
+ const handleResendCode = useCallback(async ()=>{
54
+ if (resendCooldown > 0) return;
55
+ setIsResending(true);
56
+ setError(null);
57
+ try {
58
+ const data = await sendOtp(email, purpose);
59
+ if (data.success) {
60
+ setResendCooldown(60);
61
+ } else {
62
+ setError(data.message || 'resendError');
63
+ }
64
+ } catch {
65
+ setError('resendError');
66
+ } finally{
67
+ setIsResending(false);
68
+ }
69
+ }, [
70
+ email,
71
+ purpose,
72
+ resendCooldown
73
+ ]);
74
+ return {
75
+ otp,
76
+ error,
77
+ isLoading,
78
+ isResending,
79
+ resendCooldown,
80
+ setOtp,
81
+ handleSubmit,
82
+ handleResendCode
83
+ };
84
+ }
@@ -0,0 +1,26 @@
1
+ import type { CheckEmailResponse, SendOtpResponse, VerifyOtpResponse, SetPasswordResponse, SignupResponse } from '../../domain/types.js';
2
+ /**
3
+ * Check if a user exists and whether they have a password set.
4
+ * Used in the two-step login flow.
5
+ */
6
+ export declare function checkEmail(email: string): Promise<CheckEmailResponse>;
7
+ /**
8
+ * Send an OTP verification code to the user's email.
9
+ */
10
+ export declare function sendOtp(email: string, purpose?: 'login' | 'signup' | 'password-reset'): Promise<SendOtpResponse>;
11
+ /**
12
+ * Verify an OTP code and receive an auth token.
13
+ */
14
+ export declare function verifyOtp(email: string, otp: string): Promise<VerifyOtpResponse>;
15
+ /**
16
+ * Set a new user password (requires valid auth session).
17
+ */
18
+ export declare function setUserPassword(password: string, confirmPassword: string): Promise<SetPasswordResponse>;
19
+ /**
20
+ * Create a new user account.
21
+ */
22
+ export declare function signup(name: string, email: string): Promise<SignupResponse>;
23
+ /**
24
+ * Redirect the browser to the Google OAuth login endpoint.
25
+ */
26
+ export declare function initiateGoogleLogin(redirectTo?: string): void;