/
jwt.ts
420 lines (396 loc) · 10.2 KB
/
jwt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import jwtGenerator, {
TokenExpiredError,
VerifyOptions,
SignOptions
} from 'jsonwebtoken';
import {
ExpiredTokenException,
InvalidTokenException,
AuthFailed,
NotFound,
RefreshException
} from './exception';
import Application from 'koa';
import { RouterContext } from 'koa-router';
import { get } from 'lodash';
import { routeMetaInfo } from './core';
import { TokenType } from './enums';
import { config } from './config';
/**
* 令牌类,提供令牌的生成和解析功能
*
* ```js
* const jwt = new Token(
* config.getItem("secret"),
* config.getItem("accessExp"),
* config.getItem("refreshExp")
* );
* ```
*/
export class Token {
/**
* 令牌的secret值,用于令牌的加密
*/
public secret: string | undefined;
/**
* access token 默认的过期时间
*/
public accessExp: number = 60 * 60; // 1h;
/**
* refresh token 默认的过期时间
*/
public refreshExp: number = 60 * 60 * 24 * 30 * 3; // 3 months
/**
* 构造函数
* @param secret 牌的secret值
* @param accessExp access token 过期时间
* @param refreshExp refresh token 过期时间
*/
constructor(secret?: string, accessExp?: number, refreshExp?: number) {
secret && (this.secret = secret);
refreshExp && (this.refreshExp = refreshExp);
accessExp && (this.accessExp = accessExp);
}
/**
* 挂载到 ctx 上
*/
public initApp(
app: Application,
secret?: string,
accessExp?: number,
refreshExp?: number
) {
// 将jwt实例挂到app的context上
app.context.jwt = this;
secret && (this.secret = secret);
refreshExp && (this.refreshExp = refreshExp);
accessExp && (this.accessExp = accessExp);
}
/**
* 生成access_token
* @param identity 标识位
*/
public createAccessToken(identity: string | number) {
if (!this.secret) {
throw new Error('密匙不可为空');
}
let exp: number = Math.floor(Date.now() / 1000) + this.accessExp;
return jwtGenerator.sign(
{
exp: exp,
identity: identity,
scope: 'lin',
type: TokenType.ACCESS
},
this.secret
);
}
/**
* 生成refresh_token
* @param identity 标识位
*/
public createRefreshToken(identity: string | number) {
if (!this.secret) {
throw new Error('密匙不可为空');
}
let exp: number = Math.floor(Date.now() / 1000) + this.refreshExp;
return jwtGenerator.sign(
{
exp: exp,
identity: identity,
scope: 'lin',
type: TokenType.REFRESH
},
this.secret
);
}
/**
* verifyToken 验证token
* 若过期,抛出ExpiredTokenException
* 若失效,抛出InvalidTokenException
*
* @param token 令牌
*/
public verifyToken(token: string) {
if (!this.secret) {
throw new Error('密匙不可为空');
}
// NotBeforeError
// TokenExpiredError
let decode;
try {
decode = jwtGenerator.verify(token, this.secret);
} catch (error) {
if (error instanceof TokenExpiredError) {
throw new ExpiredTokenException();
} else {
throw new InvalidTokenException();
}
}
return decode;
}
}
/**
* jwt 的实例
*/
const jwt = new Token(
config.getItem('secret'),
config.getItem('accessExp'),
config.getItem('refreshExp')
);
/**
* 生成access token
* @param payload 负载,支持 string 和 object
* @param options 参数
*/
export function createAccessToken(
payload: string | object,
options?: SignOptions
) {
// type: TokenType.REFRESH
let exp: number = Math.floor(Date.now() / 1000) + jwt.accessExp;
if (typeof payload === 'string') {
return jwtGenerator.sign(
{ indentify: payload, type: TokenType.ACCESS, exp: jwt.accessExp },
jwt.secret!,
options
);
} else {
return jwtGenerator.sign(
{ ...payload, type: TokenType.ACCESS, exp: exp },
jwt.secret!,
options
);
}
}
/**
* 生成refresh token
* @param payload 负载,支持 string 和 object
* @param options 参数
*/
export function createRefreshToken(
payload: string | object,
options?: SignOptions
) {
let exp: number = Math.floor(Date.now() / 1000) + jwt.refreshExp;
// type: TokenType.REFRESH
if (typeof payload === 'string') {
return jwtGenerator.sign(
{ indentify: payload, type: TokenType.REFRESH, exp: jwt.refreshExp },
jwt.secret!,
options
);
} else {
return jwtGenerator.sign(
{ ...payload, type: TokenType.REFRESH, exp: exp },
jwt.secret!,
options
);
}
}
/**
* 验证 access token
* @param token 令牌
* @param options 选项
*/
export function verifyAccessToken(token: string, options?: VerifyOptions) {
let decode;
try {
decode = jwtGenerator.verify(token, jwt.secret!, options);
} catch (error) {
if (error instanceof TokenExpiredError) {
throw new ExpiredTokenException();
} else {
throw new InvalidTokenException();
}
}
if (!decode['type'] || decode['type'] !== TokenType.ACCESS) {
throw new InvalidTokenException({ msg: '令牌类型错误' });
}
return decode;
}
/**
* 验证 refresh token
* @param token 令牌
* @param options 选项
*/
export function verifyRefreshToken(token: string, options?: VerifyOptions) {
let decode;
try {
decode = jwtGenerator.verify(token, jwt.secret!, options);
} catch (error) {
if (error instanceof TokenExpiredError) {
throw new ExpiredTokenException();
} else {
throw new InvalidTokenException();
}
}
if (!decode['type'] || decode['type'] !== TokenType.REFRESH) {
throw new InvalidTokenException({ msg: '令牌类型错误' });
}
return decode;
}
/**
* 颁发令牌
* @param user 用户
*/
function getTokens(user) {
const accessToken = jwt.createAccessToken(user.id);
const refreshToken = jwt.createRefreshToken(user.id);
return { accessToken, refreshToken };
}
/**
* 解析请求头
* @param ctx koa 的context
* @param type 令牌的类型
*/
async function parseHeader(ctx: RouterContext, type = TokenType.ACCESS) {
// 此处借鉴了koa-jwt
if (!ctx.header || !ctx.header.authorization) {
ctx.throw(new AuthFailed({ msg: '认证失败,请检查请求令牌是否正确' }));
}
const parts = ctx.header.authorization.split(' ');
if (parts.length === 2) {
// Bearer 字段
const scheme = parts[0];
// token 字段
const token = parts[1];
if (/^Bearer$/i.test(scheme)) {
const obj = ctx.jwt.verifyToken(token);
if (!get(obj, 'type') || get(obj, 'type') !== type) {
ctx.throw(new AuthFailed({ msg: '请使用正确类型的令牌' }));
}
if (!get(obj, 'scope') || get(obj, 'scope') !== 'lin') {
ctx.throw(new AuthFailed({ msg: '请使用正确作用域的令牌' }));
}
const user = await ctx.manager.userModel.findByPk(get(obj, 'identity'));
if (!user) {
ctx.throw(new NotFound({ msg: '用户不存在' }));
}
// 将user挂在ctx上
ctx.currentUser = user;
}
} else {
ctx.throw(new AuthFailed());
}
}
function checkUserIsActive(user) {
if (!user || !user.isActive) {
throw new AuthFailed({ msg: '您目前处于未激活状态,请联系超级管理员' });
}
}
/**
* 守卫函数,用户登陆即可访问
*/
async function loginRequired(ctx: RouterContext, next: () => Promise<any>) {
if (ctx.request.method !== 'OPTIONS') {
await parseHeader(ctx);
// 一定要await,否则这个守卫函数没有作用
// 用户处于未激活状态
const currentUser = ctx.currentUser;
checkUserIsActive(currentUser);
await next();
} else {
await next();
}
}
/**
* 守卫函数,用户刷新令牌
*/
async function refreshTokenRequired(
ctx: RouterContext,
next: () => Promise<any>
) {
// 添加access 和 refresh 的标识位
if (ctx.request.method !== 'OPTIONS') {
await parseHeader(ctx, TokenType.REFRESH);
await next();
} else {
await next();
}
}
/**
* 守卫函数,用户刷新令牌,统一异常
*/
async function refreshTokenRequiredWithUnifyException(
ctx: RouterContext,
next: () => Promise<any>
) {
// 添加access 和 refresh 的标识位
if (ctx.request.method !== 'OPTIONS') {
try {
await parseHeader(ctx, TokenType.REFRESH);
} catch (error) {
throw new RefreshException();
}
await next();
} else {
await next();
}
}
/**
* 守卫函数,用于权限组鉴权
*/
async function groupRequired(ctx: RouterContext, next: () => Promise<any>) {
if (ctx.request.method !== 'OPTIONS') {
await parseHeader(ctx);
const currentUser = ctx.currentUser;
// 用户处于未激活状态
checkUserIsActive(currentUser);
// 超级管理员
if (currentUser && currentUser.isAdmin) {
await next();
} else {
const groupId = currentUser.group_id;
if (!groupId) {
throw new AuthFailed({
msg: '您还不属于任何权限组,请联系超级管理员获得权限'
});
}
if (ctx.matched) {
const routeName = ctx._matchedRouteName || ctx.routerName;
const endpoint = `${ctx.method} ${routeName}`;
const { auth, module } = routeMetaInfo.get(endpoint);
const item = await ctx.manager.authModel.findOne({
where: { auth, module, group_id: groupId }
});
// console.log(item);
if (item) {
await next();
} else {
throw new AuthFailed({ msg: '权限不够,请联系超级管理员获得权限' });
}
} else {
throw new AuthFailed({ msg: '权限不够,请联系超级管理员获得权限' });
}
}
} else {
await next();
}
}
/**
* 守卫函数,非超级管理员不可访问
*/
async function adminRequired(ctx: RouterContext, next: () => Promise<any>) {
if (ctx.request.method !== 'OPTIONS') {
await parseHeader(ctx);
const currentUser = ctx.currentUser;
if (currentUser && currentUser.isAdmin) {
await next();
} else {
throw new AuthFailed({ msg: '只有超级管理员可操作' });
}
} else {
await next();
}
}
export {
jwt,
getTokens,
loginRequired,
groupRequired,
adminRequired,
refreshTokenRequired,
refreshTokenRequiredWithUnifyException,
checkUserIsActive
};