-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
170 lines (156 loc) · 4.99 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// const matchAppAdmin = match('/app_admin_preview/(.*)?');
import { match } from 'path-to-regexp';
const onboardingPaths = `/onboarding/(.*)?`;
// Using a middleware to protect pages from unauthorized access
// may seem repetitive however it massively increases the security
// and performance of your application. This is because the middleware
// runs first on the server and can bail out early before the
// server component is even rendered. This means no database queries
// or other expensive operations are run if the user is not authorized.
const unprotectedPagePrefixes = [
`/`,
`/changelog`,
`/feedback(/.*)?`,
`/roadmap`,
`/auth(/.*)?`,
`/confirm-delete-user(/.*)?`,
`/forgot-password(/.*)?`,
`/login(/.*)?`,
`/sign-up(/.*)?`,
`/update-password(/.*)?`,
`/roadmap/`,
`/version2`,
`/blog(/.*)?`,
`/docs(/.*)?`,
`/terms`,
`/waitlist(/.*)?`,
];
export { auth as middleware } from '@/auth';
function isLandingPage(pathname: string) {
return pathname === '/';
}
function isUnprotectedPage(pathname: string) {
return unprotectedPagePrefixes.some((prefix) => {
const matchPath = match(prefix);
return matchPath(pathname);
});
}
function shouldOnboardUser(pathname: string, userId: string) {
/*
const matchOnboarding = match(onboardingPaths);
const isOnboardingRoute = matchOnboarding(pathname);
if (!isUnprotectedPage(pathname) && user && !isOnboardingRoute) {
const userMetadata = authUserMetadataSchema.parse(user.user_metadata);
const {
onboardingHasAcceptedTerms,
onboardingHasCompletedProfile,
onboardingHasCreatedOrganization,
} = userMetadata;
if (
!onboardingHasAcceptedTerms ||
!onboardingHasCompletedProfile ||
!onboardingHasCreatedOrganization
) {
return true;
}
}
return false;
*/
return true;
//TODO figure way to store user metadata (extend user_profile table?)
}
// this middleware refreshes the user's session and must be run
// for any Server Component route that uses `createServerComponentSupabaseClient`
// renamed while moving to auth.js
/*
export async function middleware_NEXTBASE_LEGACY(req: NextRequest) {
const res = NextResponse.next();
const supabase = createMiddlewareClient<Database>(
{ req, res },
{ supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL },
);
if (
process.env.NEXT_PUBLIC_SSO_DOMAIN !== undefined &&
req.nextUrl.pathname === '/'
) {
return NextResponse.redirect(toSiteURL('/auth/sso-verify'));
}
const sessionResponse = await supabase.auth.getSession();
const maybeUser = sessionResponse?.data.session?.user;
if (isLandingPage(req.nextUrl.pathname)) {
if (maybeUser) {
//user is logged in, lets validate session and redirect on success
const user = await supabase.auth.getUser();
if (user.error) {
return NextResponse.redirect(toSiteURL('/login'));
}
return NextResponse.redirect(toSiteURL('/dashboard'));
} else {
//user is not logged in, lets redirect to login
return NextResponse.redirect(toSiteURL('/login'));
}
}
if (!isUnprotectedPage(req.nextUrl.pathname) && maybeUser) {
// user is possibly logged in, but lets validate session
const user = await supabase.auth.getUser();
if (user.error) {
return NextResponse.redirect(toSiteURL('/login'));
}
if (shouldOnboardUser(req.nextUrl.pathname, user.data.user)) {
return NextResponse.redirect(toSiteURL('/onboarding'));
}
}
if (!isUnprotectedPage(req.nextUrl.pathname) && !maybeUser) {
return NextResponse.redirect(toSiteURL('/login'));
}
if (
!req.nextUrl.pathname.startsWith(`/app_admin_preview`) &&
req.nextUrl.pathname.startsWith('/app_admin')
) {
if (
!(
maybeUser &&
'user_role' in maybeUser &&
maybeUser.user_role === 'admin'
)
) {
return NextResponse.redirect(toSiteURL('/dashboard'));
}
}
return res;
}
*/
/*
Middleware for Auth.js - but it doesn't work, edge runtime error. Back to route level
export default auth(async (req) => {
if (!req.auth) {
//not authenticated - redirect to login URL defined by Auth.js
return NextResponse.redirect(toSiteURL('/api/auth/signin'));
} else {
const user = await serverGetLoggedInUser();
if (
shouldOnboardUser(req.nextUrl.pathname, user.id) &&
req.nextUrl.pathname !== '/onboarding'
) {
// authenticated but not onboarded
return NextResponse.redirect(toSiteURL('/onboarding'));
} else {
// authenticated and onboarded - no changes to URL
return NextResponse.next();
}
}
});
*/
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - api (API routes)
* Feel free to modify this pattern to include more paths.
*/
'/((?!_next/static|_next/image|images|assets|logos|mockups|favicon.ico|api|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};