feat(m3): auth & user management with session, tests, and e2e
- Custom error classes (lib/errors.ts) and signed-cookie session (lib/auth/session.ts, HMAC-SHA256, httpOnly+sameSite=lax) - UserRepository + AuthService (bcrypt hashing, role/status checks, register/login/logout/getCurrentUser/updateProfile) - Auth helpers (getCurrentUser), user validator, API error handler - API routes: register (auto-login), login, logout, me, PATCH users/me, GET admin/migrations (admin-only guard) - middleware.ts redirects unauthenticated page access to /login - Screens: login (login/register toggle), profile, dashboard skeleton, home redirect - vitest: exclude e2e specs, setupFiles for SESSION_SECRET - playwright: run migrate before dev server, set SESSION_SECRET - Unit tests (UserRepository, AuthService, session), integration auth-flow, e2e auth.spec (register/login/logout/protected/401)
This commit is contained in:
27
app/api/admin/migrations/route.ts
Normal file
27
app/api/admin/migrations/route.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import path from 'node:path';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { Migrator } from '@/lib/db/migrator';
|
||||
import { getDb } from '@/lib/db/sqlite';
|
||||
import { getCurrentUser } from '@/lib/auth/getCurrentUser';
|
||||
import { UnauthorizedError, ForbiddenError } from '@/lib/errors';
|
||||
import { handleApiError } from '@/lib/api/handleError';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return handleApiError(new UnauthorizedError());
|
||||
}
|
||||
if (user.role !== 'system_admin') {
|
||||
return handleApiError(new ForbiddenError('管理者のみアクセス可能です'));
|
||||
}
|
||||
|
||||
try {
|
||||
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
|
||||
const migrator = new Migrator(getDb(), migrationsDir);
|
||||
return NextResponse.json({ migrations: migrator.getAppliedMigrations() });
|
||||
} catch (error) {
|
||||
return handleApiError(error);
|
||||
}
|
||||
}
|
||||
34
app/api/auth/login/route.ts
Normal file
34
app/api/auth/login/route.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { AuthService } from '@/services/AuthService';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { getDb } from '@/lib/db/sqlite';
|
||||
import { toPublicUser } from '@/lib/auth/getCurrentUser';
|
||||
import { setSessionCookie } from '@/lib/auth/session';
|
||||
import { handleApiError, jsonError } from '@/lib/api/handleError';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return jsonError(400, 'リクエスト本文が不正です');
|
||||
}
|
||||
|
||||
const authService = new AuthService(new UserRepository(getDb()));
|
||||
try {
|
||||
const { user, token } = authService.login(
|
||||
String(body.email ?? ''),
|
||||
String(body.password ?? '')
|
||||
);
|
||||
const response = NextResponse.json(
|
||||
{ user: toPublicUser(user) },
|
||||
{ status: 200 }
|
||||
);
|
||||
setSessionCookie(response, token);
|
||||
return response;
|
||||
} catch (error) {
|
||||
return handleApiError(error);
|
||||
}
|
||||
}
|
||||
10
app/api/auth/logout/route.ts
Normal file
10
app/api/auth/logout/route.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { clearSessionCookie } from '@/lib/auth/session';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST() {
|
||||
const response = NextResponse.json({ ok: true });
|
||||
clearSessionCookie(response);
|
||||
return response;
|
||||
}
|
||||
14
app/api/auth/me/route.ts
Normal file
14
app/api/auth/me/route.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getCurrentUser, toPublicUser } from '@/lib/auth/getCurrentUser';
|
||||
import { UnauthorizedError } from '@/lib/errors';
|
||||
import { handleApiError } from '@/lib/api/handleError';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return handleApiError(new UnauthorizedError());
|
||||
}
|
||||
return NextResponse.json({ user: toPublicUser(user) });
|
||||
}
|
||||
36
app/api/auth/register/route.ts
Normal file
36
app/api/auth/register/route.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { AuthService } from '@/services/AuthService';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { getDb } from '@/lib/db/sqlite';
|
||||
import { toPublicUser } from '@/lib/auth/getCurrentUser';
|
||||
import { createSessionToken, setSessionCookie } from '@/lib/auth/session';
|
||||
import { handleApiError, jsonError } from '@/lib/api/handleError';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return jsonError(400, 'リクエスト本文が不正です');
|
||||
}
|
||||
|
||||
const authService = new AuthService(new UserRepository(getDb()));
|
||||
try {
|
||||
const user = authService.register({
|
||||
name: String(body.name ?? ''),
|
||||
email: String(body.email ?? ''),
|
||||
password: String(body.password ?? ''),
|
||||
});
|
||||
// 登録成功と同時にログイン(セッションCookieを設定)
|
||||
const response = NextResponse.json(
|
||||
{ user: toPublicUser(user) },
|
||||
{ status: 201 }
|
||||
);
|
||||
setSessionCookie(response, createSessionToken(user.id));
|
||||
return response;
|
||||
} catch (error) {
|
||||
return handleApiError(error);
|
||||
}
|
||||
}
|
||||
36
app/api/users/me/route.ts
Normal file
36
app/api/users/me/route.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { AuthService } from '@/services/AuthService';
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { getDb } from '@/lib/db/sqlite';
|
||||
import { getCurrentUser, toPublicUser } from '@/lib/auth/getCurrentUser';
|
||||
import { UnauthorizedError } from '@/lib/errors';
|
||||
import { handleApiError, jsonError } from '@/lib/api/handleError';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function PATCH(request: NextRequest) {
|
||||
const currentUser = await getCurrentUser();
|
||||
if (!currentUser) {
|
||||
return handleApiError(new UnauthorizedError());
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
return jsonError(400, 'リクエスト本文が不正です');
|
||||
}
|
||||
|
||||
const authService = new AuthService(new UserRepository(getDb()));
|
||||
try {
|
||||
const updated = authService.updateProfile(currentUser.id, {
|
||||
name: typeof body.name === 'string' ? body.name : undefined,
|
||||
email: typeof body.email === 'string' ? body.email : undefined,
|
||||
avatarUrl:
|
||||
typeof body.avatarUrl === 'string' ? body.avatarUrl : undefined,
|
||||
});
|
||||
return NextResponse.json({ user: toPublicUser(updated) });
|
||||
} catch (error) {
|
||||
return handleApiError(error);
|
||||
}
|
||||
}
|
||||
27
app/dashboard/page.tsx
Normal file
27
app/dashboard/page.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { getCurrentUser } from '@/lib/auth/getCurrentUser';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-gray-50 p-8">
|
||||
<div className="mx-auto max-w-3xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">ダッシュボード</h1>
|
||||
<a href="/profile" className="text-sm text-blue-600 hover:underline">
|
||||
{user.name} さん
|
||||
</a>
|
||||
</div>
|
||||
<p className="mt-4 text-gray-600">
|
||||
プロジェクト機能は後続マイルストーンで実装されます。
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
131
app/login/page.tsx
Normal file
131
app/login/page.tsx
Normal file
@ -0,0 +1,131 @@
|
||||
'use client';
|
||||
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
type Mode = 'login' | 'register';
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<Mode>('login');
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function onSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const endpoint =
|
||||
mode === 'login' ? '/api/auth/login' : '/api/auth/register';
|
||||
const payload =
|
||||
mode === 'login' ? { email, password } : { name, email, password };
|
||||
|
||||
const res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
router.push('/dashboard');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = (await res.json().catch(() => null)) as {
|
||||
error?: { message?: string };
|
||||
} | null;
|
||||
setError(data?.error?.message ?? '処理に失敗しました');
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-gray-50 p-8">
|
||||
<div className="w-full max-w-sm rounded-lg border bg-white p-8 shadow-sm">
|
||||
<h1 className="text-2xl font-bold">
|
||||
{mode === 'login' ? 'ログイン' : '新規登録'}
|
||||
</h1>
|
||||
|
||||
<form className="mt-6 space-y-4" onSubmit={onSubmit}>
|
||||
{mode === 'register' && (
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium">
|
||||
表示名
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="mt-1 w-full rounded border px-3 py-2"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium">
|
||||
メールアドレス
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="mt-1 w-full rounded border px-3 py-2"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium">
|
||||
パスワード
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete={
|
||||
mode === 'login' ? 'current-password' : 'new-password'
|
||||
}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="mt-1 w-full rounded border px-3 py-2"
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-600" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{loading ? '処理中...' : mode === 'login' ? 'ログイン' : '登録する'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="mt-4 w-full text-center text-sm text-blue-600 hover:underline"
|
||||
onClick={() => {
|
||||
setMode(mode === 'login' ? 'register' : 'login');
|
||||
setError(null);
|
||||
}}
|
||||
>
|
||||
{mode === 'login' ? '新規登録はこちら' : 'ログイン画面に戻る'}
|
||||
</button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
18
app/page.tsx
18
app/page.tsx
@ -1,10 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center p-8">
|
||||
<h1 className="text-3xl font-bold">シンプルグループウェア</h1>
|
||||
<p className="mt-4 text-gray-600">
|
||||
プロジェクト単位で情報共有・タスク管理を行えるチームコラボレーションツール
|
||||
</p>
|
||||
</main>
|
||||
);
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
router.replace('/dashboard');
|
||||
}, [router]);
|
||||
return null;
|
||||
}
|
||||
|
||||
146
app/profile/page.tsx
Normal file
146
app/profile/page.tsx
Normal file
@ -0,0 +1,146 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { PublicUser } from '@/lib/auth/getCurrentUser';
|
||||
|
||||
export default function ProfilePage() {
|
||||
const router = useRouter();
|
||||
const [user, setUser] = useState<PublicUser | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [avatarUrl, setAvatarUrl] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/auth/me')
|
||||
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
|
||||
.then((data: { user: PublicUser }) => {
|
||||
setUser(data.user);
|
||||
setName(data.user.name);
|
||||
setEmail(data.user.email);
|
||||
setAvatarUrl(data.user.avatarUrl ?? '');
|
||||
})
|
||||
.catch(() => router.push('/login'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [router]);
|
||||
|
||||
async function onSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setSaved(false);
|
||||
const res = await fetch('/api/users/me', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, email, avatarUrl }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = (await res.json()) as { user: PublicUser };
|
||||
setUser(data.user);
|
||||
setSaved(true);
|
||||
} else {
|
||||
const data = (await res.json().catch(() => null)) as {
|
||||
error?: { message?: string };
|
||||
} | null;
|
||||
setError(data?.error?.message ?? '更新に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async function onLogout() {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
router.push('/login');
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center">
|
||||
<p>読み込み中...</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-gray-50 p-8">
|
||||
<div className="mx-auto max-w-md rounded-lg border bg-white p-8 shadow-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">プロフィール</h1>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onLogout}
|
||||
className="text-sm text-blue-600 hover:underline"
|
||||
>
|
||||
ログアウト
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form className="mt-6 space-y-4" onSubmit={onSubmit}>
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium">
|
||||
表示名
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="mt-1 w-full rounded border px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium">
|
||||
メールアドレス
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="mt-1 w-full rounded border px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="avatarUrl" className="block text-sm font-medium">
|
||||
アイコン画像URL
|
||||
</label>
|
||||
<input
|
||||
id="avatarUrl"
|
||||
type="url"
|
||||
value={avatarUrl}
|
||||
onChange={(e) => setAvatarUrl(e.target.value)}
|
||||
className="mt-1 w-full rounded border px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-600" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{saved && (
|
||||
<p className="text-sm text-green-600">プロフィールを更新しました</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full rounded bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
保存
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.push('/dashboard')}
|
||||
className="mt-4 w-full text-center text-sm text-blue-600 hover:underline"
|
||||
>
|
||||
ダッシュボードへ
|
||||
</button>
|
||||
<p className="mt-2 text-center text-xs text-gray-500">
|
||||
ロール: {user?.role}
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user