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:
28
lib/api/handleError.ts
Normal file
28
lib/api/handleError.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { AppError, ValidationError } from '@/lib/errors';
|
||||
|
||||
/**
|
||||
* Service層のエラーをHTTPエラーレスポンスに変換する。
|
||||
* 期待されるエラー(AppError)は対応するステータスコードへ、
|
||||
* 予期せぬエラーは500として内部情報を隠蔽する。
|
||||
*/
|
||||
export function handleApiError(error: unknown): NextResponse {
|
||||
if (error instanceof AppError) {
|
||||
const body: { error: { message: string; field?: string } } = {
|
||||
error: { message: error.message },
|
||||
};
|
||||
if (error instanceof ValidationError && error.field) {
|
||||
body.error.field = error.field;
|
||||
}
|
||||
return NextResponse.json(body, { status: error.status });
|
||||
}
|
||||
console.error('Unexpected error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: { message: '内部エラーが発生しました' } },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
export function jsonError(status: number, message: string): NextResponse {
|
||||
return NextResponse.json({ error: { message } }, { status });
|
||||
}
|
||||
6
lib/auth/constants.ts
Normal file
6
lib/auth/constants.ts
Normal file
@ -0,0 +1,6 @@
|
||||
/**
|
||||
* セッションCookie関連の定数。
|
||||
* Edge Runtime(middleware)からも安全に参照できるよう、依存を持たない定数のみ配置する。
|
||||
*/
|
||||
export const SESSION_COOKIE = 'session';
|
||||
export const SESSION_MAX_AGE_SECONDS = 7 * 24 * 60 * 60;
|
||||
33
lib/auth/getCurrentUser.ts
Normal file
33
lib/auth/getCurrentUser.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { UserRepository } from '@/repositories/UserRepository';
|
||||
import { getDb } from '@/lib/db/sqlite';
|
||||
import { getSessionUserId } from '@/lib/auth/session';
|
||||
import type { User } from '@/lib/types';
|
||||
|
||||
/**
|
||||
* APIレスポンス等で外部に公開するユーザー情報(passwordHashを除く)
|
||||
*/
|
||||
export type PublicUser = Omit<User, 'passwordHash'>;
|
||||
|
||||
export function toPublicUser(user: User): PublicUser {
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatarUrl,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 現在のリクエストからログインユーザーを解決する。
|
||||
* 未認証の場合は null を返す。
|
||||
*/
|
||||
export async function getCurrentUser(): Promise<User | null> {
|
||||
const userId = await getSessionUserId();
|
||||
if (userId === null) return null;
|
||||
const userRepository = new UserRepository(getDb());
|
||||
return userRepository.findById(userId);
|
||||
}
|
||||
93
lib/auth/session.ts
Normal file
93
lib/auth/session.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { cookies } from 'next/headers';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { SESSION_COOKIE, SESSION_MAX_AGE_SECONDS } from './constants';
|
||||
|
||||
/**
|
||||
* 署名付きCookieによるステートレスセッション。
|
||||
* トークン形式: base64url(payloadJson).base64url(hmacSha256(secret, encodedPayload))
|
||||
* payload = { uid, iat }
|
||||
*/
|
||||
|
||||
function getSecret(): string {
|
||||
const secret = process.env.SESSION_SECRET;
|
||||
if (!secret) {
|
||||
throw new Error('SESSION_SECRET is not configured');
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
function sign(encodedPayload: string): string {
|
||||
return crypto
|
||||
.createHmac('sha256', getSecret())
|
||||
.update(encodedPayload)
|
||||
.digest('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* ユーザーIDからセッショントークンを生成する
|
||||
*/
|
||||
export function createSessionToken(userId: number): string {
|
||||
const payload = JSON.stringify({ uid: userId, iat: Date.now() });
|
||||
const encoded = Buffer.from(payload, 'utf-8').toString('base64url');
|
||||
return `${encoded}.${sign(encoded)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* セッショントークンを検証し、ユーザーIDを返す(不正時はnull)
|
||||
*/
|
||||
export function verifySessionToken(token: string): number | null {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 2) return null;
|
||||
const [encoded, signature] = parts;
|
||||
const expected = sign(encoded);
|
||||
|
||||
const received = Buffer.from(signature);
|
||||
const wanted = Buffer.from(expected);
|
||||
if (received.length !== wanted.length) return null;
|
||||
if (!crypto.timingSafeEqual(received, wanted)) return null;
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(encoded, 'base64url').toString('utf-8')
|
||||
) as { uid?: unknown };
|
||||
if (typeof payload.uid !== 'number') return null;
|
||||
return payload.uid;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 現在のリクエスト(Server Component / Route Handler)からセッションユーザーIDを取得する
|
||||
*/
|
||||
export async function getSessionUserId(): Promise<number | null> {
|
||||
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
if (!token) return null;
|
||||
return verifySessionToken(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* レスポンスにセッションCookieを設定する
|
||||
*/
|
||||
export function setSessionCookie(res: NextResponse, token: string): void {
|
||||
res.cookies.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
maxAge: SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* レスポンスのセッションCookieを削除する(ログアウト)
|
||||
*/
|
||||
export function clearSessionCookie(res: NextResponse): void {
|
||||
res.cookies.set(SESSION_COOKIE, '', {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 0,
|
||||
});
|
||||
}
|
||||
55
lib/errors.ts
Normal file
55
lib/errors.ts
Normal file
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* アプリケーション全体で使用するカスタムエラー。
|
||||
* 各エラーは HTTP ステータスコードを保持し、Route Handler でレスポンスへの変換が容易。
|
||||
*/
|
||||
|
||||
export class AppError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number
|
||||
) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
}
|
||||
}
|
||||
|
||||
export class ValidationError extends AppError {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly field?: string
|
||||
) {
|
||||
super(message, 400);
|
||||
this.name = 'ValidationError';
|
||||
}
|
||||
}
|
||||
|
||||
export class UnauthorizedError extends AppError {
|
||||
constructor(message: string = '認証が必要です') {
|
||||
super(message, 401);
|
||||
this.name = 'UnauthorizedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ForbiddenError extends AppError {
|
||||
constructor(message: string = 'この操作を行う権限がありません') {
|
||||
super(message, 403);
|
||||
this.name = 'ForbiddenError';
|
||||
}
|
||||
}
|
||||
|
||||
export class NotFoundError extends AppError {
|
||||
constructor(
|
||||
public readonly resource: string,
|
||||
public readonly id: number | string
|
||||
) {
|
||||
super(`${resource} not found: ${id}`, 404);
|
||||
this.name = 'NotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ConflictError extends AppError {
|
||||
constructor(message: string) {
|
||||
super(message, 409);
|
||||
this.name = 'ConflictError';
|
||||
}
|
||||
}
|
||||
95
lib/validators/userValidator.ts
Normal file
95
lib/validators/userValidator.ts
Normal file
@ -0,0 +1,95 @@
|
||||
import { ValidationError } from '@/lib/errors';
|
||||
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
const MAX_NAME_LENGTH = 100;
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
const MAX_AVATAR_URL_LENGTH = 500;
|
||||
|
||||
export interface RegisterInput {
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginInput {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface ProfileUpdateInput {
|
||||
name?: string;
|
||||
email?: string;
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
export function validateRegister(input: RegisterInput): void {
|
||||
validateName(input.name);
|
||||
validateEmail(input.email);
|
||||
validatePassword(input.password);
|
||||
}
|
||||
|
||||
export function validateLogin(input: LoginInput): void {
|
||||
if (!input.email) {
|
||||
throw new ValidationError('メールアドレスを入力してください', 'email');
|
||||
}
|
||||
if (!input.password) {
|
||||
throw new ValidationError('パスワードを入力してください', 'password');
|
||||
}
|
||||
}
|
||||
|
||||
export function validateProfileUpdate(input: ProfileUpdateInput): void {
|
||||
if (
|
||||
input.name === undefined &&
|
||||
input.email === undefined &&
|
||||
input.avatarUrl === undefined
|
||||
) {
|
||||
throw new ValidationError('更新対象のフィールドを指定してください');
|
||||
}
|
||||
if (input.name !== undefined) validateName(input.name);
|
||||
if (input.email !== undefined) validateEmail(input.email);
|
||||
if (
|
||||
input.avatarUrl !== undefined &&
|
||||
input.avatarUrl.length > MAX_AVATAR_URL_LENGTH
|
||||
) {
|
||||
throw new ValidationError(
|
||||
`アイコン画像URLは${MAX_AVATAR_URL_LENGTH}文字以内で入力してください`,
|
||||
'avatarUrl'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateName(name: string): void {
|
||||
if (!name || !name.trim()) {
|
||||
throw new ValidationError('表示名を入力してください', 'name');
|
||||
}
|
||||
if (name.length > MAX_NAME_LENGTH) {
|
||||
throw new ValidationError(
|
||||
`表示名は${MAX_NAME_LENGTH}文字以内で入力してください`,
|
||||
'name'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validateEmail(email: string): void {
|
||||
if (!email) {
|
||||
throw new ValidationError('メールアドレスを入力してください', 'email');
|
||||
}
|
||||
if (!EMAIL_RE.test(email)) {
|
||||
throw new ValidationError(
|
||||
'メールアドレスの形式が正しくありません',
|
||||
'email'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function validatePassword(password: string): void {
|
||||
if (!password) {
|
||||
throw new ValidationError('パスワードを入力してください', 'password');
|
||||
}
|
||||
if (password.length < MIN_PASSWORD_LENGTH) {
|
||||
throw new ValidationError(
|
||||
`パスワードは${MIN_PASSWORD_LENGTH}文字以上で入力してください`,
|
||||
'password'
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user