eletrotupi / tcc/ frontend/context/AuthContext.tsx88d7ba76dc54469a8a0bf8d1f5da7ba67d8b612a
3.6 KB | 147 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
  }) => void;
18
  login: (email: string, password: string) => Promise<void>;
19
  signup: (userData: {
20
    firstName: string;
21
    lastName?: string;
22
    email: string;
23
    password: string;
24
  }) => Promise<void>;
25
  logout: () => Promise<void>;
26
  forgotPassword: (email: string) => Promise<{ message: string; token?: string }>;
27
  resetPassword: (token: string, password: string) => Promise<void>;
28
}
29

30
const AuthContext = createContext<AuthContextType | null>(null);
31

32
export function useAuth() {
33
  const context = useContext(AuthContext);
34
  if (!context) {
35
    throw new Error('useAuth must be used within an AuthProvider');
36
  }
37

38
  return context;
39
}
40

41
export const AuthProvider = ({ children }: AuthProviderProps) => {
42
  const [user, setUser] = useState<User | null>(null);
43
  const [isLoading, setIsLoading] = useState(true);
44

45
  console.log("user & auth", isAuthenticated, user)
46
  const isAuthenticated = !!user;
47
  console.log("after user & auth", isAuthenticated, user)
48

49
  // Check for existing authentication on app start
50
  useEffect(() => {
51
    checkAuthState();
52
  }, []);
53

54
  const checkAuthState = async () => {
55
    try {
56
      const { token } = await apiClient.getStoredAuthData();
57
      console.log("We have a token?", token);
58

59
      if (token) {
60
        const verifyResponse = await apiClient.verifyToken();
61
        console.log("Checking response: ", verifyResponse)
62
        if (verifyResponse.valid && verifyResponse.userId && verifyResponse.email) {
63
          // TODO: Fetch the full user profile
64
          // For now, we'll create a basic user object
65
          setUser({
66
            id: verifyResponse.userId,
67
            email: verifyResponse.email,
68
            firstName: verifyResponse.user.firstName,
69
            lastName: verifyResponse.user.lastName,
70
          });
71
        }
72
      }
73
    } catch (error) {
74
      console.error('Auth check failed:', error);
75
      // Token is invalid, wipe out any stored data
76
      await apiClient.logout();
77
    } finally {
78
      setIsLoading(false);
79
    }
80
  };
81

82
  const login = async (email: string, password: string) => {
83
    setIsLoading(true);
84

85
    try {
86
      const response = await apiClient.login(email, password);
87
      setUser(response.user);
88
    } finally {
89
      setIsLoading(false);
90
    }
91
  };
92

93
  const signup = async (userData: {
94
    firstName: string;
95
    lastName?: string;
96
    email: string;
97
    password: string;
98
  }) => {
99
    setIsLoading(true);
100
    try {
101
      const response = await apiClient.signup(userData);
102
      setUser(response.user);
103
    } finally {
104
      setIsLoading(false);
105
    }
106
  };
107

108
  const logout = async () => {
109
    setIsLoading(true);
110
    try {
111
      await apiClient.logout();
112
      setUser(null);
113
    } finally {
114
      setIsLoading(false);
115
    }
116
  };
117

118
  const forgotPassword = async (email: string) => {
119
    return apiClient.forgotPassword(email);
120
  };
121

122
  const resetPassword = async (token: string, password: string) => {
123
    await apiClient.resetPassword(token, password);
124
  };
125

126
  const updateAuthUser = (user) => {
127
    setUser(user);
128
  }
129

130
  const value: AuthContextType = {
131
    user,
132
    isLoading,
133
    isAuthenticated,
134
    login,
135
    signup,
136
    logout,
137
    forgotPassword,
138
    resetPassword,
139
    updateAuthUser
140
  };
141

142
  return (
143
    <AuthContext.Provider value={value}>
144
      {children}
145
    </AuthContext.Provider>
146
  );
147
}