v0.1.9 - 인증 API 추가

This commit is contained in:
2026-04-21 17:56:47 +09:00
parent d5aa7f8153
commit 20095a79db
10 changed files with 310 additions and 6 deletions

View File

@@ -12,6 +12,7 @@ const envSchema = z.object({
PORT: z.coerce.number().default(3001),
DB_FILE: z.string().default('./data/planner.sqlite'),
CORS_ORIGIN: z.string().default('http://localhost:5173'),
SESSION_TTL_DAYS: z.coerce.number().default(30),
})
export const env = envSchema.parse(process.env)

36
backend/src/db/init.js Normal file
View File

@@ -0,0 +1,36 @@
import { sqlite } from './client.js'
export function ensureDatabaseSchema() {
sqlite.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
nickname TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS auth_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS planner_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
entry_date TEXT NOT NULL,
payload TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX IF NOT EXISTS planner_entries_user_date_unique
ON planner_entries (user_id, entry_date);
`)
}

View File

@@ -9,6 +9,14 @@ export const users = sqliteTable('users', {
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
})
export const authSessions = sqliteTable('auth_sessions', {
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
tokenHash: text('token_hash').notNull().unique(),
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
})
export const plannerEntries = sqliteTable('planner_entries', {
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),

View File

@@ -0,0 +1,47 @@
import crypto from 'node:crypto'
const SCRYPT_KEY_LENGTH = 64
function scryptAsync(password, salt) {
return new Promise((resolve, reject) => {
crypto.scrypt(password, salt, SCRYPT_KEY_LENGTH, (error, derivedKey) => {
if (error) {
reject(error)
return
}
resolve(derivedKey)
})
})
}
export async function hashPassword(password) {
const salt = crypto.randomBytes(16).toString('hex')
const derivedKey = await scryptAsync(password, salt)
return `${salt}:${derivedKey.toString('hex')}`
}
export async function verifyPassword(password, storedHash) {
const [salt, originalHash] = storedHash.split(':')
if (!salt || !originalHash) {
return false
}
const derivedKey = await scryptAsync(password, salt)
const originalBuffer = Buffer.from(originalHash, 'hex')
if (originalBuffer.length !== derivedKey.length) {
return false
}
return crypto.timingSafeEqual(originalBuffer, derivedKey)
}
export function createSessionToken() {
return crypto.randomBytes(32).toString('hex')
}
export function hashSessionToken(token) {
return crypto.createHash('sha256').update(token).digest('hex')
}

197
backend/src/routes/auth.js Normal file
View File

@@ -0,0 +1,197 @@
import { eq } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../db/client.js'
import { authSessions, users } from '../db/schema.js'
import { env } from '../config.js'
import {
createSessionToken,
hashPassword,
hashSessionToken,
verifyPassword,
} from '../lib/password.js'
const signupSchema = z.object({
email: z.string().trim().email(),
password: z.string().min(8).max(72),
nickname: z.string().trim().min(2).max(30),
})
const loginSchema = z.object({
email: z.string().trim().email(),
password: z.string().min(1).max(72),
})
function sanitizeUser(user) {
return {
id: user.id,
email: user.email,
nickname: user.nickname,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
}
}
function getBearerToken(request) {
const authorization = request.headers.authorization
if (!authorization?.startsWith('Bearer ')) {
return null
}
return authorization.slice('Bearer '.length).trim()
}
async function createSession(userId) {
const token = createSessionToken()
const tokenHash = hashSessionToken(token)
const now = Date.now()
const expiresAt = now + env.SESSION_TTL_DAYS * 24 * 60 * 60 * 1000
const [session] = await db
.insert(authSessions)
.values({
userId,
tokenHash,
expiresAt: new Date(expiresAt),
createdAt: new Date(now),
})
.returning()
return {
token,
session,
}
}
async function findAuthenticatedUser(request) {
const token = getBearerToken(request)
if (!token) {
return null
}
const tokenHash = hashSessionToken(token)
const [session] = await db
.select()
.from(authSessions)
.where(eq(authSessions.tokenHash, tokenHash))
.limit(1)
if (!session || new Date(session.expiresAt).getTime() <= Date.now()) {
return null
}
const [user] = await db
.select()
.from(users)
.where(eq(users.id, session.userId))
.limit(1)
return user ?? null
}
export async function registerAuthRoutes(app) {
app.post('/api/auth/signup', async (request, reply) => {
const payload = signupSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '회원가입 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const { email, password, nickname } = payload.data
const normalizedEmail = email.toLowerCase()
const [existingUser] = await db
.select()
.from(users)
.where(eq(users.email, normalizedEmail))
.limit(1)
if (existingUser) {
return reply.code(409).send({
message: '이미 사용 중인 이메일입니다.',
})
}
const now = new Date()
const passwordHash = await hashPassword(password)
const [user] = await db
.insert(users)
.values({
email: normalizedEmail,
passwordHash,
nickname,
createdAt: now,
updatedAt: now,
})
.returning()
const { token } = await createSession(user.id)
return reply.code(201).send({
message: '회원가입이 완료되었습니다.',
token,
user: sanitizeUser(user),
})
})
app.post('/api/auth/login', async (request, reply) => {
const payload = loginSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '로그인 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const normalizedEmail = payload.data.email.toLowerCase()
const [user] = await db
.select()
.from(users)
.where(eq(users.email, normalizedEmail))
.limit(1)
if (!user) {
return reply.code(401).send({
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
})
}
const passwordMatches = await verifyPassword(payload.data.password, user.passwordHash)
if (!passwordMatches) {
return reply.code(401).send({
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
})
}
const { token } = await createSession(user.id)
return {
message: '로그인에 성공했습니다.',
token,
user: sanitizeUser(user),
}
})
app.get('/api/auth/me', async (request, reply) => {
const user = await findAuthenticatedUser(request)
if (!user) {
return reply.code(401).send({
message: '인증이 필요합니다.',
})
}
return {
user: sanitizeUser(user),
}
})
}

View File

@@ -2,16 +2,22 @@ import Fastify from 'fastify'
import cors from '@fastify/cors'
import { env } from './config.js'
import { sqlite } from './db/client.js'
import { ensureDatabaseSchema } from './db/init.js'
import { registerAuthRoutes } from './routes/auth.js'
const app = Fastify({
logger: true,
})
ensureDatabaseSchema()
await app.register(cors, {
origin: env.CORS_ORIGIN,
credentials: true,
})
await registerAuthRoutes(app)
app.get('/health', async () => {
const version = sqlite.prepare('select sqlite_version() as version').get()
@@ -26,11 +32,11 @@ app.get('/health', async () => {
})
app.get('/api/meta', async () => ({
auth: 'planned',
auth: 'active',
storage: 'sqlite',
orm: 'drizzle',
notes: [
'회원가입 로그인 API는 다음 단계에서 추가 예정',
'회원가입, 로그인, 현재 사용자 확인 API가 준비되어 있습니다.',
'플래너 저장 API는 로컬 저장 레이어 분리 이후 연결 예정',
],
}))