관리자 최초 로그인 보강
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import { z } from 'zod'
|
||||
import { createError, getRequestIP, readBody } from 'h3'
|
||||
import bcrypt from 'bcrypt'
|
||||
import { setAdminSession } from '../../../../utils/admin-auth'
|
||||
import { getAdminUserByEmail, touchUserActivity } from '../../../../repositories/member-repository'
|
||||
import { safeCompare, setAdminSession } from '../../../../utils/admin-auth'
|
||||
import { createUser, getAdminUserByEmail, getMemberBootstrapState, touchUserActivity } from '../../../../repositories/member-repository'
|
||||
import { setMemberSession } from '../../../../utils/member-auth'
|
||||
|
||||
const loginSchema = z.object({
|
||||
@@ -10,6 +10,48 @@ const loginSchema = z.object({
|
||||
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 config = useRuntimeConfig()
|
||||
const adminEmail = String(config.adminEmail || '').trim().toLowerCase()
|
||||
const adminPassword = String(config.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)
|
||||
const created = await createUser({
|
||||
username: createBootstrapUsername(adminEmail),
|
||||
email: adminEmail,
|
||||
passwordHash
|
||||
})
|
||||
|
||||
return {
|
||||
...created,
|
||||
passwordHash
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 로그인 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
@@ -27,7 +69,7 @@ export default defineEventHandler(async (event) => {
|
||||
|
||||
const body = parsedBody.data
|
||||
|
||||
const adminUser = await getAdminUserByEmail(body.email)
|
||||
const adminUser = await getAdminUserByEmail(body.email) || await createBootstrapAdminUser(body)
|
||||
const passwordMatched = adminUser
|
||||
? await bcrypt.compare(body.password, adminUser.passwordHash)
|
||||
: false
|
||||
|
||||
Reference in New Issue
Block a user