routes_auth.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { Hono } from 'hono'
  2. import type { Variables } from './app.tsx'
  3. import type { WithAuth } from './app.tsx'
  4. export function createAuthRoutes(withAuth: WithAuth) {
  5. const authRoutes = new Hono<{ Variables: Variables }>()
  6. // 登录状态检查
  7. authRoutes.get('/status', async (c) => {
  8. try {
  9. const auth = c.get('auth')
  10. const token = c.req.header('Authorization')?.replace('Bearer ', '')
  11. if (!token) {
  12. return c.json({ isValid: false }, 200)
  13. }
  14. const status = await auth.checkLoginStatus(token)
  15. return c.json(status)
  16. } catch (error) {
  17. console.error('登录状态检查失败:', error)
  18. return c.json({ isValid: false, error: '登录状态检查失败' }, 500)
  19. }
  20. })
  21. // 注册
  22. authRoutes.post('/register', async (c) => {
  23. try {
  24. const auth = c.get('auth')
  25. const { username, email, password } = await c.req.json()
  26. if (!username || !password) {
  27. return c.json({ error: '用户名和密码不能为空' }, 400)
  28. }
  29. try {
  30. await auth.createUser({ username, password, email })
  31. const result = await auth.authenticate(username, password)
  32. return c.json({
  33. message: '注册成功',
  34. user: result.user
  35. }, 201)
  36. } catch (authError) {
  37. return c.json({ error: '用户已存在或注册失败' }, 400)
  38. }
  39. } catch (error) {
  40. console.error('注册失败:', error)
  41. return c.json({ error: '注册失败' }, 500)
  42. }
  43. })
  44. // 登录
  45. authRoutes.post('/login', async (c) => {
  46. try {
  47. const auth = c.get('auth')
  48. const { username, password } = await c.req.json()
  49. if (!username || !password) {
  50. return c.json({ error: '用户名和密码不能为空' }, 400)
  51. }
  52. try {
  53. const result = await auth.authenticate(username, password)
  54. if (result.user) {
  55. const apiClient = c.get('apiClient')
  56. await apiClient.database.insert('login_history', {
  57. user_id: result.user.id,
  58. login_time: apiClient.database.fn.now(),
  59. ip_address: c.req.header('x-forwarded-for') || '未知',
  60. user_agent: c.req.header('user-agent') || '未知'
  61. })
  62. }
  63. return c.json({
  64. message: '登录成功',
  65. token: result.token,
  66. refreshToken: result.refreshToken,
  67. user: result.user
  68. })
  69. } catch (authError) {
  70. return c.json({ error: '用户名或密码错误' }, 401)
  71. }
  72. } catch (error) {
  73. console.error('登录失败:', error)
  74. return c.json({ error: '登录失败' }, 500)
  75. }
  76. })
  77. // 获取当前用户信息
  78. authRoutes.get('/me', withAuth, (c) => {
  79. const user = c.get('user')
  80. return c.json(user)
  81. })
  82. // 登出
  83. authRoutes.post('/logout', async (c) => {
  84. return c.json({ message: '登出成功' })
  85. })
  86. return authRoutes
  87. }