forked from notft/Nasa_space_apps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
38 lines (32 loc) · 1.03 KB
/
middleware.js
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
import { NextResponse } from 'next/server';
import { getCookie } from 'cookies-next';
export async function middleware(req) {
const session = getCookie('session', { req });
if (!session) {
if (req.url.includes('/home')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
try {
const res = await fetch(`http://136.185.21.210:26908/validate?session=${session}`);
const response = await res.json();
if (response.status === 'success') {
if (req.url.includes('/login')) {
return NextResponse.redirect(new URL('/home', req.url));
}
return NextResponse.next();
} else {
if (req.url.includes('/home')) {
return NextResponse.redirect(new URL('/login', req.url));
}
}
} catch (err) {
console.log('Error validating session:', err);
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.redirect(new URL('/login', req.url));
}
export const config = {
matcher: ['/home', '/login'],
};