eletrotupi / tcc/ frontend/context/AuthContext.tsx4808ab95c87b9684077fe589ac47e6884c8fa551
3.8 KB | 159 lines Raw
1
import React, { createContext, useContext, useEffect, useState } from 'react';
2
import { apiClient, User } from '@/lib/api';
3

4
interface AuthProviderProps {
5
  children: React.ReactNode;
6
}
7

8
interface AuthContextType {
9
  user: User | null;
10
  isLoading: boolean;
11
  isAuthenticated: boolean;
12
  updateAuthUser: (user: {
13
    firstName: string;
14
    lastName?: string;
15
    email: string;
16
    updatedAt: date;
17
    avatarURL?: string;
18
    avatarKey?: string;
19
  }) => void;
20
  login: (email: string, password: string) => Promise<void>;
21
  signup: (userData: {
22
    firstName: string;
23
    lastName?: string;
24
    email: string;
25
    password: string;
26
  }) => Promise<void>;
27
  logout: () => Promise<void>;
28
  forgotPassword: (email: string) => Promise<{ message: string; token?: string }>;
29
  resetPassword: (token: string, password: string) => Promise<void>;
30
}
31

32

33
export function sanitizeUser(data: any): User {
34
  return {
35
    id: data.id,
36
    email: data.email,
37
    firstName: data.firstName,
38
    lastName: data.lastName,
39
    updatedAt: data.updatedAt,
40
    avatarKey: data.avatarKey,
41
    avatarURL: data.avatarURL,
42
  };
43
}
44

45
const AuthContext = createContext<AuthContextType | null>(null);
46

47
export function useAuth() {
48
  const context = useContext(AuthContext);
49
  if (!context) {
50
    throw new Error('useAuth must be used within an AuthProvider');
51
  }
52

53
  return context;
54
}
55

56
export const AuthProvider = ({ children }: AuthProviderProps) => {
57
  const [user, setUser] = useState<User | null>(null);
58
  const [isLoading, setIsLoading] = useState(true);
59
  const isAuthenticated = !!user;
60

61
  // Check for existing authentication on app start
62
  useEffect(() => {
63
    checkAuthState();
64
  }, []);
65

66
  const checkAuthState = async () => {
67
    try {
68
      const { token } = await apiClient.getStoredAuthData();
69

70
      if (token) {
71
        const verifyResponse = await apiClient.verifyToken();
72
        if (verifyResponse.valid && verifyResponse.userId && verifyResponse.email) {
73
          // TODO: Fetch the full user profile
74
          // For now, we'll create a basic user object
75
          setUser({
76
            id: verifyResponse.userId,
77
            email: verifyResponse.email,
78
            firstName: verifyResponse.user.firstName,
79
            lastName: verifyResponse.user.lastName,
80
            avatarURL: verifyResponse.user.avatarURL,
81
            avatarKey: verifyResponse.user.avatarKey
82
          });
83
        }
84
      }
85
    } catch (error) {
86
      console.error('Auth check failed:', error);
87
      // Token is invalid, wipe out any stored data
88
      await apiClient.logout();
89
    } finally {
90
      setIsLoading(false);
91
    }
92
  };
93

94
  const login = async (email: string, password: string) => {
95
    setIsLoading(true);
96

97
    try {
98
      const response = await apiClient.login(email, password);
99
      setUser(response.user);
100
    } finally {
101
      setIsLoading(false);
102
    }
103
  };
104

105
  const signup = async (userData: {
106
    firstName: string;
107
    lastName?: string;
108
    email: string;
109
    password: string;
110
  }) => {
111
    setIsLoading(true);
112
    try {
113
      const response = await apiClient.signup(userData);
114
      setUser(response.user);
115
    } finally {
116
      setIsLoading(false);
117
    }
118
  };
119

120
  const logout = async () => {
121
    setIsLoading(true);
122
    try {
123
      await apiClient.logout();
124
      setUser(null);
125
    } finally {
126
      setIsLoading(false);
127
    }
128
  };
129

130
  const forgotPassword = async (email: string) => {
131
    return apiClient.forgotPassword(email);
132
  };
133

134
  const resetPassword = async (token: string, password: string) => {
135
    await apiClient.resetPassword(token, password);
136
  };
137

138
  const updateAuthUser = (user) => {
139
    setUser(sanitizeUser(user));
140
  }
141

142
  const value: AuthContextType = {
143
    user,
144
    isLoading,
145
    isAuthenticated,
146
    login,
147
    signup,
148
    logout,
149
    forgotPassword,
150
    resetPassword,
151
    updateAuthUser
152
  };
153

154
  return (
155
    <AuthContext.Provider value={value}>
156
      {children}
157
    </AuthContext.Provider>
158
  );
159
}