perf: 支持oidc单点登录

This commit is contained in:
xiaojunnuo
2025-11-27 01:59:22 +08:00
parent c7b298c46f
commit ec75afbc44
25 changed files with 633 additions and 103 deletions
@@ -0,0 +1,14 @@
CREATE TABLE "cd_oauth_bound"
(
"id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"user_id" integer NOT NULL,
"type" varchar(512) NOT NULL,
"open_id" varchar(512) NOT NULL,
"create_time" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
"update_time" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP)
);
CREATE INDEX "index_oauth_bound_user_id" ON "cd_oauth_bound" ("user_id");
CREATE INDEX "index_oauth_bound_open_id" ON "cd_oauth_bound" ("open_id");
@@ -0,0 +1,153 @@
import { addonRegistry, BaseController, Constants, SysInstallInfo, SysSettingsService } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { AddonGetterService } from "../../../modules/pipeline/service/addon-getter-service.js";
import { IOauthProvider } from "../../../plugins/plugin-oauth/api.js";
import { LoginService } from "../../../modules/login/service/login-service.js";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { UserEntity } from "../../../modules/sys/authority/entity/user.js";
import { simpleNanoId } from "@certd/basic";
import { OauthBoundService } from "../../../modules/login/service/oauth-bound-service.js";
import { OauthBoundEntity } from "../../../modules/login/entity/oauth-bound.js";
/**
*/
@Provide()
@Controller('/api/oauth')
export class ConnectController extends BaseController {
@Inject()
addonGetterService: AddonGetterService;
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
loginService: LoginService;
@Inject()
codeService: CodeService;
@Inject()
userService: UserService;
@Inject()
oauthBoundService: OauthBoundService;
private async getOauthProvider(type: string) {
const publicSettings = await this.sysSettingsService.getPublicSettings()
if (!publicSettings?.oauthEnabled) {
throw new Error("OAuth功能未启用");
}
const setting = publicSettings?.oauthProviders?.[type || ""]
if (!setting) {
throw new Error(`未配置该OAuth类型:${type}`);
}
const addon = await this.addonGetterService.getAddonById(setting.addonId, true, 0);
if (!addon) {
throw new Error("初始化OAuth插件失败");
}
return addon as IOauthProvider;
}
@Post('/login', { summary: Constants.per.guest })
public async login(@Body(ALL) body: { type: string }) {
const addon = await this.getOauthProvider(body.type);
const installInfo = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo);
const bindUrl = installInfo?.bindUrl || "";
//构造登录url
const redirectUrl = `${bindUrl}#/oauth/callback/${body.type}`;
const loginUrl = await addon.buildLoginUrl({ redirectUri: redirectUrl });
return this.ok({loginUrl});
}
@Post('/callback', { summary: Constants.per.guest })
public async callback(@Body(ALL) body: any) {
//处理登录回调
const addon = await this.getOauthProvider(body.type);
const tokenRes = await addon.onCallback({
code: body.code,
state: body.state,
});
const userInfo = tokenRes.userInfo;
const openId = userInfo.openId;
const loginRes = await this.loginService.loginByOpenId({ openId, type: body.type });
if (loginRes == null) {
// 用户还未绑定,让用户选择绑定已有账号还是自动注册新账号
const validationCode = await this.codeService.setValidationValue({
type: body.type,
userInfo,
});
return this.ok({
bindRequired: true,
validationCode,
});
}
//返回登录成功token
return this.ok(loginRes);
}
@Post('/bind', { summary: Constants.per.loginOnly })
public async bind(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
const validationValue = this.codeService.getValidationValue(body.validationCode);
if (!validationValue) {
throw new Error("校验码错误");
}
await this.oauthBoundService.bind({
userId,
type: body.type,
openId: validationValue.openId,
});
return this.ok(1);
}
@Post('/autoRegister', { summary: Constants.per.guest })
public async autoRegister(@Body(ALL) body: { validationCode: string, type: string }) {
const validationValue = this.codeService.getValidationValue(body.validationCode);
if (!validationValue) {
throw new Error("第三方认证授权已过期");
}
const userInfo = validationValue.userInfo;
const oauthType = validationValue.type;
let newUser = new UserEntity()
newUser.username = `${oauthType}:_${userInfo.nickName}_${simpleNanoId(6)}`;
newUser.avatar = userInfo.avatar;
newUser.nickName = userInfo.nickName;
newUser = await this.userService.register("username", newUser, async (txManager) => {
const oauthBound : OauthBoundEntity = new OauthBoundEntity()
oauthBound.userId = newUser.id;
oauthBound.type = oauthType;
oauthBound.openId = userInfo.openId;
await txManager.save(oauthBound);
});
const loginRes = await this.loginService.generateToken(newUser);
return this.ok(loginRes);
}
@Post('/unbind', { summary: Constants.per.loginOnly })
public async unbind(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
await this.oauthBoundService.unbind({
userId,
type: body.type,
});
return this.ok(1);
}
@Post('/providers', { summary: Constants.per.guest })
public async providers() {
const list = addonRegistry.getDefineList("oauth");
return this.ok(list);
}
}
@@ -1,67 +0,0 @@
import { BaseController, Constants, SysInstallInfo, SysOauthSetting, SysSettingsService } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { AddonGetterService } from "../../../modules/pipeline/service/addon-getter-service.js";
import { IOauthProvider } from "../../../plugins/plugin-oauth/api.js";
/**
*/
@Provide()
@Controller('/api/connect')
export class ConnectController extends BaseController {
@Inject()
addonGetterService: AddonGetterService;
@Inject()
sysSettingsService: SysSettingsService;
private async getOauthProvider(type:string){
const oauthSetting = await this.sysSettingsService.getSetting<SysOauthSetting>(SysOauthSetting);
const setting = oauthSetting?.oauths?.[type||""]
if (!setting) {
throw new Error(`未配置该OAuth类型:${type}`);
}
const addon = await this.addonGetterService.getAddonById(setting.addonId, true, 0);
if(!addon) {
throw new Error("初始化OAuth插件失败");
}
return addon as IOauthProvider;
}
@Post('/login', { summary: Constants.per.guest })
public async login(@Body(ALL) body: {type:string}) {
const addon = await this.getOauthProvider(body.type);
const installInfo = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo);
const bindUrl = installInfo?.bindUrl || "";
//构造登录url
const redirectUrl = `${bindUrl}#/auth/callback/${body.type}`;
const loginUrl = await addon.buildLoginUrl({ redirectUri: redirectUrl});
return this.ok(loginUrl);
}
@Post('/callback', { summary: Constants.per.guest })
public async callback(@Body(ALL) body: any) {
//处理登录回调
const addon = await this.getOauthProvider(body.type);
const tokenRes = await addon.onCallback({
code: body.code,
redirectUri: body.redirectUri,
state: body.state,
});
const userInfo = tokenRes.userInfo;
const openId = userInfo.openId;
return this.ok(openId);
}
@Post('/bind', { summary: Constants.per.guest })
public async bind(@Body(ALL) body: any) {
// const autoRegister = body.autoRegister || false;
// const bindInfo = body.bind || {};
//处理登录回调
return this.ok(1);
}
}
@@ -1,5 +1,6 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import {
addonRegistry,
CrudController,
SysPrivateSettings,
SysPublicSettings,
@@ -199,4 +200,10 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
await this.codeService.checkCaptcha(body)
return this.ok({});
}
@Post('/oauth/providers', { summary: 'sys:settings:view' })
async oauthProviders() {
const list = await addonRegistry.getDefineList("oauth");
return this.ok(list);
}
}
@@ -1,5 +1,5 @@
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { cache, isDev, randomNumber } from '@certd/basic';
import { cache, isDev, randomNumber, simpleNanoId } from '@certd/basic';
import { SysSettingsService, SysSiteInfo } from '@certd/lib-server';
import { SmsServiceFactory } from '../sms/factory.js';
import { ISmsService } from '../sms/api.js';
@@ -188,4 +188,20 @@ export class CodeService {
`
);
}
buildValidationValueKey(code:string) {
return `validationValue:${code}`;
}
setValidationValue(value:any) {
const randomCode = simpleNanoId(12);
const key = this.buildValidationValueKey(randomCode);
cache.set(key, value, {
ttl: 5 * 60 * 1000, //5分钟
});
return randomCode;
}
getValidationValue(code:string) {
return cache.get(this.buildValidationValueKey(code));
}
}
@@ -1,7 +1,7 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity('cd_oauth_bind')
export class OauthBindEntity {
@Entity('cd_oauth_bound')
export class OauthBoundEntity {
@PrimaryGeneratedColumn()
id: number;
@@ -17,9 +17,9 @@ import { TwoFactorService } from "../../mine/service/two-factor-service.js";
import { UserSettingsService } from "../../mine/service/user-settings-service.js";
import { isPlus } from "@certd/plus-core";
import { AddonService } from "@certd/lib-server";
import { OauthBoundService } from "./oauth-bound-service.js";
/**
* 系统用户
*/
@Provide()
@Scope(ScopeEnum.Request, {allowDowngrade: true})
@@ -42,6 +42,8 @@ export class LoginService {
twoFactorService: TwoFactorService;
@Inject()
addonService: AddonService;
@Inject()
oauthBoundService: OauthBoundService;
checkIsBlocked(username: string) {
const blockDurationKey = `login_block_duration:${username}`;
@@ -204,6 +206,10 @@ export class LoginService {
* @param roleIds
*/
async generateToken(user: UserEntity) {
if (user.status === 0) {
throw new CommonException('用户已被禁用');
}
const roleIds = await this.roleService.getRoleIdsByUserId(user.id);
const tokenInfo = {
username: user.username,
@@ -224,4 +230,20 @@ export class LoginService {
expire,
};
}
async loginByOpenId(req: { openId: string, type:string }) {
const {openId, type} = req;
const oauthBound = await this.oauthBoundService.findOne({
where:{openId, type}
});
if (oauthBound == null) {
return null
}
const info = await this.userService.findOne({id: oauthBound.userId});
if (info == null) {
throw new CommonException('用户不存在');
}
return this.generateToken(info);
}
}
@@ -0,0 +1,74 @@
import { BaseService, SysSettingsService } from "@certd/lib-server";
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { OauthBoundEntity } from "../entity/oauth-bound.js";
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class OauthBoundService extends BaseService<OauthBoundEntity> {
@InjectEntityModel(OauthBoundEntity)
repository: Repository<OauthBoundEntity>;
@Inject()
sysSettingsService: SysSettingsService;
//@ts-ignore
getRepository() {
return this.repository;
}
async unbind(req: { userId: any; type: any; }) {
const { userId, type } = req;
if (!userId || !type) {
throw new Error('参数错误');
}
await this.repository.delete({
userId,
type,
});
}
async bind(req: { userId: any; type: any; openId: any; }) {
const { userId, type, openId } = req;
if (!userId || !type || !openId) {
throw new Error('参数错误');
}
const exist = await this.repository.findOne({
where: {
openId,
type,
},
});
if (exist) {
throw new Error('该第三方账号已绑定用户');
}
const exist2 = await this.repository.findOne({
where: {
userId,
type,
},
});
if (exist2) {
//覆盖绑定
exist2.openId = openId;
await this.update({
id: exist2.id,
openId,
});
return;
}
//新增
await this.add({
userId,
type,
openId,
});
}
}
@@ -1,6 +1,6 @@
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import {In, MoreThan, Not, Repository} from 'typeorm';
import {EntityManager, In, MoreThan, Not, Repository} from 'typeorm';
import { UserEntity } from '../entity/user.js';
import * as _ from 'lodash-es';
import { BaseService, CommonException, Constants, FileService, SysInstallInfo, SysSettingsService } from '@certd/lib-server';
@@ -171,7 +171,7 @@ export class UserService extends BaseService<UserEntity> {
return await this.roleService.getPermissionByRoleIds(roleIds);
}
async register(type: string, user: UserEntity) {
async register(type: string, user: UserEntity,withTx?:(tx: EntityManager)=>Promise<void>) {
if (!user.password) {
user.password = simpleNanoId();
}
@@ -227,6 +227,10 @@ export class UserService extends BaseService<UserEntity> {
newUser = await txManager.save(newUser);
const userRole: UserRoleEntity = UserRoleEntity.of(newUser.id, Constants.role.defaultUser);
await txManager.save(userRole);
if(withTx) {
await withTx(txManager);
}
});
delete newUser.password;
@@ -38,3 +38,4 @@ export * from './plugin-godaddy/index.js'
export * from './plugin-captcha/index.js'
export * from './plugin-xinnet/index.js'
export * from './plugin-xinnetconnet/index.js'
export * from './plugin-oauth/index.js'
@@ -1,6 +1,5 @@
export type OnCallbackReq = {
code: string;
redirectUri: string;
state: string;
}
@@ -58,7 +58,7 @@ export class OidcOauthProvider extends BaseAddon implements IOauthProvider {
async onCallback(req: OnCallbackReq) {
const { config, client } = await this.getClient()
const currentUrl = new URL(req.redirectUri)
const currentUrl = new URL("")
let tokens: any = await client.authorizationCodeGrant(
config,
currentUrl,