|
|
typescript |
|
|
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react' |
|
|
|
|
|
interface User { |
|
|
id: string |
|
|
name: string |
|
|
email: string |
|
|
role: string |
|
|
avatar?: string |
|
|
} |
|
|
|
|
|
interface AuthContextType { |
|
|
user: User | null |
|
|
login: (email: string, password: string) => Promise<void> |
|
|
logout: () => void |
|
|
isLoading: boolean |
|
|
} |
|
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined) |
|
|
|
|
|
export const useAuth = () => { |
|
|
const context = useContext(AuthContext) |
|
|
if (context === undefined) { |
|
|
throw new Error('useAuth must be used within an AuthProvider') |
|
|
} |
|
|
return context |
|
|
} |
|
|
|
|
|
interface AuthProviderProps { |
|
|
children: ReactNode |
|
|
} |
|
|
|
|
|
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => { |
|
|
const [user, setUser] = useState<User | null>(null) |
|
|
const [isLoading, setIsLoading] = useState(true) |
|
|
|
|
|
useEffect(() => { |
|
|
|
|
|
const token = localStorage.getItem('auth_token') |
|
|
if (token) { |
|
|
|
|
|
setUser({ |
|
|
id: '1', |
|
|
name: 'John Doe', |
|
|
email: 'john.doe@company.com', |
|
|
role: 'admin' |
|
|
}) |
|
|
} |
|
|
setIsLoading(false) |
|
|
}, []) |
|
|
|
|
|
const login = async (email: string, password: string): Promise<void> => { |
|
|
setIsLoading(true) |
|
|
try { |
|
|
|
|
|
await new Promise(resolve => setTimeout(resolve, 1000)) |
|
|
|
|
|
if (email === 'admin@mapit.com' && password === 'password') { |
|
|
const userData: User = { |
|
|
id: '1', |
|
|
name: 'John Doe', |
|
|
email: email, |
|
|
role: 'admin' |
|
|
} |
|
|
setUser(userData) |
|
|
localStorage.setItem('auth_token', 'mock_jwt_token') |
|
|
} else { |
|
|
throw new Error('Invalid credentials') |
|
|
} |
|
|
} finally { |
|
|
setIsLoading(false) |
|
|
} |
|
|
} |
|
|
|
|
|
const logout = () => { |
|
|
setUser(null) |
|
|
localStorage.removeItem('auth_token') |
|
|
} |
|
|
|
|
|
return ( |
|
|
<AuthContext.Provider value={{ user, login, logout, isLoading }}> |
|
|
{children} |
|
|
</AuthContext.Provider> |
|
|
) |
|
|
} |
|
|
|
|
|
</html> |