AuthContext.jsx 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import React, { createContext, useContext, useState, useEffect } from 'react';
  2. const API_BASE = import.meta.env.PROD ? '/api' : 'http://localhost:3001/api';
  3. const AuthContext = createContext();
  4. export function useAuth() {
  5. const context = useContext(AuthContext);
  6. if (context === undefined) {
  7. throw new Error('useAuth must be used within an AuthProvider');
  8. }
  9. return context;
  10. }
  11. export function AuthProvider({ children }) {
  12. const [user, setUser] = useState(null);
  13. const [loading, setLoading] = useState(true);
  14. const [error, setError] = useState(null);
  15. // Check if user is already authenticated on app start
  16. useEffect(() => {
  17. checkAuth();
  18. }, []);
  19. const checkAuth = async () => {
  20. try {
  21. console.log('Checking auth status...');
  22. const response = await fetch(`${API_BASE}/auth/me`, {
  23. credentials: 'include'
  24. });
  25. console.log('Auth check response:', response.status, response.statusText);
  26. if (response.ok) {
  27. const data = await response.json();
  28. console.log('Auth check data:', data);
  29. setUser(data.user);
  30. } else {
  31. console.log('Auth check failed, user not authenticated');
  32. setUser(null);
  33. }
  34. } catch (err) {
  35. console.error('Auth check failed:', err);
  36. setUser(null);
  37. } finally {
  38. setLoading(false);
  39. }
  40. };
  41. const login = async (username, password) => {
  42. try {
  43. setLoading(true);
  44. setError(null);
  45. const response = await fetch(`${API_BASE}/auth/login`, {
  46. method: 'POST',
  47. headers: {
  48. 'Content-Type': 'application/json',
  49. },
  50. credentials: 'include',
  51. body: JSON.stringify({ username, password }),
  52. });
  53. const data = await response.json();
  54. if (response.ok) {
  55. setUser(data.user);
  56. return { success: true };
  57. } else {
  58. setError(data.error || 'Login failed');
  59. return { success: false, error: data.error || 'Login failed' };
  60. }
  61. } catch (err) {
  62. const errorMessage = 'Network error. Please check if the server is running.';
  63. setError(errorMessage);
  64. return { success: false, error: errorMessage };
  65. } finally {
  66. setLoading(false);
  67. }
  68. };
  69. const logout = async () => {
  70. try {
  71. await fetch(`${API_BASE}/auth/logout`, {
  72. method: 'POST',
  73. credentials: 'include',
  74. });
  75. } catch (err) {
  76. console.error('Logout request failed:', err);
  77. } finally {
  78. setUser(null);
  79. setError(null);
  80. }
  81. };
  82. const changePassword = async (currentPassword, newPassword) => {
  83. try {
  84. const response = await fetch(`${API_BASE}/auth/change-password`, {
  85. method: 'POST',
  86. headers: {
  87. 'Content-Type': 'application/json',
  88. },
  89. credentials: 'include',
  90. body: JSON.stringify({ currentPassword, newPassword }),
  91. });
  92. const data = await response.json();
  93. if (response.ok) {
  94. return { success: true, message: data.message };
  95. } else {
  96. return { success: false, error: data.error || 'Password change failed' };
  97. }
  98. } catch (err) {
  99. return { success: false, error: 'Network error. Please try again.' };
  100. }
  101. };
  102. const value = {
  103. user,
  104. loading,
  105. error,
  106. login,
  107. logout,
  108. changePassword,
  109. isAdmin: user?.role === 'admin',
  110. isAuthenticated: !!user,
  111. };
  112. return (
  113. <AuthContext.Provider value={value}>
  114. {children}
  115. </AuthContext.Provider>
  116. );
  117. }