-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
50 lines (44 loc) · 1.39 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
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(req) {
const isAuth = !!req.nextauth.token;
const isLoginPage = req.nextUrl.pathname.startsWith('/login');
const isRegisterPage = req.nextUrl.pathname.startsWith('/register');
const isProblemPage= req.nextUrl.pathname.startsWith('/problems');
const isHackathonPage= req.nextUrl.pathname.startsWith('/hackathon');
const isApiAuthRoute = req.nextUrl.pathname.startsWith('/api/auth');
// Allow authentication API endpoints
if (isApiAuthRoute) {
return NextResponse.next();
}
if( isLoginPage || isRegisterPage || isProblemPage || isHackathonPage){
return NextResponse.redirect(new URL('/', req.url))
}
// Redirect authenticated users from login or register to hackathon page
if (isAuth && (isLoginPage || isRegisterPage)) {
return NextResponse.redirect(new URL('/hackathon', req.url));
}
// Redirect unauthenticated users to login
if (!isAuth && !isLoginPage) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
},
{
callbacks: {
authorized: ({ token }) => {
return true;
},
},
}
);
export const config = {
matcher: [
'/login',
'/register',
'/problems',
'/hackathon',
'/api/:path*'
]
};