Files
sori.studio/server/routes/admin/api/auth/login.post.js
zenn de767095ba v1.10.88 품질·보안 개선과 미디어 카탈로그 database 전환을 반영한다.
세션·로그인 제한, ZIP/업로드 스트리밍, CSP 최소 강제와 Report-Only, Playwright 격리 검증을 추가하고 미디어 목록을 reconcile 후 database 모드로 고정한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-22 11:05:40 +09:00

117 lines
3.5 KiB
JavaScript

import { z } from 'zod'
import { createError, readBody } from 'h3'
import bcrypt from 'bcrypt'
import { safeCompare, setAdminSession } from '../../../../utils/admin-auth'
import { getAdminUserByEmail, getMemberBootstrapState, touchUserActivity, upsertBootstrapOwner } from '../../../../repositories/member-repository'
import { setMemberSession } from '../../../../utils/member-auth'
import { getRuntimeEnvValue } from '../../../../utils/runtime-env'
import { getClientIp } from '../../../../utils/request-ip'
import {
assertLoginAttemptAllowed,
clearLoginAccountFailures,
recordLoginFailure
} from '../../../../utils/login-attempt-limit'
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1)
})
/**
* 이메일에서 최초 관리자 닉네임을 만든다.
* @param {string} email - 관리자 이메일
* @returns {string} 닉네임
*/
const createBootstrapUsername = (email) => {
const localPart = String(email).split('@')[0] || 'admin'
return localPart.replace(/[^a-zA-Z0-9._-]/g, '').trim() || 'admin'
}
/**
* 운영 환경 변수 기반 최초 관리자 계정을 생성한다.
* @param {{ email: string, password: string }} credentials - 로그인 입력값
* @returns {Promise<import('../../../../repositories/member-repository').MemberUser | null>} 생성된 관리자
*/
const createBootstrapAdminUser = async (credentials) => {
const adminEmail = getRuntimeEnvValue('ADMIN_EMAIL', 'adminEmail').trim().toLowerCase()
const adminPassword = getRuntimeEnvValue('ADMIN_PASSWORD', 'adminPassword')
if (!adminEmail || !adminPassword || credentials.email.trim().toLowerCase() !== adminEmail || !safeCompare(credentials.password, adminPassword)) {
return null
}
const bootstrap = await getMemberBootstrapState()
if (!bootstrap.needsAdminSetup) {
return null
}
const passwordHash = await bcrypt.hash(credentials.password, 12)
return upsertBootstrapOwner({
username: createBootstrapUsername(adminEmail),
email: adminEmail,
passwordHash
})
}
/**
* 관리자 로그인 API
* @param {import('h3').H3Event} event - 요청 이벤트
* @returns {Promise<{ email: string }>} 관리자 세션 정보
*/
export default defineEventHandler(async (event) => {
const parsedBody = loginSchema.safeParse(await readBody(event))
if (!parsedBody.success) {
throw createError({
statusCode: 400,
message: '로그인 요청 형식이 올바르지 않습니다.'
})
}
const body = parsedBody.data
const emailNorm = body.email.trim().toLowerCase()
const ip = getClientIp(event)
const attempt = {
scope: 'admin',
email: emailNorm,
ip
}
assertLoginAttemptAllowed(event, attempt)
const adminUser = await getAdminUserByEmail(body.email) || await createBootstrapAdminUser(body)
const passwordMatched = adminUser
? await bcrypt.compare(body.password, adminUser.passwordHash)
: false
if (!adminUser || !passwordMatched) {
recordLoginFailure(attempt)
throw createError({
statusCode: 401,
message: '이메일 또는 비밀번호가 올바르지 않습니다.'
})
}
clearLoginAccountFailures(attempt)
setAdminSession(event, {
userId: adminUser.id,
email: adminUser.email,
sessionVersion: adminUser.sessionVersion
})
setMemberSession(event, {
userId: adminUser.id,
email: adminUser.email,
sessionVersion: adminUser.sessionVersion
})
await touchUserActivity({
userId: adminUser.id,
ip
})
return {
userId: adminUser.id,
email: adminUser.email,
username: adminUser.username
}
})