auth-middleware.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import { verifyJWT } from './auth-utils';
  3. import { findUserById } from './user-service';
  4. export interface AuthUser {
  5. id: string;
  6. email: string;
  7. username: string | null;
  8. isEmailVerified: boolean;
  9. credits: number;
  10. subscriptionCredits: number;
  11. subscriptionStatus: string | null;
  12. subscriptionPlan: string | null;
  13. subscriptionStartDate: Date | null;
  14. subscriptionEndDate: Date | null;
  15. }
  16. // 从请求中获取用户信息
  17. export async function getCurrentUser(request: NextRequest): Promise<AuthUser | null> {
  18. try {
  19. const token = request.cookies.get('auth-token')?.value;
  20. if (!token) {
  21. return null;
  22. }
  23. const payload = verifyJWT(token);
  24. if (!payload || !payload.userId) {
  25. return null;
  26. }
  27. const user = await findUserById(payload.userId);
  28. if (!user) {
  29. return null;
  30. }
  31. return {
  32. id: user.id,
  33. email: user.email,
  34. username: user.username,
  35. isEmailVerified: user.isEmailVerified,
  36. credits: user.credits,
  37. subscriptionCredits: user.subscriptionCredits,
  38. subscriptionStatus: user.subscriptionStatus,
  39. subscriptionPlan: user.subscriptionPlan,
  40. subscriptionStartDate: user.subscriptionStartDate,
  41. subscriptionEndDate: user.subscriptionEndDate,
  42. };
  43. } catch (error) {
  44. console.error('获取当前用户失败:', error);
  45. return null;
  46. }
  47. }
  48. // 认证中间件
  49. export async function requireAuth(request: NextRequest): Promise<{
  50. isAuthenticated: boolean;
  51. user?: AuthUser;
  52. response?: NextResponse;
  53. }> {
  54. const user = await getCurrentUser(request);
  55. if (!user) {
  56. return {
  57. isAuthenticated: false,
  58. response: NextResponse.json(
  59. { error: '请先登录' },
  60. { status: 401 }
  61. ),
  62. };
  63. }
  64. return {
  65. isAuthenticated: true,
  66. user,
  67. };
  68. }
  69. // 邮箱验证中间件
  70. export async function requireEmailVerified(request: NextRequest): Promise<{
  71. isVerified: boolean;
  72. user?: AuthUser;
  73. response?: NextResponse;
  74. }> {
  75. const authResult = await requireAuth(request);
  76. if (!authResult.isAuthenticated || !authResult.user) {
  77. return {
  78. isVerified: false,
  79. response: authResult.response,
  80. };
  81. }
  82. if (!authResult.user.isEmailVerified) {
  83. return {
  84. isVerified: false,
  85. user: authResult.user,
  86. response: NextResponse.json(
  87. { error: '请先验证您的邮箱地址' },
  88. { status: 403 }
  89. ),
  90. };
  91. }
  92. return {
  93. isVerified: true,
  94. user: authResult.user,
  95. };
  96. }