eletrotupi / tcc/ frontend/context/AuthContext.tsx17207313f44cdecf0de608083d71bbfaabc87bf5
3.2 KB | 132 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
  login: (email: string, password: string) => Promise<void>;
13
  signup: (userData: {
14
    firstName: string;
15
    lastName?: string;
16
    email: string;
17
    password: string;
18
  }) => Promise<void>;
19
  logout: () => Promise<void>;
20
  forgotPassword: (email: string) => Promise<{ message: string; token?: string }>;
21
  resetPassword: (token: string, password: string) => Promise<void>;
22
}
23

24
const AuthContext = createContext<AuthContextType | null>(null);
25

26
export function useAuth() {
27
  const context = useContext(AuthContext);
28
  if (!context) {
29
    throw new Error('useAuth must be used within an AuthProvider');
30
  }
31

32
  return context;
33
}
34

35
export const AuthProvider = ({ children }: AuthProviderProps) => {
36
  const [user, setUser] = useState<User | null>(null);
37
  const [isLoading, setIsLoading] = useState(true);
38

39
  const isAuthenticated = !!user;
40

41
  // Check for existing authentication on app start
42
  useEffect(() => {
43
    checkAuthState();
44
  }, []);
45

46
  const checkAuthState = async () => {
47
    try {
48
      const { token } = await apiClient.getStoredAuthData();
49

50
      if (token) {
51
        const verifyResponse = await apiClient.verifyToken();
52
        if (verifyResponse.valid && verifyResponse.userId && verifyResponse.email) {
53
          // TODO: Fetch the full user profile
54
          // For now, we'll create a basic user object
55
          setUser({
56
            id: verifyResponse.userId,
57
            email: verifyResponse.email,
58
            firstName: '',
59
            lastName: undefined,
60
          });
61
        }
62
      }
63
    } catch (error) {
64
      console.error('Auth check failed:', error);
65
      // Token is invalid, wipe out any stored data
66
      await apiClient.logout();
67
    } finally {
68
      setIsLoading(false);
69
    }
70
  };
71

72
  const login = async (email: string, password: string) => {
73
    setIsLoading(true);
74

75
    try {
76
      const response = await apiClient.login(email, password);
77
      setUser(response.user);
78
    } finally {
79
      setIsLoading(false);
80
    }
81
  };
82

83
  const signup = async (userData: {
84
    firstName: string;
85
    lastName?: string;
86
    email: string;
87
    password: string;
88
  }) => {
89
    setIsLoading(true);
90
    try {
91
      const response = await apiClient.signup(userData);
92
      setUser(response.user);
93
    } finally {
94
      setIsLoading(false);
95
    }
96
  };
97

98
  const logout = async () => {
99
    setIsLoading(true);
100
    try {
101
      await apiClient.logout();
102
      setUser(null);
103
    } finally {
104
      setIsLoading(false);
105
    }
106
  };
107

108
  const forgotPassword = async (email: string) => {
109
    return apiClient.forgotPassword(email);
110
  };
111

112
  const resetPassword = async (token: string, password: string) => {
113
    await apiClient.resetPassword(token, password);
114
  };
115

116
  const value: AuthContextType = {
117
    user,
118
    isLoading,
119
    isAuthenticated,
120
    login,
121
    signup,
122
    logout,
123
    forgotPassword,
124
    resetPassword,
125
  };
126

127
  return (
128
    <AuthContext.Provider value={value}>
129
      {children}
130
    </AuthContext.Provider>
131
  );
132
}