@enlt-bakusoku/nuxt4 0.0.0-stage → 2.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 (86) hide show
  1. package/README.md +38 -2
  2. package/dist/module.d.mts +25 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +208 -0
  5. package/dist/runtime/shared/schemas/user.d.ts +40 -0
  6. package/dist/runtime/shared/schemas/user.js +21 -0
  7. package/dist/runtime/tasks-catalog.d.ts +6 -0
  8. package/dist/runtime/tasks-catalog.js +7 -0
  9. package/dist/types.d.mts +9 -0
  10. package/package.json +120 -3
  11. package/scripts/bakusoku-dev.mjs +387 -0
  12. package/scripts/dev-log-relay.mjs +96 -0
  13. package/scripts/predeploy.mjs +24 -0
  14. package/scripts/prepare-firebase-artifact.mjs +43 -0
  15. package/scripts/setup-worktree.sh +59 -0
  16. package/scripts/verify-firebase-artifacts.mjs +70 -0
  17. package/src/layer/app/components/admin/AdminExecutionHistory.vue +137 -0
  18. package/src/layer/app/components/admin/TaskRunDialog.vue +162 -0
  19. package/src/layer/app/components/admin/UserManagementPage.vue +342 -0
  20. package/src/layer/app/components/debug/DebugApplicationLogs.vue +87 -0
  21. package/src/layer/app/components/debug/DebugErrorLogs.vue +47 -0
  22. package/src/layer/app/components/debug/DebugFirestoreOperations.vue +48 -0
  23. package/src/layer/app/components/debug/DebugHttpRequests.vue +86 -0
  24. package/src/layer/app/components/debug/DebugNavigation.vue +60 -0
  25. package/src/layer/app/components/debug/DebugNowControl.vue +243 -0
  26. package/src/layer/app/components/debug/DebugPublicConfig.vue +24 -0
  27. package/src/layer/app/components/debug/DebugTestAdmin.vue +67 -0
  28. package/src/layer/app/components/demo/DemoDebug.vue +266 -0
  29. package/src/layer/app/components/demo/DemoHome.vue +347 -0
  30. package/src/layer/app/components/demo/DemoLogin.vue +391 -0
  31. package/src/layer/app/components/demo/DemoPassword.vue +224 -0
  32. package/src/layer/app/components/demo/DemoRegister.vue +148 -0
  33. package/src/layer/app/components/home/HomePage.vue +77 -0
  34. package/src/layer/app/layouts/dashboard.vue +126 -0
  35. package/src/layer/app/layouts/default.vue +3 -0
  36. package/src/layer/app/middleware/admin.ts +15 -0
  37. package/src/layer/app/middleware/authenticated.ts +19 -0
  38. package/src/layer/app/pages/admin/migrations.vue +463 -0
  39. package/src/layer/app/pages/admin/tasks/[id].vue +276 -0
  40. package/src/layer/app/pages/admin/tasks/index.vue +220 -0
  41. package/src/layer/app/pages/admin/users.vue +17 -0
  42. package/src/layer/app/pages/bakusoku-devtools.vue +294 -0
  43. package/src/layer/app/plugins/auth-init.ts +36 -0
  44. package/src/layer/app/plugins/debug-devtools.client.ts +20 -0
  45. package/src/layer/app/plugins/debug-errors.client.ts +78 -0
  46. package/src/layer/app/plugins/debug-http.client.ts +154 -0
  47. package/src/layer/app/plugins/debug-nav.client.ts +28 -0
  48. package/src/layer/app/plugins/vuefire-inspect.ts +18 -0
  49. package/src/layer/app/stores/auth.ts +462 -0
  50. package/src/layer/app/stores/datetime.ts +41 -0
  51. package/src/layer/app/stores/debug.ts +235 -0
  52. package/src/layer/app/stores/user.ts +170 -0
  53. package/src/layer/app/utils/admin-execution.ts +48 -0
  54. package/src/layer/app/utils/dashboard-heading.ts +36 -0
  55. package/src/layer/app/utils/debug-bridge.ts +270 -0
  56. package/src/layer/app/utils/debug-firestore.ts +38 -0
  57. package/src/layer/app/utils/debug-format.ts +19 -0
  58. package/src/layer/app/utils/execution-refresh.ts +66 -0
  59. package/src/layer/app/utils/framework-version.ts +4 -0
  60. package/src/layer/app/utils/inspect-nuxt-vuefire.ts +288 -0
  61. package/src/layer/app/utils/is-debug-enabled.ts +13 -0
  62. package/src/layer/app/utils/logger.ts +235 -0
  63. package/src/layer/app/utils/map-auth-error.ts +11 -0
  64. package/src/layer/app/utils/mask-secrets.ts +100 -0
  65. package/src/layer/app/utils/resolve-auth-user.ts +53 -0
  66. package/src/layer/app/utils/resolve-firestore.ts +20 -0
  67. package/src/layer/app/utils/task-run.ts +15 -0
  68. package/src/layer/build-credentials.mjs +33 -0
  69. package/src/layer/nuxt.config.ts +86 -0
  70. package/src/layer/package.json +5 -0
  71. package/src/layer/server/api/debug/test-admin.post.ts +38 -0
  72. package/src/layer/server/api/tasks/executions/cancel.post.ts +21 -0
  73. package/src/layer/server/api/tasks/executions/index.get.ts +22 -0
  74. package/src/layer/server/api/tasks/executions/index.post.ts +25 -0
  75. package/src/layer/server/api/tasks/index.get.ts +70 -0
  76. package/src/layer/server/api/tasks/migrations/index.post.ts +27 -0
  77. package/src/layer/server/api/tasks/migrations/recovery.post.ts +20 -0
  78. package/src/layer/server/api/users/[id].delete.ts +57 -0
  79. package/src/layer/server/api/users/[id].put.ts +110 -0
  80. package/src/layer/server/api/users/index.post.ts +232 -0
  81. package/src/layer/server/utils/admin-access.ts +32 -0
  82. package/src/layer/server/utils/debug-test-admin.ts +17 -0
  83. package/src/layer/server/utils/firebase-admin.ts +22 -0
  84. package/src/layer/server/utils/logger.ts +172 -0
  85. package/src/layer/server/utils/tasks-gateway.ts +57 -0
  86. package/src/layer/server/utils/user-mutations.ts +103 -0
