auth.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import express from 'express';
  2. import {
  3. authCookieName,
  4. clearCookieOptions,
  5. cookieOptions,
  6. createSession,
  7. refreshSessionIfNeeded,
  8. validateCredentials,
  9. verifySession,
  10. } from '../libs/auth.js';
  11. const router = express.Router();
  12. router.post('/login', (req, res) => {
  13. const { username = '', password = '' } = req.body ?? {};
  14. if (!validateCredentials(String(username), String(password))) {
  15. return res.unauthorized('用户名或密码错误');
  16. }
  17. const token = createSession(username);
  18. res.cookie(authCookieName, token, cookieOptions());
  19. return res.sendSuccess({ username });
  20. });
  21. router.post('/logout', (req, res) => {
  22. res.clearCookie(authCookieName, clearCookieOptions());
  23. return res.sendSuccess();
  24. });
  25. router.get('/me', (req, res) => {
  26. const session = verifySession(req.cookies?.[authCookieName]);
  27. if (!session) {
  28. return res.unauthorized('请先登录');
  29. }
  30. refreshSessionIfNeeded(res, session);
  31. return res.sendSuccess({ username: session.username });
  32. });
  33. export default router;