💬
JWT Authentication【24Logout】
JWT Authentication【24Logout】
YouTube: https://youtu.be/fEN0wmwIRCw
今回はログアウト機能の実装になります。
ログアウトで処理するのは、
cookieに設定されているJWTの削除(サーバーサイド)、
authContextに設定されているuserの値の初期化(クライアントサイド)
こちらの2点になります。
src/context/authContext.tsx
import {
createContext,
ReactNode,
useContext,
FC,
useState,
useEffect,
} from 'react'
import axios from 'axios'
import { LoginUser } from '../types/user'
interface Props {
children: ReactNode
}
interface AuthContextType {
user: LoginUser | null
setUser: React.Dispatch<React.SetStateAction<LoginUser | null>>
login: (email: string, password: string) => Promise<void>
logout: () => Promise<void>
}
const AuthContext = createContext({} as AuthContextType)
export const AuthProvider: FC<Props> = ({ children }) => {
const [user, setUser] = useState<LoginUser | null>(null)
const login = async (email: string, password: string) => {
try {
const res = await axios.post(
`http://localhost:4000/api/auth/login`,
{
email,
password,
},
{ withCredentials: true }
)
setUser(res.data)
} catch (error: any) {
console.log(error.response.data)
}
}
const checkIsLogin = async () => {
try {
const res = await axios.get(`http://localhost:4000/api/auth/me`, {
withCredentials: true,
})
setUser(res.data)
} catch (error: any) {
console.log(error.response.data)
setUser(null)
}
}
useEffect(() => {
checkIsLogin()
}, [])
const logout = async () => {
try {
const res = await axios.post(
`http://localhost:4000/api/auth/logout`,
{},
{ withCredentials: true }
)
setUser(null)
} catch (error: any) {
console.log(error.response.data)
}
}
return (
<AuthContext.Provider value={{ user, setUser, login, logout }}>
{children}
</AuthContext.Provider>
)
}
export const useAuthContext = () => useContext(AuthContext)
src/pages/Home.tsx
import { useAuthContext } from '../context/authContext'
import { Link } from 'react-router-dom'
const Home = () => {
const { user, logout } = useAuthContext()
console.log(user)
return (
<div className="container text-center p-5">
<div className="text-4xl mb-3">Welcome Home {user && user.name}</div>
<div className="flex justify-center">
<Link
to={'/login'}
className=" bg-slate-700 text-white px-4 py-2 rounded"
>
login
</Link>
<div
className=" bg-slate-700 text-white px-4 py-2 mx-3 rounded cursor-pointer"
onClick={logout}
>
logout
</div>
<Link
to={'/protected'}
className=" bg-slate-700 text-white px-4 py-2 rounded"
>
protected
</Link>
</div>
</div>
)
}
export default Home
Discussion