feat(member): 회원 설정/헤더 상태 UI와 관리자 멤버 관리 추가
로그인 상태를 헤더에서 즉시 인지하고 계정 관리를 이어갈 수 있도록 사용자 설정과 관리자 멤버 관측 기능을 연결했다. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
48
server/api/auth/account.delete.js
Normal file
48
server/api/auth/account.delete.js
Normal file
@@ -0,0 +1,48 @@
|
||||
import bcrypt from 'bcrypt'
|
||||
import { createError, readBody } from 'h3'
|
||||
import { z } from 'zod'
|
||||
import { deleteMember, getUserByIdWithPassword } from '../../repositories/member-repository'
|
||||
import { clearMemberSession, requireMemberSession } from '../../utils/member-auth'
|
||||
|
||||
const deleteAccountSchema = z.object({
|
||||
password: z.string().min(1)
|
||||
})
|
||||
|
||||
/**
|
||||
* 회원 탈퇴 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ ok: true }>} 처리 결과
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
const parsedBody = deleteAccountSchema.safeParse(await readBody(event))
|
||||
|
||||
if (!parsedBody.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '탈퇴 요청 형식이 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const user = await getUserByIdWithPassword(session.userId)
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '회원 정보를 찾을 수 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(parsedBody.data.password, user.passwordHash)
|
||||
if (!isPasswordValid) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '비밀번호가 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
await deleteMember(session.userId)
|
||||
clearMemberSession(event)
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
31
server/api/auth/check-username.get.js
Normal file
31
server/api/auth/check-username.get.js
Normal file
@@ -0,0 +1,31 @@
|
||||
import { createError } from 'h3'
|
||||
import { isUsernameTaken } from '../../repositories/member-repository'
|
||||
import { requireMemberSession } from '../../utils/member-auth'
|
||||
|
||||
/**
|
||||
* 사용자명 중복 확인 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ available: boolean }>} 사용 가능 여부
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
const rawUsername = getQuery(event).username
|
||||
const username = typeof rawUsername === 'string' ? rawUsername.trim() : ''
|
||||
|
||||
if (!username) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '닉네임을 입력해 주세요.'
|
||||
})
|
||||
}
|
||||
|
||||
const taken = await isUsernameTaken({
|
||||
username,
|
||||
excludeUserId: session.userId
|
||||
})
|
||||
|
||||
return {
|
||||
available: !taken
|
||||
}
|
||||
})
|
||||
|
||||
50
server/api/auth/login.post.js
Normal file
50
server/api/auth/login.post.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import bcrypt from 'bcrypt'
|
||||
import { z } from 'zod'
|
||||
import { createError, getRequestIP, readBody } from 'h3'
|
||||
import { getUserByEmail, touchUserActivity } from '../../repositories/member-repository'
|
||||
import { setMemberSession } from '../../utils/member-auth'
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().trim().email(),
|
||||
password: z.string().min(1)
|
||||
})
|
||||
|
||||
/**
|
||||
* 회원 로그인 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ id: string, username: string, 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 user = await getUserByEmail(body.email)
|
||||
|
||||
if (!user || !(await bcrypt.compare(body.password, user.passwordHash))) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '이메일 또는 비밀번호가 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
setMemberSession(event, { userId: user.id, email: user.email })
|
||||
await touchUserActivity({
|
||||
userId: user.id,
|
||||
ip: String(getRequestIP(event) || '')
|
||||
})
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatarUrl || ''
|
||||
}
|
||||
})
|
||||
|
||||
12
server/api/auth/logout.post.js
Normal file
12
server/api/auth/logout.post.js
Normal file
@@ -0,0 +1,12 @@
|
||||
import { clearMemberSession } from '../../utils/member-auth'
|
||||
|
||||
/**
|
||||
* 회원 로그아웃 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {{ ok: true }} 처리 결과
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
clearMemberSession(event)
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
34
server/api/auth/me.get.js
Normal file
34
server/api/auth/me.get.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import { getUserById, touchUserActivity } from '../../repositories/member-repository'
|
||||
import { requireMemberSession } from '../../utils/member-auth'
|
||||
import { getRequestIP } from 'h3'
|
||||
|
||||
/**
|
||||
* 회원 세션 조회 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ id: string, username: string, email: string, avatarUrl: string }>} 회원 정보
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
await touchUserActivity({
|
||||
userId: session.userId,
|
||||
ip: String(getRequestIP(event) || '')
|
||||
})
|
||||
const user = await getUserById(session.userId)
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
id: session.userId,
|
||||
username: '',
|
||||
email: session.email,
|
||||
avatarUrl: ''
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatarUrl || ''
|
||||
}
|
||||
})
|
||||
|
||||
52
server/api/auth/password.put.js
Normal file
52
server/api/auth/password.put.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import bcrypt from 'bcrypt'
|
||||
import { createError, readBody } from 'h3'
|
||||
import { z } from 'zod'
|
||||
import { getUserByIdWithPassword, updateMemberPassword } from '../../repositories/member-repository'
|
||||
import { requireMemberSession } from '../../utils/member-auth'
|
||||
|
||||
const updatePasswordSchema = z.object({
|
||||
currentPassword: z.string().min(1),
|
||||
nextPassword: z.string().min(8).max(32)
|
||||
})
|
||||
|
||||
/**
|
||||
* 회원 비밀번호 변경 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ ok: true }>} 변경 결과
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
const parsedBody = updatePasswordSchema.safeParse(await readBody(event))
|
||||
|
||||
if (!parsedBody.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '비밀번호 변경 요청 형식이 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const user = await getUserByIdWithPassword(session.userId)
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '회원 정보를 찾을 수 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const isCurrentValid = await bcrypt.compare(parsedBody.data.currentPassword, user.passwordHash)
|
||||
if (!isCurrentValid) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '현재 비밀번호가 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const nextHash = await bcrypt.hash(parsedBody.data.nextPassword, 12)
|
||||
await updateMemberPassword({
|
||||
userId: session.userId,
|
||||
passwordHash: nextHash
|
||||
})
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
28
server/api/auth/profile.get.js
Normal file
28
server/api/auth/profile.get.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import { getUserById } from '../../repositories/member-repository'
|
||||
import { requireMemberSession } from '../../utils/member-auth'
|
||||
import { createError } from 'h3'
|
||||
|
||||
/**
|
||||
* 회원 프로필 조회 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ id: string, email: string, username: string, avatarUrl: string }>} 회원 프로필
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
const user = await getUserById(session.userId)
|
||||
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '회원 정보를 찾을 수 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
avatarUrl: user.avatarUrl || ''
|
||||
}
|
||||
})
|
||||
|
||||
67
server/api/auth/profile.put.js
Normal file
67
server/api/auth/profile.put.js
Normal file
@@ -0,0 +1,67 @@
|
||||
import { createError, readBody } from 'h3'
|
||||
import { z } from 'zod'
|
||||
import { getUserById, isUsernameTaken, updateMemberProfile } from '../../repositories/member-repository'
|
||||
import { requireMemberSession } from '../../utils/member-auth'
|
||||
|
||||
const updateProfileSchema = z.object({
|
||||
username: z.string().trim().min(1).max(30),
|
||||
avatarUrl: z.string().trim().max(500).optional().default('')
|
||||
})
|
||||
|
||||
/**
|
||||
* 회원 프로필 수정 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ id: string, email: string, username: string, avatarUrl: string }>} 수정된 회원 프로필
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
const parsedBody = updateProfileSchema.safeParse(await readBody(event))
|
||||
|
||||
if (!parsedBody.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '프로필 요청 형식이 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const taken = await isUsernameTaken({
|
||||
username: parsedBody.data.username,
|
||||
excludeUserId: session.userId
|
||||
})
|
||||
|
||||
if (taken) {
|
||||
throw createError({
|
||||
statusCode: 409,
|
||||
message: '이미 사용 중인 닉네임입니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const updated = await updateMemberProfile({
|
||||
userId: session.userId,
|
||||
username: parsedBody.data.username,
|
||||
avatarUrl: parsedBody.data.avatarUrl
|
||||
})
|
||||
|
||||
if (!updated) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '회원 정보를 찾을 수 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const user = await getUserById(session.userId)
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '회원 정보를 찾을 수 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
avatarUrl: user.avatarUrl || ''
|
||||
}
|
||||
})
|
||||
|
||||
69
server/api/auth/signup.post.js
Normal file
69
server/api/auth/signup.post.js
Normal file
@@ -0,0 +1,69 @@
|
||||
import bcrypt from 'bcrypt'
|
||||
import { z } from 'zod'
|
||||
import { createError, getRequestIP, readBody } from 'h3'
|
||||
import { createUser, getUserByEmail, isUsernameTaken, touchUserActivity } from '../../repositories/member-repository'
|
||||
import { setMemberSession } from '../../utils/member-auth'
|
||||
|
||||
const signupSchema = z.object({
|
||||
username: z.string().trim().min(1),
|
||||
email: z.string().trim().email(),
|
||||
password: z.string().min(8).max(32)
|
||||
})
|
||||
|
||||
/**
|
||||
* 회원 가입 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ id: string, username: string, email: string }>} 회원 정보
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const parsedBody = signupSchema.safeParse(await readBody(event))
|
||||
|
||||
if (!parsedBody.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '회원가입 요청 형식이 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const body = parsedBody.data
|
||||
const usernameTaken = await isUsernameTaken({
|
||||
username: body.username
|
||||
})
|
||||
|
||||
if (usernameTaken) {
|
||||
throw createError({
|
||||
statusCode: 409,
|
||||
message: '이미 사용 중인 닉네임입니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const existingUser = await getUserByEmail(body.email)
|
||||
|
||||
if (existingUser) {
|
||||
throw createError({
|
||||
statusCode: 409,
|
||||
message: '이미 사용 중인 이메일입니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(body.password, 12)
|
||||
const created = await createUser({
|
||||
username: body.username,
|
||||
email: body.email,
|
||||
passwordHash
|
||||
})
|
||||
|
||||
setMemberSession(event, { userId: created.id, email: created.email })
|
||||
await touchUserActivity({
|
||||
userId: created.id,
|
||||
ip: String(getRequestIP(event) || '')
|
||||
})
|
||||
|
||||
return {
|
||||
id: created.id,
|
||||
username: created.username,
|
||||
email: created.email,
|
||||
avatarUrl: created.avatarUrl || ''
|
||||
}
|
||||
})
|
||||
|
||||
16
server/api/posts/[slug]/comments.get.js
Normal file
16
server/api/posts/[slug]/comments.get.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { listPostCommentsBySlug } from '../../../repositories/comment-repository'
|
||||
|
||||
/**
|
||||
* 게시물 댓글 목록 조회 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ comments: Array<Object> }>} 댓글 목록
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const slug = String(getRouterParam(event, 'slug') || '')
|
||||
const comments = await listPostCommentsBySlug(slug)
|
||||
|
||||
return {
|
||||
comments
|
||||
}
|
||||
})
|
||||
|
||||
44
server/api/posts/[slug]/comments.post.js
Normal file
44
server/api/posts/[slug]/comments.post.js
Normal file
@@ -0,0 +1,44 @@
|
||||
import { createError, getRequestIP, readBody } from 'h3'
|
||||
import { z } from 'zod'
|
||||
import { createComment } from '../../../repositories/comment-repository'
|
||||
import { touchUserActivity } from '../../../repositories/member-repository'
|
||||
import { requireMemberSession } from '../../../utils/member-auth'
|
||||
|
||||
const createCommentSchema = z.object({
|
||||
body: z.string().trim().min(1).max(5000),
|
||||
parentId: z.string().uuid().optional().nullable()
|
||||
})
|
||||
|
||||
/**
|
||||
* 게시물 댓글 생성 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<{ comment: Object }>} 생성 댓글
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = requireMemberSession(event)
|
||||
const slug = String(getRouterParam(event, 'slug') || '')
|
||||
const parsedBody = createCommentSchema.safeParse(await readBody(event))
|
||||
|
||||
if (!parsedBody.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '댓글 요청 형식이 올바르지 않습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const comment = await createComment({
|
||||
slug,
|
||||
userId: session.userId,
|
||||
body: parsedBody.data.body,
|
||||
parentId: parsedBody.data.parentId || null
|
||||
})
|
||||
await touchUserActivity({
|
||||
userId: session.userId,
|
||||
ip: String(getRequestIP(event) || '')
|
||||
})
|
||||
|
||||
return {
|
||||
comment
|
||||
}
|
||||
})
|
||||
|
||||
196
server/repositories/comment-repository.js
Normal file
196
server/repositories/comment-repository.js
Normal file
@@ -0,0 +1,196 @@
|
||||
import { createError } from 'h3'
|
||||
import { getPostgresClient } from './postgres-client'
|
||||
|
||||
/**
|
||||
* @typedef {Object} PostComment
|
||||
* @property {string} id - 댓글 ID
|
||||
* @property {string} postId - 게시물 ID
|
||||
* @property {string | null} parentId - 부모 댓글 ID
|
||||
* @property {string} body - 댓글 내용
|
||||
* @property {string} status - 댓글 상태
|
||||
* @property {string} createdAt - 생성 시각
|
||||
* @property {string} updatedAt - 수정 시각
|
||||
* @property {{ id: string, username: string }} user - 작성자 정보
|
||||
*/
|
||||
|
||||
/**
|
||||
* DB 클라이언트 조회 (선택)
|
||||
* @returns {ReturnType<typeof import('postgres').default> | null} postgres sql 클라이언트
|
||||
*/
|
||||
const getSql = () => getPostgresClient()
|
||||
|
||||
/**
|
||||
* 게시물 ID 조회
|
||||
* @param {ReturnType<typeof import('postgres').default>} sql - postgres 클라이언트
|
||||
* @param {string} slug - 게시물 슬러그
|
||||
* @returns {Promise<string | null>} 게시물 ID
|
||||
*/
|
||||
const findPublishedPostIdBySlug = async (sql, slug) => {
|
||||
const rows = await sql`
|
||||
SELECT id
|
||||
FROM posts
|
||||
WHERE slug = ${slug}
|
||||
AND status = 'published'
|
||||
AND (
|
||||
published_at IS NULL
|
||||
OR published_at <= now()
|
||||
)
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
return rows?.[0]?.id || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시물 댓글 조회
|
||||
* @param {string} slug - 게시물 슬러그
|
||||
* @returns {Promise<Array<PostComment>>} 댓글 목록
|
||||
*/
|
||||
export const listPostCommentsBySlug = async (slug) => {
|
||||
const sql = getSql()
|
||||
|
||||
if (!sql) {
|
||||
return []
|
||||
}
|
||||
|
||||
const postId = await findPublishedPostIdBySlug(sql, slug)
|
||||
if (!postId) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: '게시물을 찾을 수 없습니다'
|
||||
})
|
||||
}
|
||||
|
||||
const rows = await sql`
|
||||
SELECT
|
||||
comments.id,
|
||||
comments.post_id AS "postId",
|
||||
comments.parent_id AS "parentId",
|
||||
comments.body,
|
||||
comments.status,
|
||||
comments.created_at AS "createdAt",
|
||||
comments.updated_at AS "updatedAt",
|
||||
users.id AS "userId",
|
||||
users.username AS "username"
|
||||
FROM comments
|
||||
INNER JOIN users ON users.id = comments.user_id
|
||||
WHERE comments.post_id = ${postId}
|
||||
AND comments.status = 'published'
|
||||
ORDER BY comments.created_at ASC
|
||||
`
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
postId: row.postId,
|
||||
parentId: row.parentId || null,
|
||||
body: row.body,
|
||||
status: row.status,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
user: {
|
||||
id: row.userId,
|
||||
username: row.username
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글 생성
|
||||
* @param {{ slug: string, userId: string, body: string, parentId?: string | null }} input - 댓글 입력값
|
||||
* @returns {Promise<PostComment>} 생성된 댓글
|
||||
*/
|
||||
export const createComment = async (input) => {
|
||||
const sql = getSql()
|
||||
|
||||
if (!sql) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '데이터베이스 설정이 필요합니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const postId = await findPublishedPostIdBySlug(sql, input.slug)
|
||||
if (!postId) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: '게시물을 찾을 수 없습니다'
|
||||
})
|
||||
}
|
||||
|
||||
let parentId = input.parentId || null
|
||||
|
||||
if (parentId) {
|
||||
const parentRows = await sql`
|
||||
SELECT id, post_id AS "postId", parent_id AS "parentId", status
|
||||
FROM comments
|
||||
WHERE id = ${parentId}
|
||||
LIMIT 1
|
||||
`
|
||||
const parent = parentRows?.[0]
|
||||
|
||||
if (!parent || parent.postId !== postId || parent.status !== 'published') {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '유효하지 않은 부모 댓글입니다.'
|
||||
})
|
||||
}
|
||||
|
||||
if (parent.parentId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '대댓글에는 추가 답글을 달 수 없습니다.'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const rows = await sql`
|
||||
INSERT INTO comments (post_id, user_id, parent_id, body, status)
|
||||
VALUES (${postId}, ${input.userId}, ${parentId}, ${input.body}, 'published')
|
||||
RETURNING
|
||||
id,
|
||||
post_id AS "postId",
|
||||
parent_id AS "parentId",
|
||||
body,
|
||||
status,
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
`
|
||||
|
||||
const created = rows?.[0]
|
||||
if (!created) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '댓글 생성에 실패했습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
const userRows = await sql`
|
||||
SELECT id, username
|
||||
FROM users
|
||||
WHERE id = ${input.userId}
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
const user = userRows?.[0]
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '회원 정보를 찾을 수 없습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
id: created.id,
|
||||
postId: created.postId,
|
||||
parentId: created.parentId || null,
|
||||
body: created.body,
|
||||
status: created.status,
|
||||
createdAt: created.createdAt.toISOString(),
|
||||
updatedAt: created.updatedAt.toISOString(),
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
284
server/repositories/member-repository.js
Normal file
284
server/repositories/member-repository.js
Normal file
@@ -0,0 +1,284 @@
|
||||
import { createError } from 'h3'
|
||||
import { getPostgresClient } from './postgres-client'
|
||||
|
||||
/**
|
||||
* @typedef {Object} MemberUser
|
||||
* @property {string} id - 사용자 ID
|
||||
* @property {string} username - 사용자명
|
||||
* @property {string} email - 이메일
|
||||
* @property {string} passwordHash - 비밀번호 해시
|
||||
* @property {string} avatarUrl - 아바타 URL
|
||||
* @property {string} createdAt - 생성 시각(ISO)
|
||||
* @property {string} updatedAt - 수정 시각(ISO)
|
||||
* @property {string | null} lastSeenAt - 최근 접속 시각(ISO)
|
||||
* @property {string} lastSeenIp - 최근 접속 IP
|
||||
*/
|
||||
|
||||
/**
|
||||
* DB 클라이언트 조회 (필수)
|
||||
* @returns {ReturnType<typeof import('postgres').default>} postgres sql 클라이언트
|
||||
*/
|
||||
const requireSql = () => {
|
||||
const sql = getPostgresClient()
|
||||
if (!sql) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '데이터베이스 설정이 필요합니다.'
|
||||
})
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
/**
|
||||
* 이메일로 회원 조회
|
||||
* @param {string} email - 이메일
|
||||
* @returns {Promise<MemberUser | null>} 회원
|
||||
*/
|
||||
export const getUserByEmail = async (email) => {
|
||||
const sql = requireSql()
|
||||
const rows = await sql`
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
password_hash AS "passwordHash",
|
||||
avatar_url AS "avatarUrl",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
last_seen_at AS "lastSeenAt",
|
||||
last_seen_ip AS "lastSeenIp"
|
||||
FROM users
|
||||
WHERE email = ${email}
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
return rows?.[0] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 회원 조회
|
||||
* @param {string} id - 사용자 ID
|
||||
* @returns {Promise<Omit<MemberUser, 'passwordHash'> | null>} 회원
|
||||
*/
|
||||
export const getUserById = async (id) => {
|
||||
const sql = requireSql()
|
||||
const rows = await sql`
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
avatar_url AS "avatarUrl",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
last_seen_at AS "lastSeenAt",
|
||||
last_seen_ip AS "lastSeenIp"
|
||||
FROM users
|
||||
WHERE id = ${id}
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
return rows?.[0] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 회원 조회(비밀번호 포함)
|
||||
* @param {string} id - 사용자 ID
|
||||
* @returns {Promise<MemberUser | null>} 회원
|
||||
*/
|
||||
export const getUserByIdWithPassword = async (id) => {
|
||||
const sql = requireSql()
|
||||
const rows = await sql`
|
||||
SELECT
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
password_hash AS "passwordHash",
|
||||
avatar_url AS "avatarUrl",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
last_seen_at AS "lastSeenAt",
|
||||
last_seen_ip AS "lastSeenIp"
|
||||
FROM users
|
||||
WHERE id = ${id}
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
return rows?.[0] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 생성
|
||||
* @param {{ username: string, email: string, passwordHash: string }} input - 입력
|
||||
* @returns {Promise<Omit<MemberUser, 'passwordHash'>>} 생성된 회원
|
||||
*/
|
||||
export const createUser = async (input) => {
|
||||
const sql = requireSql()
|
||||
|
||||
const rows = await sql`
|
||||
INSERT INTO users (username, email, password_hash, avatar_url)
|
||||
VALUES (${input.username}, ${input.email}, ${input.passwordHash}, '')
|
||||
RETURNING
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
avatar_url AS "avatarUrl",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
last_seen_at AS "lastSeenAt",
|
||||
last_seen_ip AS "lastSeenIp"
|
||||
`
|
||||
|
||||
const created = rows?.[0]
|
||||
if (!created) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '회원 생성에 실패했습니다.'
|
||||
})
|
||||
}
|
||||
|
||||
return created
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 최근 활동 정보를 기록한다.
|
||||
* @param {{ userId: string, ip: string }} input - 사용자 ID와 접속 IP
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export const touchUserActivity = async (input) => {
|
||||
const sql = requireSql()
|
||||
await sql`
|
||||
UPDATE users
|
||||
SET
|
||||
last_seen_at = now(),
|
||||
last_seen_ip = ${input.ip},
|
||||
updated_at = now()
|
||||
WHERE id = ${input.userId}
|
||||
`
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 프로필 수정
|
||||
* @param {{ userId: string, username: string, avatarUrl: string }} input - 수정 값
|
||||
* @returns {Promise<Omit<MemberUser, 'passwordHash'> | null>} 수정된 회원
|
||||
*/
|
||||
export const updateMemberProfile = async (input) => {
|
||||
const sql = requireSql()
|
||||
const rows = await sql`
|
||||
UPDATE users
|
||||
SET
|
||||
username = ${input.username},
|
||||
avatar_url = ${input.avatarUrl},
|
||||
updated_at = now()
|
||||
WHERE id = ${input.userId}
|
||||
RETURNING
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
avatar_url AS "avatarUrl",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
last_seen_at AS "lastSeenAt",
|
||||
last_seen_ip AS "lastSeenIp"
|
||||
`
|
||||
|
||||
return rows?.[0] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 비밀번호 변경
|
||||
* @param {{ userId: string, passwordHash: string }} input - 수정 값
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export const updateMemberPassword = async (input) => {
|
||||
const sql = requireSql()
|
||||
await sql`
|
||||
UPDATE users
|
||||
SET
|
||||
password_hash = ${input.passwordHash},
|
||||
updated_at = now()
|
||||
WHERE id = ${input.userId}
|
||||
`
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 탈퇴
|
||||
* @param {string} userId - 사용자 ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export const deleteMember = async (userId) => {
|
||||
const sql = requireSql()
|
||||
await sql`
|
||||
DELETE FROM users
|
||||
WHERE id = ${userId}
|
||||
`
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자명 중복 확인
|
||||
* @param {{ username: string, excludeUserId?: string }} input - 사용자명과 제외 사용자 ID
|
||||
* @returns {Promise<boolean>} 중복 여부
|
||||
*/
|
||||
export const isUsernameTaken = async (input) => {
|
||||
const sql = requireSql()
|
||||
const rows = input.excludeUserId
|
||||
? await sql`
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE lower(username) = lower(${input.username})
|
||||
AND id <> ${input.excludeUserId}
|
||||
LIMIT 1
|
||||
`
|
||||
: await sql`
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE lower(username) = lower(${input.username})
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
return Boolean(rows?.[0])
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자용 회원 목록 조회(댓글 활동 포함)
|
||||
* @returns {Promise<Array<{ id: string, username: string, email: string, avatarUrl: string, createdAt: string, updatedAt: string, lastSeenAt: string | null, lastSeenIp: string, commentCount: number, activityStatus: string }>>} 회원 목록
|
||||
*/
|
||||
export const listMembersForAdmin = async () => {
|
||||
const sql = requireSql()
|
||||
const rows = await sql`
|
||||
SELECT
|
||||
users.id,
|
||||
users.username,
|
||||
users.email,
|
||||
users.avatar_url AS "avatarUrl",
|
||||
users.created_at AS "createdAt",
|
||||
users.updated_at AS "updatedAt",
|
||||
users.last_seen_at AS "lastSeenAt",
|
||||
users.last_seen_ip AS "lastSeenIp",
|
||||
COALESCE(count(comments.id), 0)::int AS "commentCount"
|
||||
FROM users
|
||||
LEFT JOIN comments ON comments.user_id = users.id AND comments.status = 'published'
|
||||
GROUP BY users.id
|
||||
ORDER BY users.created_at DESC
|
||||
`
|
||||
|
||||
return rows.map((row) => {
|
||||
const lastSeenAt = row.lastSeenAt ? row.lastSeenAt.toISOString() : null
|
||||
const isActive = row.lastSeenAt
|
||||
? Date.now() - new Date(row.lastSeenAt).getTime() <= 1000 * 60 * 60 * 24 * 30
|
||||
: false
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
email: row.email,
|
||||
avatarUrl: row.avatarUrl || '',
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
lastSeenAt,
|
||||
lastSeenIp: row.lastSeenIp || '',
|
||||
commentCount: Number(row.commentCount || 0),
|
||||
activityStatus: isActive ? '활성' : '비활성'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
13
server/routes/admin/api/members.get.js
Normal file
13
server/routes/admin/api/members.get.js
Normal file
@@ -0,0 +1,13 @@
|
||||
import { requireAdminSession } from '../../../utils/admin-auth'
|
||||
import { listMembersForAdmin } from '../../../repositories/member-repository'
|
||||
|
||||
/**
|
||||
* 관리자 회원 목록 조회 API
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {Promise<Array<Object>>} 회원 목록
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
requireAdminSession(event)
|
||||
return listMembersForAdmin()
|
||||
})
|
||||
|
||||
152
server/utils/member-auth.js
Normal file
152
server/utils/member-auth.js
Normal file
@@ -0,0 +1,152 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto'
|
||||
import { createError, deleteCookie, getCookie, setCookie } from 'h3'
|
||||
|
||||
const memberSessionCookieName = 'sori_member_session'
|
||||
const sessionMaxAge = 60 * 60 * 24 * 14
|
||||
|
||||
/**
|
||||
* 회원 세션 서명 비밀값 조회
|
||||
* @returns {string} 세션 서명 비밀값
|
||||
*/
|
||||
const getSessionSecret = () => {
|
||||
const config = useRuntimeConfig()
|
||||
const fallbackSecret = String(config.adminPassword || '')
|
||||
const sessionSecret = String(config.memberSessionSecret || '').trim() || fallbackSecret
|
||||
|
||||
if (!sessionSecret) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '회원 세션 비밀값 환경 변수가 없습니다. (MEMBER_SESSION_SECRET 또는 ADMIN_PASSWORD)'
|
||||
})
|
||||
}
|
||||
|
||||
return sessionSecret
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 안전 비교
|
||||
* @param {string} left - 비교 문자열
|
||||
* @param {string} right - 비교 대상 문자열
|
||||
* @returns {boolean} 일치 여부
|
||||
*/
|
||||
const safeCompare = (left, right) => {
|
||||
const leftBuffer = Buffer.from(left)
|
||||
const rightBuffer = Buffer.from(right)
|
||||
|
||||
if (leftBuffer.length !== rightBuffer.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
return timingSafeEqual(leftBuffer, rightBuffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* 세션 페이로드 서명
|
||||
* @param {string} payload - 인코딩된 세션 페이로드
|
||||
* @returns {string} 세션 서명
|
||||
*/
|
||||
const signPayload = (payload) => createHmac('sha256', getSessionSecret())
|
||||
.update(payload)
|
||||
.digest('base64url')
|
||||
|
||||
/**
|
||||
* 회원 세션 토큰 생성
|
||||
* @param {{ userId: string, email: string }} user - 회원 정보
|
||||
* @returns {string} 세션 토큰
|
||||
*/
|
||||
export const createMemberSessionToken = (user) => {
|
||||
const payload = Buffer.from(JSON.stringify({
|
||||
userId: user.userId,
|
||||
email: user.email,
|
||||
expiresAt: Date.now() + sessionMaxAge * 1000
|
||||
})).toString('base64url')
|
||||
|
||||
return `${payload}.${signPayload(payload)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 세션 토큰 검증
|
||||
* @param {string | undefined} token - 세션 토큰
|
||||
* @returns {{ userId: string, email: string } | null} 세션 정보
|
||||
*/
|
||||
export const verifyMemberSessionToken = (token) => {
|
||||
if (!token) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [payload, signature] = token.split('.')
|
||||
|
||||
if (!payload || !signature || !safeCompare(signature, signPayload(payload))) {
|
||||
return null
|
||||
}
|
||||
|
||||
let session = null
|
||||
|
||||
try {
|
||||
session = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!session.userId || !session.email || !session.expiresAt || session.expiresAt < Date.now()) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
userId: session.userId,
|
||||
email: session.email
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 세션 쿠키 설정
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @param {{ userId: string, email: string }} user - 회원 정보
|
||||
* @returns {void}
|
||||
*/
|
||||
export const setMemberSession = (event, user) => {
|
||||
setCookie(event, memberSessionCookieName, createMemberSessionToken(user), {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
path: '/',
|
||||
maxAge: sessionMaxAge
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 세션 쿠키 삭제
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {void}
|
||||
*/
|
||||
export const clearMemberSession = (event) => {
|
||||
deleteCookie(event, memberSessionCookieName, {
|
||||
path: '/'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 세션 조회
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {{ userId: string, email: string } | null} 세션 정보
|
||||
*/
|
||||
export const getMemberSession = (event) => verifyMemberSessionToken(getCookie(event, memberSessionCookieName))
|
||||
|
||||
/**
|
||||
* 회원 세션 필수 확인
|
||||
* @param {import('h3').H3Event} event - 요청 이벤트
|
||||
* @returns {{ userId: string, email: string }} 세션 정보
|
||||
*/
|
||||
export const requireMemberSession = (event) => {
|
||||
const session = getMemberSession(event)
|
||||
|
||||
if (!session) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '로그인이 필요합니다.'
|
||||
})
|
||||
}
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user