10 changed files with 105 additions and 76 deletions
@ -0,0 +1,50 @@ |
|||
import jwt from "./Auth/jwt.js" |
|||
import { JWT_SECRET } from "@/middlewares/Auth/auth.js" |
|||
|
|||
/** |
|||
* 路由级权限中间件 |
|||
* 支持:auth: false/try/true/roles |
|||
* 用法:router.get('/api/user', RouteAuth({ auth: true }), handler) |
|||
*/ |
|||
export default function RouteAuth(options = {}) { |
|||
const { auth = true, roles } = options; |
|||
return async (ctx, next) => { |
|||
if (auth === false) return next(); |
|||
|
|||
// 统一用户解析逻辑
|
|||
if (!ctx.state.user) { |
|||
const token = getToken(ctx); |
|||
if (token) { |
|||
try { |
|||
ctx.state.user = jwt.verify(token, JWT_SECRET); |
|||
} catch {} |
|||
} |
|||
} |
|||
|
|||
if (auth === "try") { |
|||
return next(); |
|||
} |
|||
|
|||
if (auth === true) { |
|||
if (!ctx.state.user) { |
|||
ctx.status = 401; |
|||
ctx.body = { success: false, error: "未登录或Token无效" }; |
|||
return; |
|||
} |
|||
if (roles && !roles.includes(ctx.state.user.role)) { |
|||
ctx.status = 403; |
|||
ctx.body = { success: false, error: "无权限" }; |
|||
return; |
|||
} |
|||
return next(); |
|||
} |
|||
|
|||
// 其他自定义模式
|
|||
return next(); |
|||
}; |
|||
} |
|||
|
|||
function getToken(ctx) { |
|||
// 只支持 Authorization: Bearer xxx
|
|||
return ctx.headers["authorization"]?.replace(/^Bearer\s/i, ""); |
|||
} |
Loading…
Reference in new issue