# useAuthStore - Zustand Authentication Store ## โœ… Function 3 Completed ### ๐Ÿ“ฆ Files Created: 1. **`src/store/useAuthStore.ts`** - Zustand store managing auth 2. **`src/services/api/apiClient.ts`** - Axios client with interceptors 3. **`src/services/api/authService.ts`** - Auth API service 4. **`.env.example`** - Template for environment variables ### ๐ŸŽฏ Features Implemented: #### State Management: ```typescript interface AuthState { token: string | null; refreshToken: string | null; userInfo: UserInfo | null; isAuthenticated: boolean; isLoading: boolean; error: string | null; } ``` #### Actions: - โœ… `login(credentials)` - Login - โœ… `register(data)` - Register new account - โœ… `logout()` - Logout - โœ… `setUser(user)` - Update user information - โœ… `refreshAuthToken()` - Refresh token - โœ… `forgotPassword(data)` - Forgot password - โœ… `resetPassword(data)` - Reset password - โœ… `initializeAuth()` - Initialize auth from localStorage - โœ… `clearError()` - Clear error message ### ๐Ÿ“ Usage: #### 1. Initialize in App.tsx: ```typescript import useAuthStore from './store/useAuthStore'; function App() { const { isAuthenticated, userInfo, logout, initializeAuth } = useAuthStore(); useEffect(() => { initializeAuth(); }, [initializeAuth]); // ... } ``` #### 2. Use in Login Form: ```typescript import useAuthStore from '../store/useAuthStore'; const LoginPage = () => { const { login, isLoading, error } = useAuthStore(); const navigate = useNavigate(); const handleSubmit = async (data) => { try { await login(data); navigate('/dashboard'); // Redirect after login } catch (error) { // Error has been handled by store } }; return (
{/* Form fields */} {error &&
{error}
}
); }; ``` #### 3. Use in Register Form: ```typescript const RegisterPage = () => { const { register, isLoading } = useAuthStore(); const navigate = useNavigate(); const handleSubmit = async (data) => { try { await register(data); navigate('/login'); // Redirect to login } catch (error) { // Error displayed via toast } }; // ... }; ``` #### 4. Logout: ```typescript const Header = () => { const { logout } = useAuthStore(); const handleLogout = async () => { await logout(); // Auto redirect to login if needed }; return ; }; ``` #### 5. Display user information: ```typescript const Profile = () => { const { userInfo } = useAuthStore(); return (

Hello, {userInfo?.name}

Email: {userInfo?.email}

Role: {userInfo?.role}

); }; ``` ### ๐Ÿ” LocalStorage Persistence: Store automatically saves and reads from localStorage: - `token` - JWT access token - `refreshToken` - JWT refresh token - `userInfo` - User information When page reloads, auth state is automatically restored via `initializeAuth()`. ### ๐ŸŒ API Integration: #### Base URL Configuration: Create `.env` file in `client/` directory: ```env VITE_API_URL=http://localhost:3000 VITE_ENV=development ``` #### API Endpoints Used: - `POST /api/auth/login` - Login - `POST /api/auth/register` - Register - `POST /api/auth/logout` - Logout - `GET /api/auth/profile` - Get profile - `POST /api/auth/refresh-token` - Refresh token - `POST /api/auth/forgot-password` - Forgot password - `POST /api/auth/reset-password` - Reset password ### ๐Ÿ›ก๏ธ Security Features: 1. **Auto Token Injection**: - Axios interceptor automatically adds token to headers ```typescript Authorization: Bearer ``` 2. **Auto Logout on 401**: - When token expires (401), automatically logout and redirect to login 3. **Token Refresh**: - Can refresh token when about to expire 4. **Password Hashing**: - Backend handles bcrypt hashing ### ๐Ÿ“ฑ Toast Notifications: Store automatically displays toast for events: - โœ… Login successful - โœ… Registration successful - โœ… Logout - โŒ Login failed - โŒ Registration failed - โŒ API errors ### ๐Ÿ”„ Component Updates: #### ProtectedRoute: ```typescript // BEFORE (with props) // AFTER (automatically gets from store) ``` #### AdminRoute: ```typescript // BEFORE (with props) // AFTER (automatically gets from store) ``` #### LayoutMain: Still receives props from App.tsx to display Header/Navbar: ```typescript ``` ### ๐Ÿงช Testing: To test authentication flow: 1. **Create `.env` file**: ```bash cp .env.example .env ``` 2. **Ensure backend is running**: ```bash cd server npm run dev ``` 3. **Run frontend**: ```bash cd client npm run dev ``` 4. **Test flow**: - Access `/register` โ†’ Register account - Access `/login` โ†’ Login - Access `/dashboard` โ†’ View dashboard (protected) - Click logout โ†’ Clear session - Reload page โ†’ Auth state restored ### ๐Ÿš€ Next Steps: **Function 4: Login Form** - Create LoginPage with React Hook Form + Yup - Integrate with useAuthStore - UX enhancements (loading, show/hide password, remember me) **Function 5: Register Form** - Create RegisterPage with validation - Integrate with useAuthStore **Function 6-7: Password Reset Flow** - ForgotPasswordPage - ResetPasswordPage ### ๐Ÿ“š TypeScript Types: ```typescript interface LoginCredentials { email: string; password: string; rememberMe?: boolean; } interface RegisterData { name: string; email: string; password: string; phone?: string; } interface UserInfo { id: number; name: string; email: string; phone?: string; avatar?: string; role: string; createdAt?: string; } ``` ### โœ… Results Achieved: 1. โœ… All user information managed centrally 2. โœ… Maintain login after page reload 3. โœ… Easy access to userInfo in any component 4. โœ… Auto token management 5. โœ… Type-safe with TypeScript 6. โœ… Clean code, easy to maintain