Download src/context/AuthContext.js from SyedFouzan/taskflow-titan-workflow-wizardry: direct link, hf CLI and curl.
- Browser
- Download file 1.96 kB
-
https://huggingface.co/spaces/SyedFouzan/taskflow-titan-workflow-wizardry/resolve/main/src/context/AuthContext.js
- Command line
-
hf download hf://spaces/SyedFouzan/taskflow-titan-workflow-wizardry/src/context/AuthContext.js
-
curl -L -o AuthContext.js https://huggingface.co/spaces/SyedFouzan/taskflow-titan-workflow-wizardry/resolve/main/src/context/AuthContext.js
1.96 kB
| import React, { createContext, useContext, useState, useEffect } from 'react'; | |
| import { authAPI } from '../services/api'; | |
| const AuthContext = createContext(); | |
| export const useAuth = () => { | |
| const context = useContext(AuthContext); | |
| if (!context) { | |
| throw new Error('useAuth must be used within an AuthProvider'); | |
| } | |
| return context; | |
| }; | |
| export const AuthProvider = ({ children }) => { | |
| const [user, setUser] = useState(null); | |
| const [loading, setLoading] = useState(true); | |
| useEffect(() => { | |
| const token = localStorage.getItem('token'); | |
| if (token) { | |
| authAPI.verifyToken() | |
| .then(response => { | |
| setUser(response.data.user); | |
| }) | |
| .catch(() => { | |
| localStorage.removeItem('token'); | |
| }) | |
| .finally(() => { | |
| setLoading(false); | |
| }); | |
| } else { | |
| setLoading(false); | |
| } | |
| }, []); | |
| const login = async (credentials) => { | |
| try { | |
| const response = await authAPI.login(credentials); | |
| const { token, user } = response.data; | |
| localStorage.setItem('token', token); | |
| setUser(user); | |
| return { success: true }; | |
| } catch (error) { | |
| return { | |
| success: false, | |
| error: error.response?.data?.message || 'Login failed' | |
| }; | |
| } | |
| }; | |
| const logout = () => { | |
| localStorage.removeItem('token'); | |
| setUser(null); | |
| }; | |
| const register = async (userData) => { | |
| try { | |
| const response = await authAPI.register(userData); | |
| const { token, user } = response.data; | |
| localStorage.setItem('token', token); | |
| setUser(user); | |
| return { success: true }; | |
| } catch (error) { | |
| return { | |
| success: false, | |
| error: error.response?.data?.message || 'Registration failed' | |
| }; | |
| } | |
| }; | |
| const value = { | |
| user, | |
| login, | |
| logout, | |
| register, | |
| loading | |
| }; | |
| return ( | |
| <AuthContext.Provider value={value}> | |
| {children} | |
| </AuthContext.Provider> | |
| ); | |
| }; |