-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
59 lines (51 loc) · 1.55 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(request: NextRequest) {
let session = null;
try {
session = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
} catch (error) {
console.log(error);
return {
hasError: true,
message: "Error no controlado, hable con el administrador",
};
}
if (!session) {
if (request.nextUrl.pathname.startsWith("/api/admin")) {
return NextResponse.redirect(
new URL("/api/auth/unauthorized", request.url)
);
}
const requestedPage = request.nextUrl.pathname;
const url = request.nextUrl.clone();
url.pathname = `/auth/login`;
url.search = `p=${requestedPage}`;
return NextResponse.redirect(url);
}
//TODO: analizar los roles
const validRoles = ["admin", "super-user", "SEO"];
if (request.nextUrl.pathname.startsWith("/admin")) {
if (!validRoles.includes(session.user.role)) {
const url = request.nextUrl.clone();
url.pathname = "/";
return NextResponse.redirect(url);
}
}
if (request.nextUrl.pathname.startsWith("/api/admin")) {
if (!validRoles.includes(session.user.role)) {
return NextResponse.redirect(
new URL("/api/auth/unauthorized", request.url)
);
}
}
return NextResponse.next();
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ["/checkout/:path*", "/admin/:path*", "/api/admin/:path*"],
};