-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathmiddleware.ts
69 lines (58 loc) · 1.69 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { NextRequest, NextResponse } from "next/server"
import { withAuth } from "next-auth/middleware"
import createIntlMiddleware from "next-intl/middleware"
const locales = ["en", "so"]
const publicPages = [
"/",
"/login",
"/signup",
"/forget",
"/policies/terms_of_use",
"/policies/privacy_policy",
]
const intlMiddleware = createIntlMiddleware({
locales,
defaultLocale: "en",
})
const authMiddleware = withAuth((req) => intlMiddleware(req), {
callbacks: {
authorized: ({ req, token }) => {
const path = req.nextUrl.pathname
// if user is logged in, redirect to /learn
if (path.startsWith("/admin")) {
return token?.role === "admin"
}
if (path.startsWith("/learn")) {
return token !== null
}
// By default return true only if the token is not null
// (this forces the users to be signed in to access the page)
return token !== null
},
},
pages: {
signIn: "/login",
},
})
export default function middleware(req: NextRequest) {
const { origin } = req.nextUrl
const publicPathnameRegex = RegExp(
`^(/(${locales.join("|")}))?(${publicPages.join("|")})?/?$`,
"i",
)
const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname)
if (isPublicPage) {
// if trying to access public page and user is logged in, redirect to /learn
if (req.cookies.has("next-auth.session-token")) {
// redirect to /learn
return NextResponse.rewrite(`${origin}/en/learn`)
}
return intlMiddleware(req)
} else {
return (authMiddleware as any)(req)
}
}
export const config = {
// Skip all paths that should not be internationalized
matcher: ["/((?!api|_next|.*\\..*).*)"],
}