Skip to content

Commit 14429da

Browse files
author
pedro
committed
feat:添加统一异常的token刷新机制
1 parent f0d82f2 commit 14429da

3 files changed

Lines changed: 44 additions & 2 deletions

File tree

lib/exception.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,3 +261,24 @@ export class MethodNotAllowed extends HttpException {
261261
}
262262
}
263263
}
264+
265+
export class RefreshException extends HttpException {
266+
public code = 401;
267+
public msg = "refresh token 获取失败";
268+
public errorCode = 10100;
269+
270+
constructor(ex?: Exception) {
271+
super();
272+
if (ex && ex.code) {
273+
assert(isInteger(ex.code));
274+
this.code = ex.code;
275+
}
276+
if (ex && ex.msg) {
277+
this.msg = ex.msg;
278+
}
279+
if (ex && ex.errorCode) {
280+
assert(isInteger(ex.errorCode));
281+
this.errorCode = ex.errorCode;
282+
}
283+
}
284+
}

lib/jwt.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import {
33
ExpiredTokenException,
44
InvalidTokenException,
55
AuthFailed,
6-
NotFound
6+
NotFound,
7+
RefreshException
78
} from "./exception";
89
import Application from "koa";
910
import { RouterContext } from "koa-router";
@@ -180,6 +181,26 @@ async function refreshTokenRequired(
180181
}
181182
}
182183

184+
/**
185+
* 守卫函数,用户刷新令牌,统一异常
186+
*/
187+
async function refreshTokenRequiredWithUnifyException(
188+
ctx: RouterContext,
189+
next: () => Promise<any>
190+
) {
191+
// 添加access 和 refresh 的标识位
192+
if (ctx.request.method !== "OPTIONS") {
193+
try {
194+
await parseHeader(ctx, TokenType.REFRESH);
195+
} catch (error) {
196+
throw new RefreshException();
197+
}
198+
await next();
199+
} else {
200+
await next();
201+
}
202+
}
203+
183204
/**
184205
* 守卫函数,用于权限组鉴权
185206
*/

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "lin-mizar",
3-
"version": "0.0.1-alpha.9",
3+
"version": "0.0.1-alpha.10",
44
"description": "The core library of Lin CMS",
55
"main": "lin/index.js",
66
"scripts": {

0 commit comments

Comments
 (0)