# 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 (
);
};
```
#### 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