You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
98 lines
2.5 KiB
98 lines
2.5 KiB
import React, { createContext, useContext, useState } from 'react' |
|
import { message } from 'antd' |
|
import { useHistory } from 'react-router' |
|
import { User } from '../types' |
|
import { useAppContext } from './AppContext' |
|
import { useEffect } from 'react' |
|
import { useRef } from 'react' |
|
import axios from 'axios' |
|
|
|
type Props = { |
|
children: React.ReactNode |
|
} |
|
|
|
type Context = { |
|
user: User | null |
|
handleLogin: (name: string, password: string) => void |
|
handleLogout: () => void |
|
} |
|
|
|
const UserContext = createContext<Context | null>(null) |
|
|
|
export const UserContextProvider = ({ children }: Props) => { |
|
const api = useRef(useAppContext()) |
|
const history = useRef(useHistory()) |
|
|
|
const [user, setUser] = useState<User | null>(null) |
|
|
|
useEffect(() => { |
|
const get = async () => { |
|
try { |
|
const token = window.localStorage.getItem('cash-stacks-token') |
|
if (!token) throw new Error() |
|
|
|
// const valid = await api.current.post('/dj-rest-auth/token/verify/', { |
|
// token, |
|
// }) |
|
// console.log('token valid?', token) |
|
const user = await api.current.get<User>(`/dj-rest-auth/user/`) |
|
setUser(user) |
|
} catch (err) { |
|
console.log(`couldn't get user, token possibly expired`) |
|
// window.localStorage.removeItem('cash-stacks-token') |
|
history.current.push('/login') |
|
} |
|
} |
|
|
|
get() |
|
}, []) |
|
|
|
const handleLogin = async (username: string, password: string) => { |
|
try { |
|
const res = await axios.post<{ key: string }>( |
|
'http://localhost:8000/dj-rest-auth/login/', |
|
{ |
|
username, |
|
password, |
|
}, |
|
) |
|
if (!res.data.key) throw new Error('Problem logging in!') |
|
|
|
window.localStorage.setItem('cash-stacks-token', res.data.key) |
|
|
|
const user = await api.current.get<User>(`/dj-rest-auth/user/`) |
|
setUser(user) |
|
} catch (err) { |
|
message.error('Login Failed!') |
|
} |
|
} |
|
|
|
const handleLogout = async () => { |
|
await api.current.post('/dj-rest-auth/logout/', {}) |
|
setUser(null) |
|
history.current.push('/') |
|
} |
|
|
|
return ( |
|
<UserContext.Provider |
|
value={{ |
|
user, |
|
handleLogin, |
|
handleLogout, |
|
}} |
|
> |
|
{children} |
|
</UserContext.Provider> |
|
) |
|
} |
|
|
|
export const useUserContext = () => { |
|
const context = useContext(UserContext) |
|
|
|
if (!context) |
|
throw new Error( |
|
'UserContext must be called from within the UserContextProvider', |
|
) |
|
|
|
return context |
|
}
|
|
|