履歴: プログラミング/svelte
各行は、その日時に書かれた内容です。追加・削除は、1 つ前の版との行数の差です (全 35 版)。「差分」は比較する版、「基準」は比べる相手の版を選びます
| 日時 | タイトル | 文字数 | 追加 | 削除 | 内容 | 差分 | 基準 |
|---|---|---|---|---|---|---|---|
| 2024/9/7 0:08:14 | プログラミング/svelte 最新版 | 5,314 | +5 | -2 | 表示 | 差分 | — |
| 2024/9/6 18:23:34 | プログラミング/svelte | 5,216 | +6 | -0 | 表示 | 差分 | 選択 |
| 2024/8/30 19:02:58 | プログラミング/svelte | 5,042 | +2 | -0 | 表示 | 差分 | 選択 |
| 2024/7/30 3:52:46 | プログラミング/svelte | 4,990 | +1 | -0 | 表示 | 差分 | 選択 |
| 2024/7/21 3:07:50 | プログラミング/svelte | 4,945 | +1 | -1 | 表示 | 差分 | 選択 |
| 2024/7/19 0:55:05 | プログラミング/svelte | 4,911 | +1 | -0 | 表示 | 差分 | 選択 |
| 2024/7/2 7:41:30 | プログラミング/svelte | 4,878 | +112 | -9 | 表示 | 差分 | 選択 |
| 2024/7/1 11:29:30 | プログラミング/svelte | 2,417 | +3 | -0 | 表示 | 差分 | 選択 |
| 2023/12/3 2:48:52 | プログラミング/svelte | 2,360 | +15 | -0 | 表示 | 差分 | 選択 |
| 2023/12/2 0:45:57 | プログラミング/svelte | 2,026 | +1 | -0 | 表示 | 差分 | 選択 |
| 2023/11/30 15:59:20 | プログラミング/svelte | 1,988 | +3 | -30 | 表示 | 差分 | 選択 |
| 2023/11/29 18:54:52 | プログラミング/svelte | 2,505 | +17 | -0 | 表示 | 差分 | 選択 |
| 2023/11/29 3:15:43 | プログラミング/svelte | 2,101 | +1 | -0 | 表示 | 差分 | 選択 |
| 2023/11/28 10:21:04 | プログラミング/svelte | 2,066 | +10 | -4390 | 表示 | 差分 | 選択 |
| 2023/11/27 15:12:30 | プログラミング/svelte | 136,600 | +364 | -1 | 表示 | 差分 | 選択 |
| 2023/11/27 7:26:06 | プログラミング/svelte | 127,338 | +284 | -0 | 表示 | 差分 | 選択 |
| 2023/11/26 16:26:54 | プログラミング/svelte | 118,533 | +675 | -15 | 表示 | 差分 | 選択 |
| 2023/11/26 10:53:18 | プログラミング/svelte | 93,589 | +50 | -6 | 表示 | 差分 | 選択 |
| 2023/11/25 1:44:35 | プログラミング/svelte | 91,814 | +66 | -0 | 表示 | 差分 | 選択 |
| 2023/11/24 16:23:08 | プログラミング/svelte | 90,481 | +460 | -3 | 表示 | 差分 | 選択 |
| 2023/11/24 8:25:16 | プログラミング/svelte | 76,694 | +213 | -23 | 表示 | 差分 | 選択 |
| 2023/11/23 22:42:10 | プログラミング/svelte | 66,195 | +7 | -7 | 表示 | 差分 | 選択 |
| 2023/11/23 12:53:25 | プログラミング/svelte | 66,212 | +18 | -29 | 表示 | 表示中 | 選択 |
| 2023/11/23 9:32:58 | プログラミング/svelte | 66,711 | +512 | -38 | 表示 | 差分 | 選択 |
| 2023/11/23 0:44:28 | プログラミング/svelte | 52,259 | +300 | -55 | 表示 | 差分 | 基準 |
| 2023/11/22 14:35:58 | プログラミング/svelte | 45,266 | +81 | -0 | 表示 | 差分 | 選択 |
| 2023/11/22 7:59:00 | プログラミング/svelte | 43,056 | +124 | -5 | 表示 | 差分 | 選択 |
| 2023/11/22 0:32:39 | プログラミング/svelte | 39,942 | +210 | -86 | 表示 | 差分 | 選択 |
| 2023/11/21 14:18:13 | プログラミング/svelte | 36,876 | +93 | -5 | 表示 | 差分 | 選択 |
| 2023/11/21 11:45:28 | プログラミング/svelte | 34,915 | +825 | -5 | 表示 | 差分 | 選択 |
| 2023/7/5 14:16:38 | プログラミング/svelte | 12,623 | +1 | -1 | 表示 | 差分 | 選択 |
| 2023/6/1 13:11:31 | プログラミング/svelte | 12,622 | +12 | -1 | 表示 | 差分 | 選択 |
| 2023/6/1 6:47:49 | プログラミング/svelte | 12,354 | +412 | -2 | 表示 | 差分 | 選択 |
| 2023/5/22 9:38:55 | プログラミング/svelte | 592 | +9 | -0 | 表示 | 差分 | 選択 |
| 2023/5/15 2:26:56 | プログラミング/svelte | 271 | — | — | 表示 | — | 選択 |
基準: プログラミング/svelte (2023/11/23 0:44:28) → 比較: プログラミング/svelte (2023/11/23 12:53:25)
@@ -6,7 +6,7 @@
#contents
-** いまのところ情報収集中 [#o6d339e1]
+** いまのところ[#o6d339e1]
- SvelteKit+Superforms+Prisma+Luciaでログイン機能を爆速で実装する~
https://zenn.dev/gawarago/articles/f75f5113a3803d
@@ -18,7 +18,8 @@
https://zenn.dev/moneyforward/articles/typescript-as-const-satisfies
- コーディング不要でGraphQLサーバが作れるPrismaを触ってみて可能性を感じた - SMARTCAMP Engineer Blog~
https://tech.smartcamp.co.jp/entry/started-prisma
-
+- worst password list~
+https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10-million-password-list-top-100000.txt
* VS Code + Git Bash + nvm のインストール [#d5c705f1]
https://blog.css-net.co.jp/entry/dev-environment-windows#2-2-Git-for-Windows
@@ -658,7 +659,7 @@
*** signup フォーム用のスキーマを追加 [#ud9711bc]
-src/lib/formSchemas/signupSchema.ts
+src/lib/formSchemas/signup.ts
LANG:ts
import { z } from 'zod';
@@ -666,7 +667,7 @@
// https://qiita.com/sakuro/items/1eaa307609ceaaf51123
const emailRegexp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
- export const signupSchema = z
+ export const schema = z
.object({
name: z.string().min(3, { message: 'ユーザー名は3文字以上で入力してください' }),
email: z.string().regex(emailRegexp, { message: 'メールアドレスが不正です' }),
@@ -681,20 +682,17 @@
message: '確認用パスワードが一致しません',
path: ['confirm']
});
-
- export type signupSchemaType = typeof signupSchema;
+
*** バリデーションを行う [#c81e3fa9]
src/routes/(loggedOut)/signup/+page.server.ts
LANG:ts
import type { Actions, PageServerLoad } from './$types';
- import { signupSchema } from '$lib/formSchemas/signupSchema';
+ import { schema } from '$lib/formSchemas/signup';
import { superValidate } from 'sveltekit-superforms/server';
import { fail } from '@sveltejs/kit';
- const schema = signupSchema;
-
export const load = (async () => {
const form = await superValidate(schema);
return { form };
@@ -807,6 +805,7 @@
LANG: console
$ echo "/prisma/*.db" >> .gitignore
+ $ echo "/prisma/*.db-journal" >> .gitignore
*** Lucia に対応したテーブルを定義 [#a634da69]
@@ -1158,17 +1157,15 @@
メールアドレスやパスワードが正しいかどうかはログイン処理で確認するので
ここでは1文字でも入力されていれば良いことにする。
-src/lib/formSchemas/loginSchema.ts
+src/lib/formSchemas/login.ts
LANG: ts
import { z } from 'zod';
- export const loginSchema = z
+ export const schema = z
.object({
email: z.string().min(1, 'メールアドレスを入力して下さい'),
password: z.string().min(1, 'パスワードを入力して下さい'),
});
-
- export type loginSchemaType = typeof loginSchema;
ログインフォーム
@@ -1211,7 +1208,7 @@
src/routes/(loggedOut)/login/+page.server.ts
LANG: ts
import type { Actions, PageServerLoad } from './$types';
- import { loginSchema as schema } from '$lib/formSchemas/loginSchema';
+ import { schema } from '$lib/formSchemas/login';
import { superValidate } from 'sveltekit-superforms/server';
import { fail } from '@sveltejs/kit';
@@ -1614,7 +1611,7 @@
そもそも email を verify しないと signup ページに
たどり着けない形にした方が間違いが生じない気がする?
-+ /signup/email-verification でメールアドレスのみ入力
++ /signup でメールアドレスのみ入力
+ メールが届く
+ メールに記載のリンク先で名前やパスワードなどメールアドレス以外の情報を入力
-- /signup/xxxxxxxx
@@ -1634,7 +1631,7 @@
actor User
participant System
database Database
-User -> System : /signup/email-verification へアクセス
+User -> System : /signup へアクセス
System --> User : メールアドレス入力フォームを表示
User -> System : メールアドレスを入力
System -> Database : トークンとメールアドレスを保存
@@ -1655,7 +1652,7 @@
サインアップと同様に以下の流れで行う。
-+ /reset-password/email-verification にメールアドレスだけを入力
++ /reset-passwordn にメールアドレスだけを入力
+ メールが届く
+ メールに記載のリンク先で新しいパスワードを入力
-- /reset-password/xxxxxxxx
@@ -1665,7 +1662,7 @@
actor User
participant System
database Database
-User -> System : /reset-password/email-verification へアクセス
+User -> System : /reset-password へアクセス
System --> User : メールアドレス入力フォームを表示
User -> System : メールアドレスを入力
System -> Database : トークンとメールアドレスを保存
@@ -1707,19 +1704,17 @@
メールアドレスのチェックを行うスキーマを用意
-src/lib/formSchemas/emailVerificationSchema.ts
+src/lib/formSchemas/emailVerification.ts
LANG: ts
import { z } from 'zod';
import { emailRegexp } from '$lib/emailRegexp'
- export const emailVerificationSchema = z
+ export const schema = z
.object({
email: z.string().regex(emailRegexp, { message: 'メールアドレスが不正です' }),
})
-
- export type emailVerificationSchemaType = typeof emailVerificationSchema;
-サインアップとパスワードリセットの両方に使えるようにするため
+サインアップとパスワードリセットの両方を扱えるようにするため
matcher を使ったルーティングを行う。
https://kit.svelte.jp/docs/advanced-routing#matching
@@ -1740,7 +1735,7 @@
return Object.hasOwn(purposes, param);
};
-src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/email-verification/+page.svelte
+src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/+page.svelte
LANG: html
<script lang="ts">
import type { PageData } from './$types';
@@ -1776,30 +1771,39 @@
}
</style>
-src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/email-verification/+page.server.ts
+src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/+page.server.ts
LANG: ts
- import type { Actions, PageServerLoad } from './$types';
- import { emailVerificationSchema as schema } from '$lib/formSchemas/emailVerificationSchema';
+ import type { Actions, PageServerLoad, PageServerLoadEvent, RequestEvent } from './$types';
+ import { schema } from '$lib/formSchemas/emailVerification';
import { superValidate } from 'sveltekit-superforms/server';
import { fail } from '@sveltejs/kit';
import { redirect } from 'sveltekit-flash-message/server';
- import type { purposes } from '$params/emailVerificationPurpose';
+ import { purposes } from '$lib/emailVerificationPurposes';
+ import { transporter } from '$lib/server/transporter';
- export const load = (async (event) => {
- // 目的を確認
+ import { db } from '$lib/server/db'
+
+ async function getPurpose(event: PageServerLoadEvent | RequestEvent) {
const purpose = event.params.purpose as keyof typeof purposes;
+ const session = await event.locals.auth.validate();
+ if((purpose == 'change-email') !== (!! session?.user)) {
+ throw redirect(302, '/', { type: 'error', message: 'ログイン状態が無効です'}, event);
+ }
+ return purpose;
+ }
+ export const load = (async (event) => {
const form = await superValidate(schema);
+ const purpose = await getPurpose(event);
return { form, purpose };
}) satisfies PageServerLoad;
export const actions: Actions = {
default: async (event) => {
- // 目的を確認
- const purpose = event.params.purpose as keyof typeof purposes;
// フォームデータのバリデーション
const form = await superValidate(event, schema);
+ const purpose = await getPurpose(event);
if (!form.valid) {
return fail(400, { form, purpose });
}
@@ -1816,7 +1820,7 @@
一定時間以内に作成されたものがすでに存在すればエラーにする
-src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/email-verification/+page.server.ts
+src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/+page.server.ts
LANG: ts
// emailVerification レコードが既に存在するか?
const existing = await db.emailVerification.findUnique({where: {email: form.data.email}})
@@ -1852,14 +1856,14 @@
port: 25,
});
-src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/email-verification/+page.server.ts
+src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/+page.server.ts
LANG: ts
import { transporter } from '$lib/server/transporter';
...
// メールを送信
- const url = `${purpose}/${token}`
+ const url = `${event.url.origin}/${purpose}/${token}`
try {
await transporter.sendMail({
@@ -1874,44 +1878,503 @@
*** サインアップフォーム [#j99985ea]
+フォームからメールアドレス欄を除く
+
+src/lib/formSchemas/signup.ts
+ LANG: ts
+ import { z } from 'zod';
+
+ - // https://qiita.com/sakuro/items/1eaa307609ceaaf51123
+ - const emailRegexp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
+ -
+ export const schema = z
+ .object({
+ name: z.string().min(3, { message: 'ユーザー名は3文字以上で入力してください' }),
+ - email: z.string().regex(emailRegexp, { message: 'メールアドレスが不正です' }),
+ password: z
+ .string()
+ .regex(/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/, {
+ message: 'パスワードは小文字・大文字・数字を一文字以上含めて8文字以上で入力してください'
+ }),
+ confirm: z.string(),
+ })
+ .refine((data) => data.password === data.confirm, {
+ message: '確認用パスワードが一致しません',
+ path: ['confirm']
+ });
+
+disabled にしたフィールドは表示専用になりフォーム送信時にデータが送られない。
+
+src/routes/(loggedOut)/signup/[token]/+page.svelte
+ LANG: html
+ <label for="email">メールアドレス</label>
+ + <input type="text" name="email" bind:value={data.email} disabled={true} />
+ - <input type="text" name="email" bind:value={$form.email} disabled={$submitting} readonly={true} />
+ - {#if $errors.email}<span class="invalid">{$errors.email}</span>{/if}
+
以前の src/routes/(loggedOut)/signup/+page.* を
src/routes/(loggedOut)/signup/[token]/+page.* に移す。
+form と共に email アドレスを返す。
+
src/routes/(loggedOut)/signup/[token]/+page.server.ts
LANG: ts
- - export const load = (async () => {
- + export const load = (async (event) => {
- const form = await superValidate(schema);
-
- + // トークンをチェックしてメールアドレスを設定
- + const token = event.params.token;
- + const record = await db.emailVerification.findUnique({where: {id: token}})
+ - import type { Actions, PageServerLoad } from './$types';
+ + import type { Actions, PageServerLoad, PageServerLoadEvent, RequestEvent } from './$types';
+ ...
+
+ + async function getEmail(event: PageServerLoadEvent | RequestEvent) {
+ + const record = await db.emailVerification.findUnique({where: {id: event.params.token}})
+ if(!record || Date.now() - (1000 * 60 * 60 * 2) > record.createdAt.getTime()) {
+ // 見つからないあるいは古すぎる
+ throw redirect(302, '/', {type: 'error', message: '無効なトークンです'}, event);
+ }
- + form.data.email = record.email;
+ + return record.email;
+ + }
- return { form };
+ - export const load = (async () => {
+ + export const load = (async (event) => {
+ const form = await superValidate(schema);
+ - return { form };
+ + const email = await getEmail(event)
+ + return { form, email };
}) satisfies PageServerLoad;
export const actions: Actions = {
default: async (event) => {
+
// フォームデータのバリデーション
const form = await superValidate(event, schema);
+ + const email = await getEmail(event)
if (!form.valid) {
- return fail(400, { form });
+ return fail(400, { form, email });
}
+
+ // サインアップ処理
+ try {
+ const user = await auth.createUser({
+ key: {
+ providerId: 'email',
+ - providerUserId: form.data.email,
+ + providerUserId: email,
+ password: form.data.password
+ },
+ attributes: {
+ name: form.data.name,
+ - email: form.data.email,
+ + email: email,
+ }
+ });
+ ...
- + const token = event.params.token;
- + const record = await db.emailVerification.findUnique({where: {id: token}})
- + if(!record || Date.now() - (1000 * 60 * 60 * 2) > record.createdAt.getTime()) {
- + // 見つからないあるいは古すぎる
- + throw redirect(302, '/', {type: 'error', message: '無効なトークンです'}, event);
+ - return fail(400, { form: { ...form, message: '名前またはメールアドレスが既存のアカウントと重複しています' } });
+ + return fail(400, { form: { ...form, message: '名前またはメールアドレスが既存のアカウントと重複しています' }, email });
+
+ ...
+
+ - return fail(400, { form: { ...form, message: 'サインアップエラー' } });
+ + return fail(400, { form: { ...form, message: 'サインアップエラー' }, email });
+ ...
+
+ + // レコードを消去
+ + await db.emailVerification.delete({where: {id: event.params.token}})
+
+ throw redirect(302, '/', { type: 'success', message: 'サインアップしました'}, event);
+ }
+ };
+
+これで大丈夫そう。
+
+*** パスワードリセット [#l485ccd3]
+
+メール送信フォームでそのメールアドレスを持つアカウントの存在を確認する
+
+src/routes/(loggedOut)/[purpose=emailVerificationPurpose]/+page.server.ts
+ LANG: ts
+ // フォームデータのバリデーション
+ const form = await superValidate(event, schema);
+ if (!form.valid) {
+ return fail(400, { form, purpose });
+ }
+
+ + // パスワードリセットは既存のアカウントがなければエラー
+ + if(purpose == 'reset-password') {
+ + if(!await db.authUser.findUnique({where: {email: form.data.email}})){
+ + form.errors.email = [...(form.errors.email || []), '登録されていません']
+ + return fail(400, { form, purpose });
+ + }
+ + }
+
+フォーム検証スキーム
+
+authtest/src/lib/formSchemas/resetPassword.ts
+ LANG: ts
+ import { z } from 'zod';
+
+ export const schema = z
+ .object({
+ password: z
+ .string()
+ .regex(/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/, {
+ message: 'パスワードは小文字・大文字・数字を一文字以上含めて8文字以上で入力してください'
+ }),
+ confirm: z.string(),
+ })
+ .refine((data) => data.password === data.confirm, {
+ message: '確認用パスワードが一致しません',
+ path: ['confirm']
+ });
+
+ユーザー名とメールアドレスは変更不可
+
+フォームに表示はするが disable なので値は POST されない。
+
+src/routes/(loggedOut)/reset-password/[token]/+page.svelte
+ LANG: html
+ <script lang="ts">
+ import type { PageData } from './$types';
+ import { superForm } from 'sveltekit-superforms/client';
+
+ export let data: PageData;
+ const { form, message, errors, submitting, capture, restore, enhance } = superForm(data.form, {
+ taintedMessage: false
+ });
+ export const snapshot = { capture, restore };
+ </script>
+
+ <div>
+ <h1>パスワードの変更</h1>
+ {#if $message}<span class="invalid">{$message}</span>{/if}
+ <form method="POST" use:enhance>
+ <label for="name">ユーザー名</label>
+ <input type="text" name="name" bind:value={data.user.name} disabled={true} />
+
+ <label for="email">メールアドレス</label>
+ <input type="text" name="email" bind:value={data.user.email} disabled={true} />
+
+ <label for="password">パスワード</label>
+ <input type="password" name="password" bind:value={$form.password} disabled={$submitting} />
+ {#if $errors.password}<span class="invalid">{$errors.password}</span>{/if}
+
+ <label for="confirm">パスワード(確認)</label>
+ <input
+ type="password"
+ name="confirm"
+ bind:value={$form.confirm}
+ disabled={$submitting}
+ />
+ {#if $errors.confirm}<span class="invalid">{$errors.confirm}</span>{/if}
+
+ <div><button disabled={$submitting}>パスワードを変更</button></div>
+ </form>
+ </div>
+
+ <style>
+ .invalid {
+ color: red;
+ }
+ </style>
+
+src/routes/(loggedOut)/reset-password/[token]/+page.server.ts
+ LANG: ts
+ import type { Actions, PageServerLoad, PageServerLoadEvent, RequestEvent } from './$types';
+ import { schema } from '$lib/formSchemas/signup';
+ import { superValidate } from 'sveltekit-superforms/server';
+ import { fail } from '@sveltejs/kit';
+ import { redirect } from 'sveltekit-flash-message/server';
+ import { auth } from '$lib/server/lucia';
+ import { db } from '$lib/server/db'
+
+ async function getUser(event: PageServerLoadEvent | RequestEvent) {
+ const record = await db.emailVerification.findUnique({where: {id: event.params.token}});
+ if(!record || Date.now() - (1000 * 60 * 60 * 2) > record.createdAt.getTime()) {
+ throw redirect(302, '/', {type: 'error', message: '無効なトークンです'}, event);
+ }
+
+ const user = await db.authUser.findUnique({where: {email: record.email}});
+ if (!user) {
+ throw redirect(302, '/', {type: 'error', message: '無効なトークンです'}, event);
+ }
+ return user;
+ }
+
+ export const load = (async (event) => {
+ const form = await superValidate(schema);
+ const user = await getUser(event);
+ return { form, user };
+ }) satisfies PageServerLoad;
+
+ export const actions: Actions = {
+ default: async (event) => {
+ // フォームデータのバリデーション
+ const form = await superValidate(event, schema);
+ const user = await getUser(event);
+ if (!form.valid) {
+ return fail(400, { form, user });
+ }
+
+ // パスワードを変更
+ auth.updateKeyPassword(
+ 'email', user.email, form.data.password
+ )
+
+ // 直接ログインする
+ const session = await auth.createSession({userId: user.id, attributes: {}});
+ event.locals.auth.setSession(session);
+
+ // レコードを消去
+ await db.emailVerification.delete({where: {id: event.params.token}});
+
+ throw redirect(302, '/', { type: 'success', message: 'パスワードを変更してログインしました'}, event);
+ }
+ };
+
+** メールアドレス変更 [#g1870852]
+
+これもメールアドレスを確認後、飛び先で確認ボタンを押したら変更という形にすべき。
+
+'chage-email' というパスを用意
+
+src/lib/emailVerificationPurposes.ts
+ LANG: ts
+ export const purposes = {
+ signup: 'サインアップ',
+ 'reset-password': 'パスワードリセット',
+ + 'change-email': 'メールアドレス変更',
+ };
+
+signup や reset-password はログアウト状態で行う処理だったのに対して
+この作業はログイン状態で行うので、
+
+src/routes/(loggedOut)/[purpose=emailVerificationPurpose] を~
+src/routes/[purpose=emailVerificationPurpose] へ移動した上で、
+
+コード上でログイン状態を確認することにした。
+
+|>||>|!!session?.user|
+|~|~|true|false|
+|purpose == 'change-email'|true|OK|Error|
+|~|false|Error|OK|
+
+なので (purpose == 'change-email') !== (!! session?.user) で判断すればいい。
+
+src/routes/[purpose=emailVerificationPurpose]/+page.server.ts
+ LANG: ts
+ export const load = (async (event) => {
+ // 目的を確認
+ const purpose = event.params.purpose as keyof typeof purposes;
+ + const session = await event.locals.auth.validate();
+ + if((purpose == 'change-email') !== (!! session?.user)) {
+ + throw redirect(302, '/', { type: 'error', message: 'ログイン状態が無効です'}, event);
+ + }
+ ...
+
+ // 目的を確認
+ const purpose = event.params.purpose as keyof typeof purposes;
+ + const session = await event.locals.auth.validate();
+ + if((purpose == 'change-email') !== (!! session?.user)) {
+ + throw redirect(302, '/', { type: 'error', message: 'ログイン状態が無効です'}, event);
+ }
- + if(form.data.email != record.email) {
- + form.errors.email = [...(form.errors.email || []), 'メールアドレスは変更できません'];
- + return fail(400, { form });
- + }
-こんな感じ?
+フォームは単なる確認用なのでデータは何も受け取らない
+
+したがって、バリデーション用スキームも必要ない
+
+src/routes/(loggedIn)/change-email/[token]/+page.svelte
+ LANG: html
+ <script lang="ts">
+ import type { PageData } from './$types';
+ export let data: PageData;
+ </script>
+
+ <div>
+ <h1>メールアドレスの変更</h1>
+ <form method="POST">
+ <label for="name">ユーザー名</label>
+ <input type="text" name="name" value={data.user.name} disabled />
+
+ <label for="email">古いメールアドレス</label>
+ <input type="text" name="email" value={data.user.email} disabled />
+
+ <label for="email">新しいメールアドレス</label>
+ <input type="text" name="email" value={data.email} disabled />
+
+ <div><button>メールアドレスを変更</button></div>
+ </form>
+ </div>
+
+認証キー(ここではメールアドレス)を変更する機能は Lucia には備わっていない?
+
+見つけられなかったのでデータベースを直接書き換えている。
+
+src/routes/(loggedIn)/change-email/[token]/+page.server.ts
+ LANG: ts
+ import type { Actions, PageServerLoad, PageServerLoadEvent, RequestEvent } from './$types';
+ import { redirect } from 'sveltekit-flash-message/server';
+ import { db } from '$lib/server/db'
+
+ async function getEmailAndUser(event: PageServerLoadEvent | RequestEvent) {
+ const record = await db.emailVerification.findUnique({where: {id: event.params.token}});
+ if(!record || Date.now() - (1000 * 60 * 60 * 2) > record.createdAt.getTime()) {
+ throw redirect(302, '/', {type: 'error', message: '無効なトークンです'}, event);
+ }
+
+ const session = await event.locals.auth.validate();
+ if(!session?.user) {
+ throw redirect(302, '/login', {type: 'error', message: '旧メールアドレスでログインしてください'}, event);
+ }
+
+ return {email: record.email, user: session.user};
+ }
+
+ export const load = (async (event) => {
+ return await getEmailAndUser(event);
+ }) satisfies PageServerLoad;
+
+ export const actions: Actions = {
+ default: async (event) => {
+ const {email, user} = await getEmailAndUser(event);
+
+ // メールアドレスを変更
+ db.$transaction([
+ db.authUser.update({
+ where: {id: user.userId},
+ data: {email},
+ }),
+ db.authKey.update({
+ where: {id: `email:${user.email}`, user_id: user.userId},
+ data: {id: `email:${email}`},
+ }),
+ ])
+
+ // レコードを消去
+ await db.emailVerification.delete({where: {id: event.params.token}});
+
+ throw redirect(302, '/', { type: 'success', message: 'メールアドレスを変更しました'}, event);
+ }
+ };
+
+** ユーザー情報変更 [#ea677d6d]
+
+メールアドレス以外を変更できる
+
+パスワードを変更しない場合には空にしておく
+
+src/lib/formSchemas/changeProfile.ts
+ LANG: ts
+ import { z } from 'zod';
+
+ export const schema = z
+ .object({
+ name: z.string().min(3, { message: 'ユーザー名は3文字以上で入力してください' }),
+ password: z
+ .string()
+ .regex(/^$|^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/, {
+ message: 'パスワードは小文字・大文字・数字を一文字以上含めて8文字以上で入力してください'
+ }),
+ confirm: z.string(),
+ })
+ .refine((data) => data.password === data.confirm, {
+ message: '確認用パスワードが一致しません',
+ path: ['confirm']
+ });
+
+src/routes/(loggedIn)/change-profile/+page.svelte
+ LANG: html
+ <script lang="ts">
+ import type { PageData } from './$types';
+ import { superForm } from 'sveltekit-superforms/client';
+
+ export let data: PageData;
+ const { form, message, errors, submitting, capture, restore, enhance } = superForm(data.form, {
+ taintedMessage: false
+ });
+ export const snapshot = { capture, restore };
+ </script>
+
+ <div>
+ <h1>ユーザー情報の変更</h1>
+ {#if $message}<span class="invalid">{$message}</span>{/if}
+ <form method="POST" use:enhance>
+ <label for="name">ユーザー名</label>
+ <input type="text" name="name" bind:value={$form.name} disabled={$submitting} />
+ {#if $errors.name}<span class="invalid">{$errors.name}</span>{/if}
+
+ <label for="email">メールアドレス</label>
+ <input type="text" name="email" bind:value={data.user.email} disabled={true} />
+
+ <label for="password">パスワード(変更しないなら何も入力しない)</label>
+ <input type="password" name="password" bind:value={$form.password} disabled={$submitting} />
+ {#if $errors.password}<span class="invalid">{$errors.password}</span>{/if}
+
+ <label for="confirm">パスワード(確認)</label>
+ <input
+ type="password"
+ name="confirm"
+ bind:value={$form.confirm}
+ disabled={$submitting}
+ />
+ {#if $errors.confirm}<span class="invalid">{$errors.confirm}</span>{/if}
+
+ <div><button disabled={$submitting}>ユーザー情報を変更</button></div>
+ </form>
+ </div>
+
+ <style>
+ .invalid {
+ color: red;
+ }
+ </style>
+
+src/routes/(loggedIn)/change-profile/+page.svelte
+ LANG: ts
+ import type { Actions, PageServerLoad, PageServerLoadEvent, RequestEvent } from './$types';
+ import { schema } from '$lib/formSchemas/changeProfile';
+ import { superValidate } from 'sveltekit-superforms/server';
+ import { fail } from '@sveltejs/kit';
+ import { redirect } from 'sveltekit-flash-message/server';
+
+ import { auth } from '$lib/server/lucia';
+ import { db } from '$lib/server/db'
+
+ async function getUser(event: PageServerLoadEvent | RequestEvent) {
+ const session = await event.locals.auth.validate();
+ return session!.user;
+ }
+
+ export const load = (async (event) => {
+ const form = await superValidate(schema);
+ const user = await getUser(event);
+ form.data.name = user.name;
+ return { form, user };
+ }) satisfies PageServerLoad;
+
+ export const actions: Actions = {
+ default: async (event) => {
+
+ // フォームデータのバリデーション
+ const form = await superValidate(event, schema);
+ const user = await getUser(event);
+ if (!form.valid) {
+ return fail(400, { form, user });
+ }
+
+ const changed = [] as string[];
+ if(form.data.password) {
+ auth.updateKeyPassword('email', user.email, form.data.password);
+ changed.push('パスワード');
+ }
+ if(form.data.name != user.name) {
+ db.authUser.update({where: {id: user.userId}, data: {name: user.name}});
+ changed.push('名前');
+ }
+
+ let message: string;
+ if(changed.length == 0) {
+ message = '何も変更されませんでした';
+ } else {
+ message = changed.join('と') + 'が変更されました';
+ }
+ throw redirect(302, '/', { type: 'success', message}, event);
+ }
+ };