@@ -0,0 +1,391 @@
1
+ <template>
2
+ <UPage class="login-page p-4 md:p-6 lg:p-8">
3
+ <UPageHeader
4
+ title="爆速開発v2 デモ"
5
+ description="つくる楽しさを、ここから。Bakusoku の機能を体験してみましょう。"
6
+ >
7
+ <template #links>
8
+ <UBadge color="primary" variant="subtle" size="lg">
9
+ nuxt4 {{ FRAMEWORK_VERSION }}
10
+ </UBadge>
11
+ <UButton
12
+ to="/register"
13
+ color="neutral"
14
+ variant="outline"
15
+ icon="i-lucide-user-plus"
16
+ >
17
+ ユーザー作成
18
+ </UButton>
19
+ </template>
20
+ </UPageHeader>
21
+
22
+ <UPageBody>
23
+ <div class="mx-auto flex max-w-5xl flex-col gap-8">
24
+ <div class="grid grid-cols-1 gap-8 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]">
25
+ <section class="space-y-4">
26
+ <div>
27
+ <h2 class="text-xl font-semibold">ログイン</h2>
28
+ <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
29
+ デモでは Google・パスワード・メールリンクの3系統を試せます。
30
+ </p>
31
+ </div>
32
+
33
+ <ClientOnly>
34
+ <UCard v-if="isLoading" class="text-center py-12">
35
+ <div class="flex flex-col items-center gap-4">
36
+ <UIcon name="i-heroicons-arrow-path" class="w-10 h-10 animate-spin text-primary-500" />
37
+ <p class="text-gray-600 dark:text-gray-400">読み込み中...</p>
38
+ </div>
39
+ </UCard>
40
+
41
+ <UCard v-else>
42
+ <div class="mb-6">
43
+ <UButton
44
+ block
45
+ color="neutral"
46
+ variant="outline"
47
+ :loading="isLoadingGoogle"
48
+ :disabled="isLoading || isLoadingEmailLink"
49
+ icon="i-simple-icons-google"
50
+ @click="handleLoginWithGoogle"
51
+ >
52
+ Googleでログイン
53
+ </UButton>
54
+ <UAlert
55
+ v-if="authStore.error"
56
+ color="error"
57
+ variant="soft"
58
+ :title="authStore.error"
59
+ class="mt-3"
60
+ />
61
+ </div>
62
+
63
+ <USeparator class="my-6" label="または" />
64
+
65
+ <UTabs v-model="loginMethod" :items="loginMethods" />
66
+
67
+ <div class="mt-6">
68
+ <div v-if="loginMethod === 0" />
69
+ <UAuthForm
70
+ v-else-if="loginMethod === 1"
71
+ :fields="loginFields"
72
+ :validate="validateLogin"
73
+ :loading="isLoading"
74
+ :disabled="isLoading"
75
+ title="ログイン"
76
+ description="メールアドレスとパスワードを入力してください。"
77
+ icon="i-heroicons-envelope"
78
+ :submit="{ label: 'ログイン', block: true }"
79
+ @submit="handleLogin"
80
+ >
81
+ <template #validation>
82
+ <UAlert
83
+ v-if="authStore.error"
84
+ color="error"
85
+ variant="soft"
86
+ :title="authStore.error"
87
+ />
88
+ </template>
89
+ </UAuthForm>
90
+
91
+ <UAuthForm
92
+ v-else
93
+ :fields="emailLinkFields"
94
+ :validate="validateEmailLink"
95
+ :loading="isLoadingEmailLink"
96
+ :disabled="isLoadingEmailLink"
97
+ title="メールリンクでログイン"
98
+ description="メールアドレスを入力すると、ログイン用のリンクが送信されます。"
99
+ icon="i-heroicons-envelope"
100
+ :submit="{ label: 'ログインリンクを送信', block: true }"
101
+ @submit="handleSendEmailLink"
102
+ >
103
+ <template #validation>
104
+ <UAlert
105
+ v-if="emailLinkSent"
106
+ color="success"
107
+ variant="soft"
108
+ title="メールを送信しました"
109
+ description="メールボックスを確認して、ログインリンクをクリックしてください。"
110
+ class="mb-4"
111
+ />
112
+ <UAlert
113
+ v-if="authStore.error"
114
+ color="error"
115
+ variant="soft"
116
+ :title="authStore.error"
117
+ />
118
+ </template>
119
+ </UAuthForm>
120
+ </div>
121
+ </UCard>
122
+
123
+ <p class="mt-6 text-center text-sm text-gray-500 dark:text-gray-400">
124
+ アカウントをお持ちでない方は
125
+ <NuxtLink to="/register" class="text-primary-500 hover:underline">
126
+ ユーザーを作成
127
+ </NuxtLink>
128
+ </p>
129
+ </ClientOnly>
130
+ </section>
131
+
132
+ <aside class="demo-visual">
133
+ <div class="visual-heading">
134
+ <span class="visual-eyebrow">爆速開発を体験する</span>
135
+ <h2>アイディアを、<br>その日のうちに、<br><span>動くものまで作る。</span></h2>
136
+ <p>ログインやユーザー管理。アプリの土台になる機能を、ここから試せます。</p>
137
+ </div>
138
+
139
+ <div class="build-figure" aria-hidden="true">
140
+ <div class="build-inputs">
141
+ <span><UIcon name="i-lucide-lightbulb" class="size-5" />アイディア</span>
142
+ <b>+</b>
143
+ <span><UIcon name="i-lucide-panels-top-left" class="size-5" />テンプレート</span>
144
+ </div>
145
+ <UIcon name="i-lucide-arrow-down" class="build-arrow size-7" />
146
+ <div class="app-figure">
147
+ <div class="app-title"><UIcon name="i-lucide-panels-top-left" class="size-5" />あなたのアプリ</div>
148
+ <div class="app-fields"><span /><span /></div>
149
+ <div class="app-action">ログイン</div>
150
+ </div>
151
+ <p>すぐに動く。ここから作れる。</p>
152
+ </div>
153
+
154
+ <div class="visual-features">
155
+ <div v-for="highlight in highlights" :key="highlight.title" class="visual-feature">
156
+ <UIcon :name="highlight.icon" class="size-5 shrink-0" />
157
+ <span>{{ highlight.title }}</span>
158
+ <span class="feature-label">{{ highlight.badge }}</span>
159
+ </div>
160
+ </div>
161
+ <p class="visual-footer">つくるための土台を、ひとつに。</p>
162
+ </aside>
163
+ </div>
164
+ </div>
165
+ </UPageBody>
166
+ </UPage>
167
+ </template>
168
+
169
+ <script setup lang="ts">
170
+ import { useRoute, useRouter, useToast, useRequestURL, ref, onMounted } from '#imports'
171
+ import type { AuthFormField, FormError, FormSubmitEvent } from '@nuxt/ui'
172
+ import { useFirebaseAuth } from 'vuefire'
173
+ import { isSignInWithEmailLink } from 'firebase/auth'
174
+
175
+ const authStore = useBakusokuAuthStore()
176
+ const route = useRoute()
177
+ const router = useRouter()
178
+ const toast = useToast()
179
+ const url = useRequestURL()
180
+ const firebaseAuth = import.meta.client ? useFirebaseAuth() : null
181
+
182
+ const isLoading = ref(false)
183
+ const isLoadingEmailLink = ref(false)
184
+ const isLoadingGoogle = ref(false)
185
+ const loginMethod = ref(0)
186
+ const emailLinkSent = ref(false)
187
+
188
+ const loginMethods = [
189
+ { label: 'パスワード', value: 1 },
190
+ { label: 'メールリンク', value: 2 },
191
+ ]
192
+
193
+ const loginFields: AuthFormField[] = [
194
+ {
195
+ name: 'email',
196
+ type: 'email',
197
+ label: 'メールアドレス',
198
+ placeholder: 'メールアドレスを入力',
199
+ required: true,
200
+ },
201
+ {
202
+ name: 'password',
203
+ type: 'password',
204
+ label: 'パスワード',
205
+ placeholder: 'パスワードを入力',
206
+ required: true,
207
+ },
208
+ ]
209
+
210
+ const emailLinkFields: AuthFormField[] = [
211
+ {
212
+ name: 'email',
213
+ type: 'email',
214
+ label: 'メールアドレス',
215
+ placeholder: 'メールアドレスを入力',
216
+ required: true,
217
+ },
218
+ ]
219
+
220
+ const highlights = [
221
+ {
222
+ title: '認証フロー',
223
+ description: 'Google・パスワード・メールリンク。ログアウト後に別方式で入り直すと見せやすいです。',
224
+ icon: 'i-lucide-shield-check',
225
+ badge: 'Auth',
226
+ badgeColor: 'primary' as const,
227
+ },
228
+ {
229
+ title: 'ロールとユーザー管理',
230
+ description: 'admin ロールならサイドバーのユーザー管理で一覧・作成・編集・無効化まで確認できます。',
231
+ icon: 'i-lucide-users-round',
232
+ badge: 'Admin',
233
+ badgeColor: 'success' as const,
234
+ },
235
+ {
236
+ title: 'デバッグ時刻',
237
+ description: '下部ツールバーや /debug から effectiveNow をずらせます。',
238
+ icon: 'i-lucide-clock-3',
239
+ badge: 'Debug',
240
+ badgeColor: 'warning' as const,
241
+ },
242
+ ]
243
+
244
+ type LoginSchema = { email: string; password: string }
245
+ type EmailLinkSchema = { email: string }
246
+
247
+ /** メールアドレスとパスワードを検証し、フォーム用のエラーを返す。 */
248
+ function validateLogin(state: Partial<LoginSchema>): FormError[] {
249
+ const errors: FormError[] = []
250
+ if (!state.email) {
251
+ errors.push({ name: 'email', message: 'メールアドレスを入力してください' })
252
+ }
253
+ if (!state.password) {
254
+ errors.push({ name: 'password', message: 'パスワードを入力してください' })
255
+ }
256
+ return errors
257
+ }
258
+
259
+ /** フォームの入力値でメールアドレスとパスワードによるログインを実行する。 */
260
+ async function handleLogin(event: FormSubmitEvent<LoginSchema>) {
261
+ isLoading.value = true
262
+ try {
263
+ await authStore.login(event.data.email, event.data.password)
264
+
265
+ const redirect = route.query.redirect as string | undefined
266
+ await router.push(redirect || '/')
267
+ } catch (error) {
268
+ console.error('ログインエラー:', error)
269
+ } finally {
270
+ isLoading.value = false
271
+ }
272
+ }
273
+
274
+ /** Google ログインを実行し、結果をフォームに反映する。 */
275
+ async function handleLoginWithGoogle() {
276
+ isLoadingGoogle.value = true
277
+ try {
278
+ await authStore.loginWithGoogle()
279
+ toast.add({ title: 'ログインしました', color: 'success' })
280
+ const redirect = route.query.redirect as string | undefined
281
+ await router.push(redirect || '/')
282
+ } catch (error) {
283
+ console.error('Googleログインエラー:', error)
284
+ } finally {
285
+ isLoadingGoogle.value = false
286
+ }
287
+ }
288
+
289
+ /** ログインリンクの送信先メールアドレスを検証する。 */
290
+ function validateEmailLink(state: Partial<EmailLinkSchema>): FormError[] {
291
+ const errors: FormError[] = []
292
+ if (!state.email) {
293
+ errors.push({ name: 'email', message: 'メールアドレスを入力してください' })
294
+ } else if (!state.email.includes('@')) {
295
+ errors.push({ name: 'email', message: '有効なメールアドレスを入力してください' })
296
+ }
297
+ return errors
298
+ }
299
+
300
+ /** 入力されたメールアドレスにログインリンクを送信する。 */
301
+ async function handleSendEmailLink(event: FormSubmitEvent<EmailLinkSchema>) {
302
+ isLoadingEmailLink.value = true
303
+ emailLinkSent.value = false
304
+
305
+ try {
306
+ await authStore.sendEmailLink(event.data.email)
307
+ emailLinkSent.value = true
308
+ toast.add({
309
+ title: 'メールを送信しました',
310
+ description: 'メールボックスを確認して、ログインリンクをクリックしてください。',
311
+ color: 'success',
312
+ })
313
+ } catch (error) {
314
+ console.error('メールリンク送信エラー:', error)
315
+ } finally {
316
+ isLoadingEmailLink.value = false
317
+ }
318
+ }
319
+
320
+ onMounted(async () => {
321
+ if (!firebaseAuth) return
322
+
323
+ if (isSignInWithEmailLink(firebaseAuth, url.toString())) {
324
+ isLoading.value = true
325
+ loginMethod.value = 2
326
+ try {
327
+ await authStore.signInWithEmailLink()
328
+ toast.add({
329
+ title: 'ログインしました',
330
+ color: 'success',
331
+ })
332
+ const redirect = route.query.redirect as string | undefined
333
+ await router.push(redirect || '/')
334
+ } catch (error) {
335
+ console.error('メールリンクログインエラー:', error)
336
+ toast.add({
337
+ title: 'ログインに失敗しました',
338
+ description: authStore.error || 'メールリンクが無効または期限切れです。',
339
+ color: 'error',
340
+ })
341
+ } finally {
342
+ isLoading.value = false
343
+ }
344
+ } else {
345
+ loginMethod.value = 1
346
+ }
347
+ })
348
+ </script>
349
+
350
+ <style scoped>
351
+ .login-page {
352
+ --ui-primary: #0017c1;
353
+ --ui-bg: #fff;
354
+ --ui-bg-elevated: #f2f2f2;
355
+ --ui-bg-muted: #f2f2f2;
356
+ --ui-bg-accented: #e6e6e6;
357
+ --ui-text: #333;
358
+ --ui-text-highlighted: #1a1a1a;
359
+ --ui-text-muted: #666;
360
+ --ui-text-dimmed: #666;
361
+ --ui-text-toned: #333;
362
+ --ui-border: #949494;
363
+ --ui-border-accented: #666;
364
+ color: #333;
365
+ background: #fff;
366
+ }
367
+ .demo-visual { padding: 32px; border: 1px solid #949494; border-radius: 16px; background: #fff; color: #333; }
368
+ .visual-eyebrow { color: #0017c1; font-size: 13px; font-weight: 700; }
369
+ .visual-heading h2 { margin: 16px 0; font-size: clamp(26px, 3vw, 36px); line-height: 1.5; font-weight: 700; }
370
+ .visual-heading h2 span { color: #0017c1; }
371
+ .visual-heading p { font-size: 14px; line-height: 1.8; }
372
+ .build-figure { margin: 28px 0; padding: 24px 16px; border: 1px solid #b3b3b3; border-radius: 12px; text-align: center; }
373
+ .build-inputs { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 8px; }
374
+ .build-inputs span { display: flex; align-items: center; gap: 6px; padding: 8px; border: 1px solid #0017c1; border-radius: 6px; background: #e8f1fe; color: #00118f; font-size: 12px; font-weight: 700; }
375
+ .build-arrow { display: block; margin: 16px auto; color: #0017c1; }
376
+ .app-figure { max-width: 220px; margin: auto; border: 1px solid #949494; border-radius: 8px; padding: 16px; text-align: left; }
377
+ .app-title { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 700; }
378
+ .app-fields { display: grid; gap: 8px; margin: 16px 0; }
379
+ .app-fields span { height: 20px; border: 1px solid #b3b3b3; border-radius: 4px; background: #f2f2f2; }
380
+ .app-action { border-radius: 6px; background: #0017c1; color: #fff; padding: 8px; text-align: center; font-size: 12px; font-weight: 700; }
381
+ .build-figure p { margin-top: 16px; font-size: 12px; color: #666; }
382
+ .visual-features { display: grid; gap: 16px; }
383
+ .visual-feature { display: flex; align-items: center; gap: 12px; font-size: 13px; }
384
+ .visual-feature > :first-child { color: #0017c1; }
385
+ .feature-label { margin-left: auto; font-size: 11px; color: #666; }
386
+ .visual-footer { margin-top: 24px; padding-top: 16px; border-top: 1px solid #949494; font-size: 12px; color: #666; }
387
+ @media (max-width: 380px) {
388
+ .demo-visual { padding: 20px; }
389
+ .build-figure { padding: 20px 10px; }
390
+ }
391
+ </style>
@@ -0,0 +1,224 @@
1
+ <template>
2
+ <div :class="inDashboard ? 'mx-auto w-full max-w-md self-center' : 'p-4 md:p-6 lg:p-8'">
3
+ <div v-if="!inDashboard" class="mx-auto mb-6 flex max-w-md flex-wrap items-start justify-between gap-3">
4
+ <div>
5
+ <h1 class="text-2xl font-semibold">パスワード変更</h1>
6
+ <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
7
+ 現在のパスワードを確認して、新しいログインパスワードへ変更します
8
+ </p>
9
+ </div>
10
+ <UButton
11
+ to="/"
12
+ variant="ghost"
13
+ color="neutral"
14
+ icon="i-heroicons-arrow-left"
15
+ >
16
+ トップへ戻る
17
+ </UButton>
18
+ </div>
19
+
20
+ <div class="mx-auto max-w-md">
21
+ <UCard>
22
+ <UAuthForm
23
+ ref="passwordForm"
24
+ :fields="passwordFields"
25
+ :validate="validatePasswordChange"
26
+ :loading="isLoading"
27
+ :disabled="isLoading"
28
+ title="パスワード変更"
29
+ description="メールアドレスとパスワードでログインしているアカウントが対象です。"
30
+ icon="i-heroicons-key"
31
+ :submit="{ label: '変更する', block: true, color: 'primary' }"
32
+ @submit="handleSubmit"
33
+ >
34
+ <template #validation>
35
+ <UAlert
36
+ v-if="formError"
37
+ color="error"
38
+ variant="soft"
39
+ :title="formError"
40
+ />
41
+ </template>
42
+ </UAuthForm>
43
+ </UCard>
44
+ </div>
45
+ </div>
46
+ </template>
47
+
48
+ <script setup lang="ts">
49
+ import { useBakusokuAuthStore } from '../../stores/auth'
50
+ import { useDashboardHeading, useInDashboardLayout } from '../../utils/dashboard-heading'
51
+
52
+ import type { AuthFormField, FormError, FormSubmitEvent } from '@nuxt/ui'
53
+ import {
54
+ EmailAuthProvider,
55
+ reauthenticateWithCredential,
56
+ } from 'firebase/auth'
57
+ import { useFirebaseAuth } from 'vuefire'
58
+ import {
59
+ changePasswordSchema,
60
+ type ChangePasswordInput,
61
+ } from '#bakusoku/user-schemas-base'
62
+
63
+
64
+ const authStore = useBakusokuAuthStore()
65
+ const inDashboard = useInDashboardLayout()
66
+ const toast = useToast()
67
+
68
+ useDashboardHeading({
69
+ title: 'パスワード変更',
70
+ description: '現在のパスワードを確認して、新しいログインパスワードへ変更します。',
71
+ })
72
+ const firebaseAuth = import.meta.client ? useFirebaseAuth() : null
73
+ const isLoading = ref(false)
74
+ const formError = ref<string | null>(null)
75
+ const passwordFormRef = useTemplateRef<{
76
+ state: ChangePasswordInput
77
+ }>('passwordForm')
78
+
79
+ const passwordFields: AuthFormField[] = [
80
+ {
81
+ name: 'currentPassword',
82
+ type: 'password',
83
+ label: '現在のパスワード',
84
+ placeholder: '現在のパスワードを入力',
85
+ required: true,
86
+ },
87
+ {
88
+ name: 'newPassword',
89
+ type: 'password',
90
+ label: '新しいパスワード',
91
+ placeholder: '新しいパスワードを入力(6文字以上)',
92
+ required: true,
93
+ },
94
+ {
95
+ name: 'confirmPassword',
96
+ type: 'password',
97
+ label: '新しいパスワード(確認)',
98
+ placeholder: '新しいパスワードを再入力',
99
+ required: true,
100
+ },
101
+ ]
102
+
103
+ /** パスワード変更フォームの入力値を検証する。 */
104
+ function validatePasswordChange(state: Partial<ChangePasswordInput>): FormError[] {
105
+ const result = changePasswordSchema.safeParse(state)
106
+ if (result.success) {
107
+ return []
108
+ }
109
+
110
+ return result.error.issues.map((issue) => ({
111
+ name: String(issue.path[0] ?? ''),
112
+ message: issue.message,
113
+ }))
114
+ }
115
+
116
+ /** パスワード変更フォームの入力値を初期化する。 */
117
+ function resetForm() {
118
+ const state = passwordFormRef.value?.state
119
+ if (!state) return
120
+ state.currentPassword = ''
121
+ state.newPassword = ''
122
+ state.confirmPassword = ''
123
+ }
124
+
125
+ /** Firebase Auth の再認証エラーを画面表示用のメッセージに変換する。 */
126
+ function mapReauthError(err: unknown): string {
127
+ const code = (err as { code?: string })?.code
128
+ const messageMap: Record<string, string> = {
129
+ 'auth/wrong-password': '現在のパスワードが正しくありません。',
130
+ 'auth/invalid-credential': '現在のパスワードが正しくありません。',
131
+ 'auth/invalid-login-credentials': '現在のパスワードが正しくありません。',
132
+ 'auth/too-many-requests':
133
+ '試行回数が多すぎます。しばらくしてから再度お試しください。',
134
+ }
135
+ if (code && messageMap[code]) {
136
+ return messageMap[code]
137
+ }
138
+ if (err instanceof Error && err.message) {
139
+ return err.message
140
+ }
141
+ return 'パスワード変更に失敗しました。'
142
+ }
143
+
144
+ /**
145
+ * 現在のパスワードで再認証したうえで変更する。
146
+ * フレームワークに changePasswordWithCurrentPassword がある場合はそれを使う。
147
+ */
148
+ async function changePasswordWithReauth(
149
+ currentPassword: string,
150
+ newPassword: string,
151
+ ) {
152
+ const storeWithReauth = authStore as typeof authStore & {
153
+ changePasswordWithCurrentPassword?: (
154
+ currentPassword: string,
155
+ newPassword: string,
156
+ ) => Promise<void>
157
+ }
158
+
159
+ if (typeof storeWithReauth.changePasswordWithCurrentPassword === 'function') {
160
+ await storeWithReauth.changePasswordWithCurrentPassword(
161
+ currentPassword,
162
+ newPassword,
163
+ )
164
+ return
165
+ }
166
+
167
+ // ストアに再認証付きの変更処理がない場合は、Firebase Auth で再認証する。
168
+ if (!firebaseAuth) {
169
+ throw new Error('Firebaseが初期化されていません。')
170
+ }
171
+
172
+ const firebaseUser = firebaseAuth.currentUser
173
+ if (!firebaseUser) {
174
+ throw new Error('ログインしていません。')
175
+ }
176
+ if (!firebaseUser.email) {
177
+ throw new Error(
178
+ 'メール/パスワードでログインしているアカウントのみパスワードを変更できます。',
179
+ )
180
+ }
181
+
182
+ try {
183
+ const credential = EmailAuthProvider.credential(
184
+ firebaseUser.email,
185
+ currentPassword,
186
+ )
187
+ await reauthenticateWithCredential(firebaseUser, credential)
188
+ } catch (err: unknown) {
189
+ throw new Error(mapReauthError(err))
190
+ }
191
+
192
+ await authStore.changePassword(newPassword)
193
+ }
194
+
195
+ /** パスワード変更を実行し、結果を画面に反映する。 */
196
+ async function handleSubmit(event: FormSubmitEvent<ChangePasswordInput>) {
197
+ isLoading.value = true
198
+ formError.value = null
199
+ try {
200
+ await changePasswordWithReauth(
201
+ event.data.currentPassword,
202
+ event.data.newPassword,
203
+ )
204
+ resetForm()
205
+ toast.add({
206
+ title: 'パスワードを変更しました',
207
+ description: '次回ログインから新しいパスワードを使用できます。',
208
+ color: 'success',
209
+ })
210
+ } catch (error) {
211
+ console.error('パスワード変更エラー:', error)
212
+ formError.value =
213
+ authStore.error
214
+ ?? (error instanceof Error ? error.message : 'パスワード変更に失敗しました。')
215
+ toast.add({
216
+ title: 'パスワード変更に失敗しました',
217
+ description: formError.value,
218
+ color: 'error',
219
+ })
220
+ } finally {
221
+ isLoading.value = false
222
+ }
223
+ }
224
+ </script>