auth.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // 定义用户接口 (参考 OpenAPI VasUserOut)
  2. export interface User {
  3. id: string;
  4. email: string;
  5. phone?: string;
  6. nickname?: string;
  7. role?: string; // 关键字段: 'admin' | 'user'
  8. avatar_url?: string;
  9. }
  10. // 获取当前用户
  11. export const getCurrentUser = (): User | null => {
  12. if (typeof window === 'undefined') return null;
  13. const userStr = localStorage.getItem('user_info');
  14. if (!userStr) return null;
  15. try {
  16. return JSON.parse(userStr);
  17. } catch (e) {
  18. return null;
  19. }
  20. };
  21. // 检查是否是管理员
  22. export const isAdmin = (): boolean => {
  23. const user = getCurrentUser();
  24. // 注意:请确认你数据库里的角色字符串是 'admin' 还是 'administrator' 或 'superuser'
  25. return user?.role === 'admin';
  26. };
  27. // 退出登录
  28. export const logout = () => {
  29. if (typeof window === 'undefined') return;
  30. localStorage.removeItem('rsid');
  31. localStorage.removeItem('user_info');
  32. // 触发 storage 事件以便其他组件更新
  33. window.dispatchEvent(new Event('storage'));
  34. window.location.href = '/login';
  35. };