-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
56 lines (46 loc) · 1.36 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
// import { auth } from "./auth";
import {
apiRoutes,
authRoutes,
publicRoutes,
DEF_LOGIN_REDIRECT,
} from "@/routes";
import NextAuth from "next-auth";
import authConfig from "@/auth.config";
import { NextResponse } from "next/server";
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const { nextUrl } = req;
const isLogged = !!req.auth;
const isApi = nextUrl.pathname.startsWith(apiRoutes);
const checkIsPublic = (url: string) => {
return publicRoutes.some((item) => {
if (item.includes("*")) {
const regex = new RegExp(item.replace("*", ".*"));
return url.match(regex);
} else {
return item.includes(url);
}
});
};
const isPublic = checkIsPublic(nextUrl.pathname);
const isAuth = authRoutes.includes(nextUrl.pathname);
if (isApi) return null;
if (isAuth) {
if (isLogged)
return Response.redirect(new URL(DEF_LOGIN_REDIRECT, nextUrl));
return null;
}
if (!isLogged && !isPublic) {
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) callbackUrl += nextUrl.search;
const encodedCallbackUrl = `/hws/login?callbackUrl=${encodeURIComponent(
callbackUrl
)}`;
return Response.redirect(new URL(encodedCallbackUrl, nextUrl));
}
return null;
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/(api|trpc)(.*)"],
};