aboutsummaryrefslogtreecommitdiffstats
path: root/frontend/src/context/auth-context.js
blob: d67b345fc71b0546f4b6abed406805b456f162e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import { createContext, useContext, useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Sonner, toast } from 'sonner';
import * as authApi from '@/lib/api/auth';

// Create auth context
const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  // Check if user is logged in on initial load
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const currentUser = authApi.getCurrentUser();
        if (currentUser) {
          setUser(currentUser);
        }
      } catch (error) {
        console.error('Authentication check failed:', error);
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, []);

  // Login user
  const login = async (credentials) => {
    try {
      setLoading(true);
      const data = await authApi.login(credentials);
      setUser(data.user);
      
      toast.success('Login successful!');
      
      // Redirect based on role
      if (data.user.role === 'admin') {
        router.push('/admin');
      } else if (data.user.role === 'staff') {
        router.push('/staff');
      } else {
        router.push('/');
      }
      
      return data;
    } catch (error) {
      toast.error(error.message || 'Login failed');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  // Register user
  const register = async (userData) => {
    try {
      setLoading(true);
      const data = await authApi.register(userData);
      setUser(data.user);
      
      toast.success('Registration successful!');
      router.push('/');
      
      return data;
    } catch (error) {
      toast.error(error.message || 'Registration failed');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  // Logout user
  const logout = () => {
    authApi.logout();
    setUser(null);
    router.push('/login');
    toast.success('Logged out successfully');
  };

  // Get user profile
  const getProfile = async () => {
    try {
      setLoading(true);
      const data = await authApi.getProfile();
      setUser(data.user);
      return data.user;
    } catch (error) {
      console.error('Failed to get user profile:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        loading,
        isAuthenticated: !!user,
        login,
        register,
        logout,
        getProfile,
      }}
    >
      {children}
      <Sonner position="top-right" />
    </AuthContext.Provider>
  );
};

// Custom hook to use auth context
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};