feat: 添加JWKS管理功能,支持基于用户token创建新token
This commit is contained in:
@@ -2,7 +2,7 @@ import { nanoid, customAlphabet } from 'nanoid';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
import { useContextKey } from '@kevisual/context';
|
||||
import { Redis } from 'ioredis';
|
||||
import { oauth } from '../oauth/auth.ts';
|
||||
import { oauth, jwksManager } from '../oauth/auth.ts';
|
||||
import { cryptPwd } from '../oauth/salt.ts';
|
||||
import { OauthUser } from '../oauth/oauth.ts';
|
||||
import { db } from '../../modules/db.ts';
|
||||
@@ -36,6 +36,9 @@ const userSecretsTable = cfUserSecrets;
|
||||
|
||||
export const redis = useContextKey<Redis>('redis');
|
||||
|
||||
type TokenOptions = {
|
||||
expire?: number; // 过期时间,单位秒
|
||||
}
|
||||
/**
|
||||
* 用户模型,使用 Drizzle ORM
|
||||
*/
|
||||
@@ -69,7 +72,7 @@ export class User {
|
||||
* @param uid
|
||||
* @returns
|
||||
*/
|
||||
async createToken(uid?: string, loginType?: 'default' | 'plugin' | 'month' | 'season' | 'year' | 'week', expand: any = {}) {
|
||||
async createToken(uid?: string, loginType?: 'default' | 'plugin' | 'month' | 'season' | 'year' | 'week' | 'jwks', opts: TokenOptions = {}) {
|
||||
const { id, username, type } = this;
|
||||
const oauthUser: OauthUser = {
|
||||
id,
|
||||
@@ -81,7 +84,21 @@ export class User {
|
||||
if (uid) {
|
||||
oauthUser.orgId = id;
|
||||
}
|
||||
const token = await oauth.generateToken(oauthUser, { type: loginType, hasRefreshToken: true, ...expand });
|
||||
if (loginType === 'jwks') {
|
||||
const accessToken = await jwksManager.sign({
|
||||
sub: 'user:' + this.id,
|
||||
name: this.username,
|
||||
});
|
||||
const expiresIn = opts?.expire ?? 2 * 3600; // 2 hours
|
||||
return {
|
||||
accessToken: accessToken,
|
||||
refreshToken: null,
|
||||
token: accessToken,
|
||||
refreshTokenExpiresIn: null,
|
||||
accessTokenExpiresIn: expiresIn
|
||||
};
|
||||
}
|
||||
const token = await oauth.generateToken(oauthUser, { type: loginType, hasRefreshToken: true, ...opts });
|
||||
return {
|
||||
accessToken: token.accessToken,
|
||||
refreshToken: token.refreshToken,
|
||||
|
||||
Reference in New Issue
Block a user