-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
48 lines (44 loc) · 1.37 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { NextResponse, type NextRequest } from "next/server"
import { getProfile } from "@/lib/hn-web-fetcher"
import { COOKIE_NAME_SESSION, parseSession } from "@/lib/session"
export async function middleware(request: NextRequest) {
const { pathname, searchParams } = request.nextUrl
let sessionValue = request.cookies.get(COOKIE_NAME_SESSION)?.value
const liveSession = await validateSession(sessionValue)
if (isAuthPath(pathname)) {
if (liveSession) {
return NextResponse.redirect(new URL(`/`, request.url))
}
} else {
if (!liveSession) {
const response = NextResponse.redirect(
new URL(
`/login?goto=${pathname}?${searchParams.toString()}`,
request.url
)
)
let allCookies = request.cookies.getAll()
if (allCookies && allCookies.length > 0) {
allCookies.forEach((c) => {
response.cookies.delete(c.name)
})
}
return response
}
}
return NextResponse.next()
}
export const config = {
matcher: ["/signup"],
}
function isAuthPath(pathname: string) {
return ["/login", "/signup"].includes(pathname)
}
async function validateSession(sessionValue: string | undefined) {
if (!sessionValue) {
return false
}
const { userCookieVal, acct } = parseSession(sessionValue)
const profile = await getProfile(acct, userCookieVal)
return profile && profile.authCode
}