-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
110 lines (98 loc) · 2.13 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import {
NextResponse,
NextRequest
} from "next/server";
import { createClient } from "@/app/lib/supabase/middleware";
export async function middleware(
request: NextRequest
) {
const {
supabase,
response
} = createClient(request);
const url = request.nextUrl;
const path = new URL(request.url).pathname;
const publicUrls = [
"/login",
"/reset-password",
"/dashboard/create",
"/dashboard/cards",
"/dashboard/cards/[slug]",
];
const isPublic = publicUrls.some(publicUrl =>
path === publicUrl ||
path.startsWith(publicUrl.replace('[slug]', ''))
);
const isPublicUserProfile = path
.startsWith('/dashboard/profile/') &&
path !== '/dashboard/profile';
if (isPublic || isPublicUserProfile) {
return response;
}
const {
data: {
user: session
}
} = await supabase
.auth
.getUser();
if (
!session &&
path === "/dashboard/profile"
) {
// Redirect to login if user is not logged in
return NextResponse
.redirect(
new URL(
"/login",
request.url
)
);
} else if (
!session &&
(
path.toLowerCase().includes("credits") ||
path.toLowerCase().includes("contact")
)
) {
// Redirect to login if user is not logged in
return NextResponse
.redirect(
new URL(
"/login",
request.url
)
);
}
if (session && (
path === "/" ||
path === "/login"
)) {
return NextResponse
.redirect(new URL(
"/dashboard",
request.url
)
);
}
// Redirect to /credits after Stripe checkout
if (
session &&
url.searchParams.get("redirect") === "credits" &&
(
url.searchParams.get("success") === "true" ||
url.searchParams.get("canceled") === "true"
)
) {
const destination = new URL(
"/dashboard/credits",
request.url
);
destination.search = url.search;
return NextResponse.redirect(destination);
}
return response;
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|images|favicon.ico|login).*)"],
};