Skip to content

Commit

Permalink
새로고침 후 재로그인
Browse files Browse the repository at this point in the history
  • Loading branch information
오승태 authored and 오승태 committed Jan 12, 2024
1 parent fb6d36d commit 5608cba
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 81 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<title>Synergy | 팀프로젝트 협업 SNS</title>
</head>
<body>
<div id="root"></div>
Expand Down
25 changes: 19 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { MantineProvider } from "@mantine/core";
import { LoadingOverlay, MantineProvider } from "@mantine/core";
import {
BrowserRouter,
Navigate,
Outlet,
Route,
Routes,
useNavigate,
} from "react-router-dom";
import Layout from "components/ui/Layout";
import ChatRoom from "components/chat/ChatRoom";
Expand All @@ -20,20 +21,32 @@ import Notification from "pages/Notification";
import RecentPost from "pages/RecentPost";
import RecentProject from "pages/RecentProject";
import Search from "pages/Search";
import { selectCurrentToken } from "app/authSlice";
import { useSelector } from "react-redux";
import { selectCurrentToken, setAccessToken } from "app/authSlice";
import { useDispatch, useSelector } from "react-redux";
import PostDetail from "pages/PostDetail";
import Following from "pages/Following";
import OauthRedirect from "pages/OauthRedirect";
import ProjectNotice from "components/project/ProjectNotice";
import ProjectSchedule from "components/project/ProjectSchedule";
import ProjectPeerRating from "components/project/ProjectPeerRating";
import ProjectTaskBoard from "components/project/task/ProjectTaskBoard";
import { useEffect } from "react";
import { useLocalStorage } from "@mantine/hooks";

const PrivateRoutes = () => {
const auth = useSelector(selectCurrentToken);
console.log(auth);
return auth ? <Outlet /> : <Navigate to="/auth" />;
const dispatch = useDispatch();
const token = useSelector(selectCurrentToken);

if (!token) {
localStorage.setItem("redirect-url-after-auth", window.location.pathname);
window.location.href =
import.meta.env.VITE_API_URL +
`/oauth2/authorization/google?redirect_uri=${window.location.origin}/oauth/redirect`;
return <LoadingOverlay visible />;
}

localStorage.removeItem("redirect-url-after-auth");
return <Outlet />;
};

