import express from 'express'; import { authCookieName, clearCookieOptions, cookieOptions, createSession, refreshSessionIfNeeded, validateCredentials, verifySession, } from '../libs/auth.js'; const router = express.Router(); router.post('/login', (req, res) => { const { username = '', password = '' } = req.body ?? {}; if (!validateCredentials(String(username), String(password))) { return res.unauthorized('用户名或密码错误'); } const token = createSession(username); res.cookie(authCookieName, token, cookieOptions()); return res.sendSuccess({ username }); }); router.post('/logout', (req, res) => { res.clearCookie(authCookieName, clearCookieOptions()); return res.sendSuccess(); }); router.get('/me', (req, res) => { const session = verifySession(req.cookies?.[authCookieName]); if (!session) { return res.unauthorized('请先登录'); } refreshSessionIfNeeded(res, session); return res.sendSuccess({ username: session.username }); }); export default router;