refresh.ts (1337B)
1 import { ERR_METHOD_NOT_ALLOWED, ERR_UNAUTHORIZED } from '@/lib/apierror' 2 import { getRefreshTokenCookieName } from '@/lib/env' 3 import { deleteSession, getSession, putSession } from '@/lib/security/session' 4 import { verifyToken } from '@/lib/security/token' 5 import { signAndSendToken } from '@/pages/api/auth/token' 6 import { nanoid } from 'nanoid' 7 import { NextApiRequest, NextApiResponse } from 'next' 8 9 export default async function handler ( 10 req: NextApiRequest, 11 res: NextApiResponse, 12 ) { 13 if (req.method !== 'POST') { 14 res.status(405).json(ERR_METHOD_NOT_ALLOWED) 15 return 16 } 17 18 const refreshToken = req.cookies[getRefreshTokenCookieName()] 19 if (refreshToken == null) { 20 res.status(401).json(ERR_UNAUTHORIZED) 21 return 22 } 23 24 const token = await verifyToken(refreshToken) 25 if (token == null) { 26 res.status(401).json(ERR_UNAUTHORIZED) 27 return 28 } 29 30 const { tid: oldTID, uid } = token as { tid: string, uid: number } 31 32 // 기존 세션이 없으면 유효하지 않은 세션 33 const session = await getSession(oldTID) 34 if (session == null) { 35 res.status(401).json(ERR_UNAUTHORIZED) 36 return 37 } 38 39 // 기존 세션 제거 40 await deleteSession(oldTID) 41 42 // 새로운 세션 생성 43 const tid = nanoid() 44 await putSession({ 45 ...session, 46 id: tid, 47 }) 48 49 await signAndSendToken(res, tid, uid) 50 }