export default function App() {
Expand Down
10 changes: 5 additions & 5 deletions src/app/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ const baseQueryWithReauth = async (
extraOptions: object
) => {
let result = await baseQuery(args, api, extraOptions);
// if (result.error && result.error.status === 401) {
if (result.error) {
if (result.error && result.error.status === 401) {
const state = api.getState() as RootState;
console.log("state", state);
const token = state.auth.token;
Expand All @@ -53,7 +52,6 @@ const baseQueryWithReauth = async (
} = await axios.get(import.meta.env.VITE_API_URL + "/api/v1/auth/refresh", {
headers: {
Authorization: `Bearer ${token}`,
Credentials: "include",
},
});

Expand All @@ -64,7 +62,8 @@ const baseQueryWithReauth = async (
}

if (refreshResult.header?.code === 400) {
window.location.href = "/auth";
console.log(refreshResult);
// window.location.href = "/auth";
}
}

Expand Down Expand Up @@ -110,6 +109,7 @@ export const api = createApi({
// MyInfo
getMyInfo: build.query<User, null>({
query: () => "/users/me/info",
providesTags: [{ type: "MyInfo" }],
}),

editMyInfo: build.mutation<void, User>({
Expand Down Expand Up @@ -752,7 +752,7 @@ export const api = createApi({
{ content: Post[]; totalPages: number },
[string, number]
>({
query: ([userId, page]) => `/posts?authorId=${userId}&page=${page}`,
query: ([userId, page]) => `/posts/other?userId=${userId}&page=${page}`,
serializeQueryArgs: ({ queryArgs, endpointName }) => {
return endpointName + queryArgs[0];
},
Expand Down
1 change: 1 addition & 0 deletions src/app/authSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const authSlice = createSlice({
});

export const { setAccessToken } = authSlice.actions;

export default authSlice.reducer;

export const selectCurrentToken = (state: RootState) => state.auth.token;
2 changes: 1 addition & 1 deletion src/components/comment/CommentCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default function CommentCard({ userId, comment, updateAt }: Comment) {

dayjs.extend(relativeTime);
dayjs.extend(utc);
const fromNow = dayjs(updateAt).local().fromNow();
const fromNow = dayjs.utc(updateAt).local().fromNow();

return (
<Paper w="100%" p="sm">
Expand Down
2 changes: 1 addition & 1 deletion src/components/post/PostCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export default function PostCard({
<Text>{post.authorName}</Text>

<Text fz="sm" c="gray">
{dayjs(post.createAt).local().fromNow()}
{dayjs.utc(post.createAt).local().fromNow()}
</Text>
</Group>

Expand Down
5 changes: 3 additions & 2 deletions src/components/ui/HeaderSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import { useDisclosure } from "@mantine/hooks";
import { IconSearch } from "@tabler/icons-react";
import { ReactComponent as Logo } from "assets/logo.svg";
import { Link, useLocation } from "react-router-dom";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { SearchInput } from "../search/SearchInput";
import { api } from "app/api";
import { setAccessToken } from "app/authSlice";
Expand Down Expand Up @@ -73,6 +73,7 @@ interface HeaderSearchProps {

export function HeaderSearch({ links, children }: HeaderSearchProps) {
const dispatch = useDispatch();
const navigate = useNavigate();
const activePage = useLocation().pathname.split("/")[1];
const { classes, cx } = useStyles();

Expand Down Expand Up @@ -171,7 +172,7 @@ export function HeaderSearch({ links, children }: HeaderSearchProps) {
<Menu.Item>내 프로필</Menu.Item>
</Link>
<Link
to={`/`}
to={`/auth`}
style={{ color: "inherit", textDecoration: "inherit" }}
>
<Menu.Item onClick={removeAccessToken}>로그아웃</Menu.Item>
Expand Down
131 changes: 68 additions & 63 deletions src/components/ui/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import { useEffect } from "react";
import { SseProvider } from "app/SseContext";
import { EditUserInfoModal } from "components/user/EditUserInfoModal";
import { StompProvider } from "app/StompContext";

const headerLinks = [
{
Expand Down Expand Up @@ -87,39 +88,25 @@ export default function Layout() {
);

return (
// <StompProvider>
<SseProvider>
<AppShell
styles={{
main: {
minHeight: 0,
background:
theme.colorScheme === "dark" ? theme.colors.dark[8] : theme.white,
},
}}
navbarOffsetBreakpoint="md"
asideOffsetBreakpoint="md"
navbar={
<Navbar
p="xs"
hiddenBreakpoint="md"
hidden={!opened}
width={{ sm: 200, lg: 300 }}
bg={
theme.colorScheme === "dark" ? theme.colors.dark[8] : theme.white
}
withBorder={false}
>
<Navbar.Section grow mt="md">
<NavbarContent />
</Navbar.Section>
</Navbar>
}
aside={
<MediaQuery smallerThan="md" styles={{ display: "none" }}>
<Aside
<StompProvider>
<SseProvider>
<AppShell
styles={{
main: {
minHeight: 0,
background:
theme.colorScheme === "dark"
? theme.colors.dark[8]
: theme.white,
},
}}
navbarOffsetBreakpoint="md"
asideOffsetBreakpoint="md"
navbar={
<Navbar
p="xs"
hiddenBreakpoint="md"
hidden={!opened}
width={{ sm: 200, lg: 300 }}
bg={
theme.colorScheme === "dark"
Expand All @@ -128,38 +115,56 @@ export default function Layout() {
}
withBorder={false}
>
<Aside.Section grow mt="md">
<AsideContent />
</Aside.Section>
</Aside>
</MediaQuery>
}
footer={
isChatRoom ? undefined : (
<MediaQuery largerThan="md" styles={{ display: "none" }}>
<Footer height={56}>
<BottomNav links={headerLinks} />
</Footer>
</MediaQuery>
)
}
header={
<HeaderSearch links={headerLinks}>
<MediaQuery largerThan="md" styles={{ display: "none" }}>
<Burger
opened={opened}
onClick={handleToggleNavbar}
size="sm"
color={theme.colors.gray[6]}
/>
<Navbar.Section grow mt="md">
<NavbarContent />
</Navbar.Section>
</Navbar>
}
aside={
<MediaQuery smallerThan="md" styles={{ display: "none" }}>
<Aside
p="xs"
hiddenBreakpoint="md"
width={{ sm: 200, lg: 300 }}
bg={
theme.colorScheme === "dark"
? theme.colors.dark[8]
: theme.white
}
withBorder={false}
>
<Aside.Section grow mt="md">
<AsideContent />
</Aside.Section>
</Aside>
</MediaQuery>
</HeaderSearch>
}
>
<Outlet />
<FloatingActionButton />
</AppShell>
</SseProvider>
// </StompProvider>
}
footer={
isChatRoom ? undefined : (
<MediaQuery largerThan="md" styles={{ display: "none" }}>
<Footer height={56}>
<BottomNav links={headerLinks} />
</Footer>
</MediaQuery>
)
}
header={
<HeaderSearch links={headerLinks}>
<MediaQuery largerThan="md" styles={{ display: "none" }}>
<Burger
opened={opened}
onClick={handleToggleNavbar}
size="sm"
color={theme.colors.gray[6]}
/>
</MediaQuery>
</HeaderSearch>
}
>
<Outlet />
<FloatingActionButton />
</AppShell>
</SseProvider>
</StompProvider>
);
}
6 changes: 4 additions & 2 deletions src/pages/OauthRedirect.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import { setAccessToken } from "app/authSlice";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";

function OauthRedirect() {
const location = useLocation();
const navigate = useNavigate();
const dispatch = useDispatch();
const redirectUrl = localStorage.getItem("redirect-url-after-auth") || "/";

useEffect(() => {
const searchParams = new URLSearchParams(location.search);
const token = searchParams.get("token");
if (token) dispatch(setAccessToken(token));

console.log(token);
navigate("/");
console.log(redirectUrl);
navigate(redirectUrl);
}, [location.search]);

return null;
Expand Down
5 changes: 5 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ export default defineConfig({
changeOrigin: true, // host 헤더를 변경합니다.
secure: false, // SSL 설정 (https 프로토콜)
},
"/oauth2/authorization": {
target: "https://synergyy.link",
changeOrigin: true, // host 헤더를 변경합니다.
secure: false, // SSL 설정 (https 프로토콜)
},
},
},
});

0 comments on commit 5608cba

Please sign in to comment.