Skip to content

Commit 9d60a6b

Browse files
committed
refactor(middleware): utiliza getToken para autenticação e controle de acesso por rota
1 parent 0a01159 commit 9d60a6b

1 file changed

Lines changed: 18 additions & 27 deletions

File tree

Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,28 @@
1-
import { withAuth } from 'next-auth/middleware';
2-
import { NextResponse } from 'next/server';
1+
import { NextResponse } from "next/server";
2+
import type { NextRequest } from "next/server";
3+
import { getToken } from "next-auth/jwt";
34

4-
export default withAuth(
5-
function middleware(req) {
6-
const url = req.nextUrl.pathname;
7-
console.log(`[ACESSO] ${url} - ${new Date().toISOString()}`);
5+
export async function middleware(req: NextRequest) {
6+
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
87

9-
return NextResponse.next();
10-
},
11-
{
12-
callbacks: {
13-
authorized: ({ token }) => {
14-
if (!token) return false;
8+
const url = req.nextUrl.pathname;
9+
console.log(`[ACESSO] ${url} - ${new Date().toISOString()}`);
1510

16-
// Se for rota de admin, exige role 'admin'
17-
if (typeof token === 'object' && token.role && token.role === 'admin') {
18-
return true;
19-
}
20-
21-
if (token && token.email) {
22-
return true;
23-
}
11+
if (!token) {
12+
return NextResponse.redirect(new URL("/", req.url));
13+
}
2414

25-
return false;
26-
},
27-
},
15+
if (url.startsWith("/admin") && token?.role !== "admin") {
16+
return NextResponse.redirect(new URL("/dashboard", req.url));
2817
}
29-
);
18+
19+
return NextResponse.next();
20+
}
3021

3122
export const config = {
3223
matcher: [
33-
'/dashboard/:path*',
34-
'/admin/:path*',
35-
'/encurtar/:path*',
24+
"/dashboard/:path*",
25+
"/admin/:path*",
26+
"/encurtar/:path*",
3627
],
3728
};

0 commit comments

Comments
 (0)