init code

This commit is contained in:
Tham Luu
2024-09-23 15:07:25 +08:00
commit 2842b3fc19
63 changed files with 7901 additions and 0 deletions

37
src/hooks/useAuth.js Normal file
View File

@ -0,0 +1,37 @@
import { getLogout, postLogin } from '@api/auth'
import { AuthContext } from '@context/auth-context'
import { PathConstants } from '@routes/routes'
import { LOGIN_KEY } from '@utils/enum'
import { Helpers } from '@utils/helper'
import { useContext } from 'react'
import { useNavigate } from 'react-router-dom'
export function useSignInUp(setAuth) {
const navigate = useNavigate()
const onLogin = async ({ username, password }) => {
const resp = await postLogin({ username, password })
if (resp.status === 200) {
const token = resp.data || {}
if (token) {
const { name, ...rest } = token
setAuth({ isLogged: true, userInfo: { name } })
localStorage.setItem(LOGIN_KEY, Helpers.encrypt(JSON.stringify(rest)))
}
navigate('/')
}
}
const onLogout = async () => {
await getLogout()
Helpers.clearStorage()
setAuth({ isLogged: false, userInfo: null })
navigate(PathConstants.LOGIN)
}
return { onLogin, onLogout }
}
export function useAuth() {
return useContext(AuthContext)
}