重构鉴权逻辑,新增中间件刷新令牌,授权接口统一后处理无授权跳转

This commit is contained in:
2025-04-26 14:18:08 +08:00
parent 5c88cd7f32
commit 6db037204c
20 changed files with 303 additions and 318 deletions

38
src/middleware.ts Normal file
View File

@@ -0,0 +1,38 @@
import {NextRequest, NextResponse} from 'next/server'
import {refreshAuth} from '@/actions/auth'
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*(?<!\.svg|\.webp|\.jpg)$)',
],
}
export async function middleware(request: NextRequest) {
console.log('👀 middleware triggered', request.method, request.nextUrl.pathname)
// 记录请求页面
request.headers.set('x-pathname', request.nextUrl.pathname)
// 如果没有访问令牌但有刷新令牌,尝试刷新访问令牌
const match = [
RegExp(`^/admin.*`),
].some(item => item.test(request.nextUrl.pathname))
if (match) {
try {
const accessToken = request.cookies.get('auth_token')
const refreshToken = request.cookies.get('auth_refresh')
if (!accessToken && refreshToken) {
console.log('💡 refresh token')
const token = await refreshAuth()
request.cookies.set('auth_token', token.access_token)
request.cookies.set('auth_refresh', token.refresh_token)
}
}
catch (error) {
return NextResponse.redirect(`${request.nextUrl.origin}/login?redirect=${request.nextUrl.pathname}`)
}
}
return NextResponse.next({request})
}