client: change all auth redirects to middleware

This commit is contained in:
Max Leiter 2022-03-21 01:36:31 -07:00
parent abe419daba
commit bf878473af
No known key found for this signature in database
GPG key ID: A3512F2F2F17EBDA
4 changed files with 27 additions and 83 deletions

View file

@ -5,7 +5,6 @@ import { useEffect, useMemo, useState } from "react";
import styles from './header.module.css';
import { useRouter } from "next/router";
import useSignedIn from "../../lib/hooks/use-signed-in";
import Cookies from 'js-cookie'
type Tab = {
name: string
@ -23,7 +22,7 @@ const Header = ({ changeTheme, theme }: DriftProps) => {
const [expanded, setExpanded] = useState<boolean>(false)
const [, setBodyHidden] = useBodyScroll(null, { scrollLayer: true })
const isMobile = useMediaQuery('xs', { match: 'down' })
const { isLoading, isSignedIn, signout } = useSignedIn({ redirectIfNotAuthed: false })
const isSignedIn = useSignedIn()
const [pages, setPages] = useState<Tab[]>([])
useEffect(() => {
@ -42,7 +41,7 @@ const Header = ({ changeTheme, theme }: DriftProps) => {
name: "Home",
href: "/",
icon: <HomeIcon />,
condition: true,
condition: !isSignedIn,
value: "home"
},
{
@ -59,34 +58,9 @@ const Header = ({ changeTheme, theme }: DriftProps) => {
condition: isSignedIn,
value: "mine"
},
// {
// name: "Settings",
// href: "/settings",
// icon: <SettingsIcon />,
// condition: isSignedIn
// },
{
name: "Sign out",
onClick: () => {
if (typeof window !== 'undefined') {
localStorage.clear();
// // send token to API blacklist
// fetch('/api/auth/signout', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// token: Cookies.get("drift-token")
// })
// })
signout();
router.push("/signin");
}
},
href: "#signout",
href: "/signout",
icon: <SignoutIcon />,
condition: isSignedIn,
value: "signout"
@ -126,12 +100,8 @@ const Header = ({ changeTheme, theme }: DriftProps) => {
}
]
if (isLoading) {
return setPages([])
}
setPages(pageList.filter(page => page.condition))
}, [changeTheme, isLoading, isMobile, isSignedIn, router, signout, theme])
}, [changeTheme, isMobile, isSignedIn, theme])
// useEffect(() => {
// setSelectedTab(pages.find((page) => {
@ -161,7 +131,7 @@ const Header = ({ changeTheme, theme }: DriftProps) => {
hideDivider
hideBorder
onChange={onTabChange}>
{!isLoading && pages.map((tab) => {
{pages.map((tab) => {
return <Tabs.Item
font="14px"
label={<>{tab.icon} {tab.name}</>}

View file

@ -1,48 +1,18 @@
import { useRouter } from "next/router";
import { useCallback, useEffect } from "react"
import useSharedState from "./use-shared-state";
import Cookies from 'js-cookie'
import Cookies from "js-cookie";
import { useEffect, useState } from "react";
const useSignedIn = ({ redirectIfNotAuthed = false }: { redirectIfNotAuthed?: boolean }) => {
const [isSignedIn, setSignedIn] = useSharedState('isSignedIn', false)
const [isLoading, setLoading] = useSharedState('isLoading', true)
const signout = useCallback(() => {
Cookies.remove('drift-token')
setSignedIn(false)
}, [setSignedIn])
const router = useRouter();
if (redirectIfNotAuthed && !isLoading && isSignedIn === false) {
router.push('/signin')
}
const useSignedIn = () => {
const [signedIn, setSignedIn] = useState(typeof window === 'undefined' ? false : !!Cookies.get("drift-token"));
useEffect(() => {
async function checkToken() {
const token = Cookies.get('drift-token')
if (token) {
const response = await fetch('/server-api/auth/verify-token', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
if (Cookies.get("drift-token")) {
setSignedIn(true);
} else {
setSignedIn(false);
}
})
if (response.ok) {
setSignedIn(true)
}
}
setLoading(false)
}
setLoading(true)
checkToken()
}, []);
const interval = setInterval(() => {
checkToken()
}, 10000);
return () => clearInterval(interval);
}, [setLoading, setSignedIn])
return { isSignedIn, isLoading, signout }
return signedIn;
}
export default useSignedIn
export default useSignedIn;

View file

@ -18,6 +18,8 @@ export function middleware(req: NextRequest, ev: NextFetchEvent) {
if (signedIn) {
const resp = NextResponse.redirect(getURL(''));
resp.clearCookie('drift-token');
resp.clearCookie('drift-userid');
return resp
}
} else if (pathname === '/') {
@ -30,10 +32,14 @@ export function middleware(req: NextRequest, ev: NextFetchEvent) {
return NextResponse.redirect(getURL(''))
}
// If you're signed in we redirect the sign in page to the home page (which is the new page)
} else if (pathname === '/signin') {
} else if (pathname === '/signin' || pathname === '/signup') {
if (signedIn) {
return NextResponse.redirect(getURL(''))
}
} else if (pathname === '/new') {
if (!signedIn) {
return NextResponse.redirect(getURL(''))
}
}
return NextResponse.next()

View file

@ -7,12 +7,10 @@ import { ThemeProps } from './_app'
import { useRouter } from 'next/router'
import PageSeo from '@components/page-seo'
const Home = ({ theme, changeTheme }: ThemeProps) => {
const New = ({ theme, changeTheme }: ThemeProps) => {
const router = useRouter()
const { isSignedIn, isLoading } = useSignedIn({ redirectIfNotAuthed: true })
if (!isSignedIn && !isLoading) {
router.push("/signin")
}
const isSignedIn = useSignedIn()
return (
<Page className={styles.container} width="100%">
<PageSeo title="Drift - New" />
@ -28,4 +26,4 @@ const Home = ({ theme, changeTheme }: ThemeProps) => {
)
}
export default Home
export default New