auth.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. export type UserRole = "stu" | "teacher";
  2. export interface User {
  3. id: string;
  4. username: string;
  5. role: UserRole;
  6. name: string;
  7. avatar: string;
  8. }
  9. export interface AuthResponse {
  10. token: string;
  11. user: User;
  12. }
  13. const AUTH_USERS: Record<string, User> = {
  14. stu: {
  15. id: "231250001",
  16. username: "stu",
  17. role: "stu",
  18. name: "李子涵",
  19. avatar: "/images/profile-avatar.png",
  20. },
  21. teacher: {
  22. id: "tea_001",
  23. username: "teacher",
  24. role: "teacher",
  25. name: "刘钦",
  26. avatar: "/images/profile-avatar.png",
  27. },
  28. };
  29. const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
  30. export const authApi = {
  31. login: async (username: string, password: string): Promise<AuthResponse> => {
  32. await delay(300);
  33. if (password !== "passwd") {
  34. throw new Error("密码错误");
  35. }
  36. const user = AUTH_USERS[username];
  37. if (!user) {
  38. throw new Error("用户不存在");
  39. }
  40. return {
  41. token: `local_auth_${user.username}_${user.id}_${Date.now()}`,
  42. user,
  43. };
  44. },
  45. verifySession: async (token: string | null): Promise<User | null> => {
  46. await delay(120);
  47. if (!token) {
  48. return null;
  49. }
  50. return Object.values(AUTH_USERS).find((user) => token.includes(user.id)) ?? null;
  51. },
  52. };