@humanonlyweb/create-nuxtflare 0.2.1 → 0.2.3

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.
@@ -1,5 +1,8 @@
1
+ import type { Ref } from 'vue'
2
+
1
3
  import { isLocalPath } from '#shared/utils/paths'
2
- import { problemOf } from '~/utils/api-error'
4
+ import { ForgotPasswordFormSchema, LoginFormSchema, RegisterFormSchema, ResetPasswordFormSchema, TotpCodeFormSchema } from '#shared/utils/schema-validation'
5
+ import { fieldErrors, problemOf } from '~/utils/api-error'
3
6
 
4
7
  export type LoginStep = { readonly kind: 'credentials' } | { readonly kind: 'totp'; readonly challenge?: string }
5
8
  export type ForgotStep = { readonly kind: 'form' } | { readonly kind: 'sent' }
@@ -8,8 +11,6 @@ export type ResetStep =
8
11
  | { readonly kind: 'invalid'; readonly message: string }
9
12
  | { readonly kind: 'form'; readonly token: string }
10
13
  | { readonly kind: 'done' }
11
- export type VerifyStep = { readonly kind: 'verifying' } | { readonly kind: 'verified' } | { readonly kind: 'error'; readonly message: string }
12
- export type EmailChangeStep = { readonly kind: 'confirming' } | { readonly kind: 'confirmed' } | { readonly kind: 'error'; readonly message: string }
13
14
 
