-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
51 lines (44 loc) · 1.54 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
import {NextResponse, NextRequest} from "next/server";
import {withAuth} from "next-auth/middleware";
import {decode} from "next-auth/jwt";
import {isUserAuthenticated} from "@/src/services/auth/AuthServer";
export default withAuth(
async function middleware(request: NextRequest) {
let cookie = request.cookies.get(process.env.JWT_NAME)
if (cookie === null) {
const signinUrl = `${new URL('/login', request.url)}?error=NotCookiesFound`
return NextResponse.redirect(signinUrl)
} else {
const user = await decode({token: cookie?.value, secret: process.env.JWT_SECRET});
let userIsAuthenticated = false;
if (user !== null) {
const {accessToken} = user;
userIsAuthenticated = await isUserAuthenticated(accessToken);
}
if (userIsAuthenticated) {
return NextResponse.next()
}
}
const signinUrl = `${new URL('/login', request.url)}?error=UserIsNotAuthenticated`;
return NextResponse.redirect(signinUrl)
},
{
callbacks: {
authorized: ({req, token}) => {
if (
req.nextUrl.pathname.startsWith('/protected') &&
token === null
) {
return false
}
return true
}
}
}
)
export const config = {
matcher: [
'/lists/:path*',
'/tasks/:path*'
],
}