8 changed files with 125 additions and 75 deletions
@ -0,0 +1,45 @@ |
|||||
|
import jwt from "@/middlewares/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 } = 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 |
||||
|
} |
||||
|
return next() |
||||
|
} |
||||
|
|
||||
|
// 其他自定义模式
|
||||
|
return next() |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function getToken(ctx) { |
||||
|
// 只支持 Authorization: Bearer xxx
|
||||
|
return ctx.headers["authorization"]?.replace(/^Bearer\s/i, "") |
||||
|
} |
Loading…
Reference in new issue