14
15
  const OAUTH_ERRORS: Readonly<Record<string, string>> = {
15
16
  google: 'Google sign-in failed. Please try again.',
@@ -21,19 +22,23 @@ const OAUTH_ERRORS: Readonly<Record<string, string>> = {
21
22
  }
22
23
 
23
24
  const turnstileHeaders = (token: string) => (token ? { 'x-turnstile-token': token } : undefined)
24
-
25
25
  const routeToken = (params: Record<string, unknown>): string => ('token' in params && typeof params.token === 'string' ? params.token : '')
26
+ const mapFields = fieldErrors()
27
+
28
+ type FormElementRef = Readonly<Ref<HTMLElement | null>>
26
29
 
27
- export const useAuthLogin = () => {
30
+ export const useAuthLogin = (
31
+ options: {
32
+ readonly credentialsFormRef?: FormElementRef
33
+ readonly totpFormRef?: FormElementRef
34
+ readonly onResetCaptcha?: () => void
35
+ } = {},
36
+ ) => {
28
37
  const route = useRoute()
29
38
  const { fetch: refreshSession } = useUserSession()
30
39
 
31
40
  const step = ref<LoginStep>(route.query.totp === '1' ? { kind: 'totp' } : { kind: 'credentials' })
32
- const identity = ref('')
33
- const password = ref('')
34
- const code = ref('')
35
41
  const turnstileToken = ref('')
36
- const busy = ref(false)
37
42
  const initialError = typeof route.query.error === 'string' ? (OAUTH_ERRORS[route.query.error] ?? '') : ''
38
43
  const errorMessage = ref(initialError)
39
44
 
@@ -49,134 +54,129 @@ export const useAuthLogin = () => {
49
54
  document.cookie = `app_next=${encodeURIComponent(next)}; Path=/auth; Max-Age=600; SameSite=Lax${secure}`
50
55
  }
51
56
 
52
- const submitCredentials = async (onResetCaptcha?: () => void) => {
53
- errorMessage.value = ''
54
- busy.value = true
55
- try {
57
+ const credentials = useForm({
58
+ schema: LoginFormSchema,
59
+ initialValues: { identity: '', password: '' },
60
+ formRef: options.credentialsFormRef,
61
+ mapError: mapFields,
62
+ onSubmit: async (values) => {
63
+ errorMessage.value = ''
56
64
  const result = await $fetch('/api/auth/login', {
57
65
  method: 'POST',
58
- body: { identity: identity.value, password: password.value },
66
+ body: values,
59
67
  headers: turnstileHeaders(turnstileToken.value),
60
68
  })
61
69
  if (result.status === 'totp_required') {
62
- password.value = ''
70
+ credentials.form.password = ''
63
71
  step.value = { kind: 'totp', challenge: result.challenge }
64
72
  return
65
73
  }
66
74
  await refreshSession()
67
75
  await navigateTo(destination())
68
- } catch (error) {
69
- errorMessage.value = problemOf(error).message
70
- onResetCaptcha?.()
71
- } finally {
72
- busy.value = false
73
- }
74
- }
76
+ },
77
+ onError: (error) => {
78
+ if (!mapFields(error)) errorMessage.value = problemOf(error).message
79
+ options.onResetCaptcha?.()
80
+ },
81
+ })
75
82
 
76
- const submitTotp = async () => {
77
- if (step.value.kind !== 'totp') return
78
- errorMessage.value = ''
79
- busy.value = true
80
- try {
83
+ const totp = useForm({
84
+ schema: TotpCodeFormSchema,
85
+ initialValues: { code: '' },
86
+ formRef: options.totpFormRef,
87
+ mapError: mapFields,
88
+ onSubmit: async (values) => {
89
+ if (step.value.kind !== 'totp') return
90
+ errorMessage.value = ''
81
91
  await $fetch('/api/auth/login/totp', {
82
92
  method: 'POST',
83
- body: step.value.challenge ? { challenge: step.value.challenge, code: code.value } : { code: code.value },
93
+ body: step.value.challenge ? { challenge: step.value.challenge, code: values.code } : { code: values.code },
84
94
  })
85
95
  await refreshSession()
86
96
  await navigateTo(destination())
87
- } catch (error) {
88
- errorMessage.value = problemOf(error).message
89
- } finally {
90
- busy.value = false
91
- }
92
- }
97
+ },
98
+ onError: (error) => {
99
+ if (!mapFields(error)) errorMessage.value = problemOf(error).message
100
+ },
101
+ })
93
102
 
94
103
  const backToCredentials = () => {
95
- code.value = ''
104
+ totp.reset()
96
105
  errorMessage.value = ''
97
106
  step.value = { kind: 'credentials' }
98
107
  }
99
108
 
100
109
  return {
101
110
  step,
102
- identity,
103
- password,
104
- code,
111
+ credentials,
112
+ totp,
105
113
  turnstileToken,
106
- busy,
107
114
  errorMessage,
108
115
  rememberOAuthNext,
109
- submitCredentials,
110
- submitTotp,
111
116
  backToCredentials,
112
117
  }
113
118
  }
114
119
 
115
- export const useAuthRegister = () => {
120
+ export const useAuthRegister = (options: { readonly formRef?: FormElementRef; readonly onResetCaptcha?: () => void } = {}) => {
116
121
  const { fetch: refreshSession } = useUserSession()
117
- const username = ref('')
118
- const email = ref('')
119
- const password = ref('')
120
122
  const turnstileToken = ref('')
121
- const busy = ref(false)
122
123
  const errorMessage = ref('')
123
124
 
124
- const submit = async (onResetCaptcha?: () => void) => {
125
- errorMessage.value = ''
126
- busy.value = true
127
- try {
125
+ const formState = useForm({
126
+ schema: RegisterFormSchema,
127
+ initialValues: { username: '', email: '', password: '', confirm: '' },
128
+ formRef: options.formRef,
129
+ mapError: mapFields,
130
+ onSubmit: async (values) => {
131
+ errorMessage.value = ''
128
132
  await $fetch('/api/auth/register', {
129
133
  method: 'POST',
130
- body: { username: username.value, email: email.value, password: password.value },
134
+ body: { username: values.username, email: values.email, password: values.password },
131
135
  headers: turnstileHeaders(turnstileToken.value),
132
136
  })
133
137
  await refreshSession()
134
138
  await navigateTo('/account')
135
- } catch (error) {
136
- errorMessage.value = problemOf(error).message
137
- onResetCaptcha?.()
138
- } finally {
139
- busy.value = false
140
- }
141
- }
139
+ },
140
+ onError: (error) => {
141
+ if (!mapFields(error)) errorMessage.value = problemOf(error).message
142
+ options.onResetCaptcha?.()
143
+ },
144
+ })
142
145
 
143
- return { username, email, password, turnstileToken, busy, errorMessage, submit }
146
+ return { ...formState, turnstileToken, errorMessage }
144
147
  }
145
148
 
146
- export const useForgotPassword = () => {
149
+ export const useForgotPassword = (options: { readonly formRef?: FormElementRef; readonly onResetCaptcha?: () => void } = {}) => {
147
150
  const step = ref<ForgotStep>({ kind: 'form' })
148
- const email = ref('')
149
151
  const turnstileToken = ref('')
150
- const busy = ref(false)
151
152
  const errorMessage = ref('')
152
153
 
153
- const submit = async (onResetCaptcha?: () => void) => {
154
- errorMessage.value = ''
155
- busy.value = true
156
- try {
154
+ const formState = useForm({
155
+ schema: ForgotPasswordFormSchema,
156
+ initialValues: { email: '' },
157
+ formRef: options.formRef,
158
+ mapError: mapFields,
159
+ onSubmit: async (values) => {
160
+ errorMessage.value = ''
157
161
  await $fetch('/api/auth/reset/request', {
158
162
  method: 'POST',
159
- body: { email: email.value },
163
+ body: values,
160
164
  headers: turnstileHeaders(turnstileToken.value),
161
165
  })
162
166
  step.value = { kind: 'sent' }
163
- } catch (error) {
164
- errorMessage.value = problemOf(error).message
165
- onResetCaptcha?.()
166
- } finally {
167
- busy.value = false
168
- }
169
- }
167
+ },
168
+ onError: (error) => {
169
+ if (!mapFields(error)) errorMessage.value = problemOf(error).message
170
+ options.onResetCaptcha?.()
171
+ },
172
+ })
170
173
 
171
- return { step, email, turnstileToken, busy, errorMessage, submit }
174
+ return { ...formState, step, turnstileToken, errorMessage }
172
175
  }
173
176
 
174
- export const usePasswordReset = () => {
177
+ export const usePasswordReset = (options: { readonly formRef?: FormElementRef } = {}) => {
175
178
  const route = useRoute()
176
179
  const step = ref<ResetStep>({ kind: 'checking' })
177
- const password = ref('')
178
- const confirm = ref('')
179
- const busy = ref(false)
180
180
  const errorMessage = ref('')
181
181
 
182
182
  onMounted(async () => {
@@ -193,226 +193,25 @@ export const usePasswordReset = () => {
193
193
  }
194
194
  })
195
195
 
196
- const submit = async () => {
197
- if (step.value.kind !== 'form') return
198
- errorMessage.value = ''
199
- if (password.value !== confirm.value) {
200
- errorMessage.value = 'Passwords do not match.'
201
- return
202
- }
203
- busy.value = true
204
- try {
196
+ const formState = useForm({
197
+ schema: ResetPasswordFormSchema,
198
+ initialValues: { password: '', confirm: '' },
199
+ formRef: options.formRef,
200
+ mapError: mapFields,
201
+ onSubmit: async (values) => {
202
+ if (step.value.kind !== 'form') return
203
+ errorMessage.value = ''
205
204
  await $fetch('/api/auth/reset', {
206
205
  method: 'POST',
207
- body: { token: step.value.token, password: password.value },
206
+ body: { token: step.value.token, password: values.password },
208
207
  })
209
- password.value = ''
210
- confirm.value = ''
208
+ formState.reset()
211
209
  step.value = { kind: 'done' }
212
- } catch (error) {
213
- errorMessage.value = problemOf(error).message
214
- } finally {
215
- busy.value = false
216
- }
217
- }
218
-
219
- return { step, password, confirm, busy, errorMessage, submit }
220
- }
221
-
222
- export const useEmailVerify = () => {
223
- const route = useRoute()
224
- const { loggedIn, fetch: refreshSession } = useUserSession()
225
- const step = ref<VerifyStep>({ kind: 'verifying' })
226
-
227
- onMounted(async () => {
228
- const token = routeToken(route.params)
229
- if (!token) {
230
- step.value = { kind: 'error', message: 'This verification link is invalid or has expired.' }
231
- return
232
- }
233
- try {
234
- await $fetch('/api/auth/verify', { method: 'POST', body: { token } })
235
- if (loggedIn.value) await refreshSession()
236
- step.value = { kind: 'verified' }
237
- } catch (error) {
238
- step.value = { kind: 'error', message: problemOf(error).message }
239
- }
240
- })
241
-
242
- return { step, loggedIn }
243
- }
244
-
245
- export const useEmailChangeConfirm = () => {
246
- const route = useRoute()
247
- const { clear } = useUserSession()
248
- const step = ref<EmailChangeStep>({ kind: 'confirming' })
249
-
250
- onMounted(async () => {
251
- const token = routeToken(route.params)
252
- if (!token) {
253
- step.value = { kind: 'error', message: 'This email confirmation link is invalid or has expired.' }
254
- return
255
- }
256
- try {
257
- await $fetch('/api/auth/email', { method: 'POST', body: { token } })
258
- await clear()
259
- step.value = { kind: 'confirmed' }
260
- } catch (error) {
261
- step.value = { kind: 'error', message: problemOf(error).message }
262
- }
263
- })
264
-
265
- return { step }
266
- }
267
-
268
- export const useAccount = async () => {
269
- const { data: me, refresh: refreshMe } = await useMe()
270
- const features = useFeatures()
271
- const { clear, fetch: refreshSession } = useUserSession()
272
-
273
- const canUseVerifiedActions = computed(() => Boolean(me.value && (!features.emailVerificationRequired || me.value.emailStatus === 'verified')))
274
-
275
- const { data: sessionList, refresh: refreshSessions } = await useFetch('/api/account/sessions', {
276
- immediate: canUseVerifiedActions.value,
277
- default: () => ({ sessions: [] }),
210
+ },
211
+ onError: (error) => {
212
+ if (!mapFields(error)) errorMessage.value = problemOf(error).message
213
+ },
278
214
  })
279
215
 
280
- const username = ref(me.value?.username ?? '')
281
- const nextEmail = ref('')
282
- const emailPassword = ref('')
283
- const emailCode = ref('')
284
- const currentPassword = ref('')
285
- const newPassword = ref('')
286
- const passwordCode = ref('')
287
- const deleteConfirm = ref('')
288
- const deletePassword = ref('')
289
- const deleteCode = ref('')
290
- const busy = ref(false)
291
- const notice = ref('')
292
- const errorMessage = ref('')
293
-
294
- const runAction = async (work: () => Promise<void>, successMessage?: string) => {
295
- errorMessage.value = ''
296
- notice.value = ''
297
- busy.value = true
298
- try {
299
- await work()
300
- if (successMessage) notice.value = successMessage
301
- } catch (error) {
302
- errorMessage.value = problemOf(error).message
303
- } finally {
304
- busy.value = false
305
- }
306
- }
307
-
308
- const signOut = () =>
309
- runAction(async () => {
310
- await $fetch('/api/auth/logout', { method: 'POST' })
311
- await clear()
312
- await navigateTo('/login')
313
- })
314
-
315
- const signOutEverywhere = () =>
316
- runAction(async () => {
317
- await $fetch('/api/auth/logout-everywhere', { method: 'POST' })
318
- await clear()
319
- await navigateTo('/login')
320
- })
321
-
322
- const resendVerification = () =>
323
- runAction(async () => {
324
- await $fetch('/api/auth/verify/send', { method: 'POST' })
325
- }, 'Verification email sent.')
326
-
327
- const saveProfile = () =>
328
- runAction(async () => {
329
- const updated = await $fetch('/api/account', { method: 'PATCH', body: { username: username.value } })
330
- username.value = updated.username
331
- await Promise.all([refreshMe(), refreshSession()])
332
- }, 'Username updated.')
333
-
334
- const requestEmailChange = () =>
335
- runAction(async () => {
336
- await $fetch('/api/account/email', {
337
- method: 'POST',
338
- body: {
339
- email: nextEmail.value,
340
- password: emailPassword.value,
341
- ...(emailCode.value ? { code: emailCode.value } : {}),
342
- },
343
- })
344
- nextEmail.value = ''
345
- emailPassword.value = ''
346
- emailCode.value = ''
347
- await refreshMe()
348
- }, 'Check your new email address for a confirmation link.')
349
-
350
- const cancelEmailChange = () =>
351
- runAction(async () => {
352
- await $fetch('/api/account/email', { method: 'DELETE' })
353
- await refreshMe()
354
- }, 'Pending email change cancelled.')
355
-
356
- const savePassword = () =>
357
- runAction(
358
- async () => {
359
- const hadPassword = Boolean(me.value?.hasPassword)
360
- await $fetch('/api/account/password', {
361
- method: 'POST',
362
- body: {
363
- ...(hadPassword && currentPassword.value ? { currentPassword: currentPassword.value } : {}),
364
- newPassword: newPassword.value,
365
- ...(passwordCode.value ? { code: passwordCode.value } : {}),
366
- },
367
- })
368
- currentPassword.value = ''
369
- newPassword.value = ''
370
- passwordCode.value = ''
371
- await Promise.all([refreshMe(), refreshSessions()])
372
- },
373
- me.value?.hasPassword ? 'Password updated and other sessions signed out.' : 'Password set.',
374
- )
375
-
376
- const deleteAccount = () =>
377
- runAction(async () => {
378
- await $fetch('/api/account', {
379
- method: 'DELETE',
380
- body: {
381
- confirm: deleteConfirm.value,
382
- ...(deletePassword.value ? { password: deletePassword.value } : {}),
383
- ...(deleteCode.value ? { code: deleteCode.value } : {}),
384
- },
385
- })
386
- await clear()
387
- await navigateTo('/login')
388
- })
389
-
390
- return {
391
- me,
392
- features,
393
- canUseVerifiedActions,
394
- sessionList,
395
- username,
396
- nextEmail,
397
- emailPassword,
398
- emailCode,
399
- currentPassword,
400
- newPassword,
401
- passwordCode,
402
- deleteConfirm,
403
- deletePassword,
404
- deleteCode,
405
- busy,
406
- notice,
407
- errorMessage,
408
- refreshSessions,
409
- signOut,
410
- signOutEverywhere,
411
- resendVerification,
412
- saveProfile,
413
- savePassword,
414
- requestEmailChange,
415
- cancelEmailChange,
416
- deleteAccount,
417
- }
216
+ return { ...formState, step, errorMessage }
418
217
  }
@@ -0,0 +1,52 @@
1
+ import { problemOf } from '~/utils/api-error'
2
+
3
+ export type VerifyStep = { readonly kind: 'verifying' } | { readonly kind: 'verified' } | { readonly kind: 'error'; readonly message: string }
4
+ export type EmailChangeStep = { readonly kind: 'confirming' } | { readonly kind: 'confirmed' } | { readonly kind: 'error'; readonly message: string }
5
+
6
+ const routeToken = (params: Record<string, unknown>): string => ('token' in params && typeof params.token === 'string' ? params.token : '')
7
+
8
+ export const useEmailVerify = () => {
9
+ const route = useRoute()
10
+ const { loggedIn, fetch: refreshSession } = useUserSession()
11
+ const step = ref<VerifyStep>({ kind: 'verifying' })
12
+
13
+ onMounted(async () => {
14
+ const token = routeToken(route.params)
15
+ if (!token) {
16
+ step.value = { kind: 'error', message: 'This verification link is invalid or has expired.' }
17
+ return
18
+ }
19
+ try {
20
+ await $fetch('/api/auth/verify', { method: 'POST', body: { token } })
21
+ if (loggedIn.value) await refreshSession()
22
+ step.value = { kind: 'verified' }
23
+ } catch (error) {
24
+ step.value = { kind: 'error', message: problemOf(error).message }
25
+ }
26
+ })
27
+
28
+ return { step, loggedIn }
29
+ }
30
+
31
+ export const useEmailChangeConfirm = () => {
32
+ const route = useRoute()
33
+ const { clear } = useUserSession()
34
+ const step = ref<EmailChangeStep>({ kind: 'confirming' })
35
+
36
+ onMounted(async () => {
37
+ const token = routeToken(route.params)
38
+ if (!token) {
39
+ step.value = { kind: 'error', message: 'This email confirmation link is invalid or has expired.' }
40
+ return
41
+ }
42
+ try {
43
+ await $fetch('/api/auth/email', { method: 'POST', body: { token } })
44
+ await clear()
45
+ step.value = { kind: 'confirmed' }
46
+ } catch (error) {
47
+ step.value = { kind: 'error', message: problemOf(error).message }
48
+ }
49
+ })
50
+
51
+ return { step }
52
+ }