Skip to content

Commit

Permalink
#104 refactor: 새로고침 해도 로그인 상태가 유지되도록 수정 및 이슈목록 페이지 로그아웃 버튼 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
silvertae committed Aug 17, 2023
1 parent 49291c7 commit 4321352
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 7 deletions.
22 changes: 19 additions & 3 deletions frontend/src/context/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { useState, createContext, ReactElement } from 'react';

export type AuthUser = {
userId: string;
userId: number;
userName: string;
profileImg: string;
accessToken: string;
} | null;

export type AuthContextType = {
auth: AuthUser | null;
isAuthenticated: boolean;
setAuth: React.Dispatch<React.SetStateAction<AuthUser | null>>;
login: (authUser: AuthUser) => void;
logout: () => void;
Expand All @@ -17,18 +18,33 @@ export type AuthContextType = {
export const AuthContext = createContext<AuthContextType>(null);

export function AuthProvider({ children }: { children: ReactElement }) {
const [auth, setAuth] = useState<AuthUser>(null);
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(
localStorage.getItem('userId') ? true : false
);
const [auth, setAuth] = useState<AuthUser>(
localStorage.getItem('userId')
? {
userId: JSON.parse(localStorage.getItem('userId')!) as number,
userName: localStorage.getItem('userName') as string,
profileImg: localStorage.getItem('profileImg') as string,
accessToken: localStorage.getItem('accessToken') as string,
}
: null
);

const login = (authUser: AuthUser) => {
setIsAuthenticated(true);
setAuth(authUser);
};

const logout = () => {
setIsAuthenticated(false);
setAuth(null);
};

return (
<AuthContext.Provider value={{ auth, setAuth, login, logout }}>
<AuthContext.Provider
value={{ auth, isAuthenticated, setAuth, login, logout }}>
{children}
</AuthContext.Provider>
);
Expand Down
29 changes: 29 additions & 0 deletions frontend/src/pages/Issues.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { AppContext } from '../main';
import useAuth from '../hooks/useAuth';
import Header from '../components/landmark/Header';
import IssueTable from '../components/issues/IssueTable';
import Main from '../components/landmark/Main';
Expand All @@ -16,7 +18,9 @@ import useAxiosPrivate from '../hooks/useAxiosPrivate';

export default function Issues() {
const { util } = useContext(AppContext);
const { auth, logout } = useAuth();
const logo = (util.getLogoByTheme() as ContextLogo).medium;
const navigate = useNavigate();
const axiosPrivate = useAxiosPrivate();

const [data, setData] = useState<Data>({
Expand Down Expand Up @@ -99,13 +103,38 @@ export default function Issues() {
// };
// fetchData();
// }, []);
const handleLogout = async () => {
if (!auth) {
return;
}

try {
const res = await axiosPrivate.post('/api/logout', null, {
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
});

if (res.status === 200) {
localStorage.clear();
logout();
navigate('/login');
} else {
console.error('로그아웃 실패:', res.status);
}
} catch (err) {
console.error('로그아웃 에러:', err);
}
};

return (
<Layout>
<Header>
<Link to="/">
<img src={logo} alt="이슈트래커" />
</Link>
<Button type="button" ghost onClick={handleLogout}>
로그아웃
</Button>
<div>
{/* profile */}
popopo
Expand Down
7 changes: 5 additions & 2 deletions frontend/src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ export default function Login() {
);

if (res.status === 200) {
localStorage.setItem('userId', res.data.message.userId);
localStorage.setItem('userName', res.data.message.userName);
localStorage.setItem('profileImg', res.data.message.profileImgUrl);
localStorage.setItem('accessToken', res.data.message.accessToken);
localStorage.setItem('refreshToken', res.data.message.refreshToken);
login({
Expand Down Expand Up @@ -105,7 +108,7 @@ export default function Login() {
<TextInput
id="userId"
name="userId"
size="tall"
sizeType="tall"
labelName="아이디"
value={userId}
onChange={handleChange}
Expand All @@ -116,7 +119,7 @@ export default function Login() {
<TextInput
id="password"
name="password"
size="tall"
sizeType="tall"
type="password"
value={password}
onChange={handleChange}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/routes/RequireAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { useLocation, Navigate, Outlet } from 'react-router-dom';
import useAuth from '../hooks/useAuth';

function RequireAuth() {
const { auth } = useAuth();
const { isAuthenticated } = useAuth();
const location = useLocation();

return auth?.userId ? (
return isAuthenticated ? (
<Outlet />
) : (
<Navigate to="/login" state={{ from: location }} replace />
Expand Down

0 comments on commit 4321352

Please sign in to comment.