feat: 域名验证方法支持CNAME间接方式,此方式支持所有域名注册商,且无需提供Access授权,但是需要手动添加cname解析

This commit is contained in:
xiaojunnuo
2024-10-07 03:21:16 +08:00
parent 0c8e83e125
commit f3d35084ed
123 changed files with 2373 additions and 456 deletions
@@ -0,0 +1,62 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController, PlusService } from '@certd/lib-server';
import { AppKey } from '@certd/pipeline';
import { SysSettingsService } from '@certd/lib-server';
import { SysInstallInfo } from '@certd/lib-server';
export type PreBindUserReq = {
userId: number;
};
export type BindUserReq = {
userId: number;
};
/**
*/
@Provide()
@Controller('/api/sys/account')
export class BasicController extends BaseController {
@Inject()
plusService: PlusService;
@Inject()
sysSettingsService: SysSettingsService;
@Post('/preBindUser', { summary: 'sys:settings:edit' })
public async preBindUser(@Body(ALL) body: PreBindUserReq) {
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
// 设置缓存内容
await this.plusService.requestWithoutSign({
url: '/activation/subject/preBind',
method: 'POST',
data: {
userId: body.userId,
appKey: AppKey,
subjectId: installInfo.siteId,
},
});
return this.ok({});
}
@Post('/bindUser', { summary: 'sys:settings:edit' })
public async bindUser(@Body(ALL) body: BindUserReq) {
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
installInfo.bindUserId = body.userId;
await this.sysSettingsService.saveSetting(installInfo);
return this.ok({});
}
@Post('/unbindUser', { summary: 'sys:settings:edit' })
public async unbindUser() {
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
installInfo.bindUserId = null;
await this.sysSettingsService.saveSetting(installInfo);
return this.ok({});
}
@Post('/updateLicense', { summary: 'sys:settings:edit' })
public async updateLicense(@Body(ALL) body: { license: string }) {
await this.plusService.updateLicense(body.license);
return this.ok(true);
}
}
@@ -0,0 +1,54 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { PermissionService } from '../service/permission-service.js';
/**
* 权限资源
*/
@Provide()
@Controller('/api/sys/authority/permission')
export class PermissionController extends CrudController<PermissionService> {
@Inject()
service: PermissionService;
getService() {
return this.service;
}
@Post('/page', { summary: 'sys:auth:per:view' })
async page(
@Body(ALL)
body
) {
return await super.page(body);
}
@Post('/add', { summary: 'sys:auth:per:add' })
async add(
@Body(ALL)
bean
) {
return await super.add(bean);
}
@Post('/update', { summary: 'sys:auth:per:edit' })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
}
@Post('/delete', { summary: 'sys:auth:per:remove' })
async delete(
@Query('id')
id: number
) {
return await super.delete(id);
}
@Post('/tree', { summary: 'sys:auth:per:view' })
async tree() {
const tree = await this.service.tree({});
return this.ok(tree);
}
}
@@ -0,0 +1,91 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { RoleService } from '../service/role-service.js';
/**
* 系统用户
*/
@Provide()
@Controller('/api/sys/authority/role')
export class RoleController extends CrudController<RoleService> {
@Inject()
service: RoleService;
getService() {
return this.service;
}
@Post('/page', { summary: 'sys:auth:role:view' })
async page(
@Body(ALL)
body
) {
return await super.page(body);
}
@Post('/list', { summary: 'sys:auth:role:view' })
async list() {
const ret = await this.service.find({});
return this.ok(ret);
}
@Post('/add', { summary: 'sys:auth:role:add' })
async add(
@Body(ALL)
bean
) {
return await super.add(bean);
}
@Post('/update', { summary: 'sys:auth:role:edit' })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
}
@Post('/delete', { summary: 'sys:auth:role:remove' })
async delete(
@Query('id')
id: number
) {
if (id === 1) {
throw new Error('不能删除默认的管理员角色');
}
return await super.delete(id);
}
@Post('/getPermissionTree', { summary: 'sys:auth:role:view' })
async getPermissionTree(
@Query('id')
id: number
) {
const ret = await this.service.getPermissionTreeByRoleId(id);
return this.ok(ret);
}
@Post('/getPermissionIds', { summary: 'sys:auth:role:view' })
async getPermissionIds(
@Query('id')
id: number
) {
const ret = await this.service.getPermissionIdsByRoleId(id);
return this.ok(ret);
}
/**
* 给角色授予权限
* @param roleId
* @param permissionIds
*/
@Post('/authz', { summary: 'sys:auth:role:edit' })
async authz(
@Body('roleId')
roleId,
@Body('permissionIds')
permissionIds
) {
await this.service.authz(roleId, permissionIds);
return this.ok(null);
}
}
@@ -0,0 +1,114 @@
import { Provide, Controller, Post, Inject, Body, Query, ALL } from '@midwayjs/core';
import { UserService } from '../service/user-service.js';
import { CrudController } from '@certd/lib-server';
import { RoleService } from '../service/role-service.js';
import { PermissionService } from '../service/permission-service.js';
import { Constants } from '@certd/lib-server';
/**
* 系统用户
*/
@Provide()
@Controller('/api/sys/authority/user')
export class UserController extends CrudController<UserService> {
@Inject()
service: UserService;
@Inject()
roleService: RoleService;
@Inject()
permissionService: PermissionService;
getService() {
return this.service;
}
@Post('/page', { summary: 'sys:auth:user:view' })
async page(
@Body(ALL)
body
) {
const ret = await super.page(body);
const users = ret.data.records;
//获取roles
const userIds = users.map(item => item.id);
const userRoles = await this.roleService.getByUserIds(userIds);
const userRolesMap = new Map();
for (const ur of userRoles) {
let roles = userRolesMap.get(ur.userId);
if (roles == null) {
roles = [];
userRolesMap.set(ur.userId, roles);
}
roles.push(ur.roleId);
}
for (const record of users) {
//withRoles
record.roles = userRolesMap.get(record.id);
//删除密码字段
delete record.password;
}
return ret;
}
@Post('/add', { summary: 'sys:auth:user:add' })
async add(
@Body(ALL)
bean
) {
return await super.add(bean);
}
@Post('/update', { summary: 'sys:auth:user:edit' })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
}
@Post('/delete', { summary: 'sys:auth:user:remove' })
async delete(
@Query('id')
id: number
) {
if (id === 1) {
throw new Error('不能删除默认的管理员用户');
}
return await super.delete(id);
}
/**
* 当前登录用户的个人信息
*/
@Post('/mine', { summary: Constants.per.authOnly })
public async mine() {
const id = this.ctx.user.id;
const info = await this.service.info(id, ['password']);
return this.ok(info);
}
/**
* 当前登录用户的权限列表
*/
@Post('/permissions', { summary: Constants.per.authOnly })
public async permissions() {
const id = this.ctx.user.id;
const permissions = await this.service.getUserPermissions(id);
return this.ok(permissions);
}
/**
* 当前登录用户的权限树形列表
*/
@Post('/permissionTree', { summary: Constants.per.authOnly })
public async permissionTree() {
const id = this.ctx.user.id;
const permissions = await this.service.getUserPermissions(id);
const tree = this.permissionService.buildTree(permissions);
return this.ok(tree);
}
}
@@ -0,0 +1,40 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
/**
* 权限
*/
@Entity('sys_permission')
export class PermissionEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ comment: '标题', length: 100 })
title: string;
/**
* 权限代码
* 示例:sys:user:read
*/
@Column({ comment: '权限代码', length: 100, nullable: true })
permission: string;
@Column({ name: 'parent_id', comment: '父节点ID', default: -1 })
parentId: number;
@Column({ comment: '排序号' })
sort: number;
@Column({
name: 'create_time',
comment: '创建时间',
default: () => 'CURRENT_TIMESTAMP',
})
createTime: Date;
@Column({
name: 'update_time',
comment: '修改时间',
default: () => 'CURRENT_TIMESTAMP',
})
updateTime: Date;
// @ManyToMany(type => RoleEntity, res => res.permissions)
// roles: RoleEntity[];
}
@@ -0,0 +1,12 @@
import { Entity, PrimaryColumn } from 'typeorm';
/**
* 角色权限多对多
*/
@Entity('sys_role_permission')
export class RolePermissionEntity {
@PrimaryColumn({ name: 'role_id' })
roleId: number;
@PrimaryColumn({ name: 'permission_id' })
permissionId: number;
}
@@ -0,0 +1,43 @@
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
/**
* 角色
*/
@Entity('sys_role')
export class RoleEntity {
@PrimaryGeneratedColumn()
id: number;
@Index({ unique: true })
@Column({ comment: '角色名称', length: 100 })
name: string;
@Column({
name: 'create_time',
comment: '创建时间',
default: () => 'CURRENT_TIMESTAMP',
})
createTime: Date;
@Column({
name: 'update_time',
comment: '修改时间',
default: () => 'CURRENT_TIMESTAMP',
})
updateTime: Date;
// @ManyToMany(type => PermissionEntity, res => res.roles)
// @JoinTable({
// name: 'sys_role_resources',
// joinColumn: {
// name: 'roleId',
// referencedColumnName: 'id',
// },
// inverseJoinColumn: {
// name: 'resourceId',
// referencedColumnName: 'id',
// },
// })
// resources: PermissionEntity[];
// @ManyToMany(type => UserEntity, res => res.roles)
// users: UserEntity[];
}
@@ -0,0 +1,16 @@
import { Entity, PrimaryColumn } from 'typeorm';
/**
* 用户角色多对多
*/
@Entity('sys_user_role')
export class UserRoleEntity {
@PrimaryColumn({ name: 'role_id' })
roleId: number;
@PrimaryColumn({ name: 'user_id' })
userId: number;
static of(userId: number, roleId: number): UserRoleEntity {
return Object.assign(new UserRoleEntity(), { userId, roleId });
}
}
@@ -0,0 +1,71 @@
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
/**
* 系统用户
*/
@Entity('sys_user')
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Index({ unique: true })
@Column({ comment: '用户名', length: 100 })
username: string;
@Column({ comment: '密码', length: 100 })
password: string;
@Column({ name: 'password_version', comment: '密码版本' })
passwordVersion: number;
@Column({ name: 'nick_name', comment: '昵称', length: 100, nullable: true })
nickName: string;
@Column({ comment: '头像', length: 255, nullable: true })
avatar: string;
@Column({ name: 'phone_code', comment: '区号', length: 20, nullable: true })
phoneCode: string;
@Column({ comment: '手机', length: 20, nullable: true })
mobile: string;
@Column({ comment: '邮箱', length: 50, nullable: true })
email: string;
@Column({ comment: '备注', length: 100, nullable: true })
remark: string;
@Column({ comment: '状态 0:禁用 1:启用', default: 1, type: 'int' })
status: number;
@Column({
name: 'create_time',
comment: '创建时间',
default: () => 'CURRENT_TIMESTAMP',
})
createTime: Date;
@Column({
name: 'update_time',
comment: '修改时间',
default: () => 'CURRENT_TIMESTAMP',
})
updateTime: Date;
// @ManyToMany(type => RoleEntity, res => res.users)
// @JoinTable({
// name: 'sys_user_roles',
// joinColumn: {
// name: 'userId',
// referencedColumnName: 'id',
// },
// inverseJoinColumn: {
// name: 'roleId',
// referencedColumnName: 'id',
// },
// })
// roles: RoleEntity[];
static of(user: Partial<UserEntity>) {
return Object.assign(new UserEntity(), user);
}
roleIds: number[];
}
@@ -0,0 +1,17 @@
import { EnumItem } from '@certd/lib-server';
import * as _ from 'lodash-es';
class ResourceTypes {
MENU = new EnumItem('menu', '菜单', 'blue');
BTN = new EnumItem('btn', '按钮', 'green');
ROUTE = new EnumItem('route', '路由', 'red');
names() {
const list = [];
_.forEach(this, (item, key) => {
list.push(item);
});
return list;
}
}
export const ResourceTypeEnum = new ResourceTypes();
@@ -0,0 +1,38 @@
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { RoleService } from './role-service.js';
import { BaseService } from '@certd/lib-server';
/**
* 权限校验
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class AuthService {
@Inject()
roleService: RoleService;
async checkPermission(ctx: any, permission: string) {
//如果不是仅校验登录,还需要校验是否拥有权限
const roleIds: number[] = ctx.user.roles;
const permissions = await this.roleService.getCachedPermissionSetByRoleIds(roleIds);
if (!permissions.has(permission)) {
return false;
}
return true;
}
async isAdmin(ctx: any) {
const roleIds: number[] = ctx.user.roles;
if (roleIds.includes(1)) {
return true;
}
}
async checkEntityUserId(ctx: any, service: BaseService<any>, id: any = 0, userKey = 'userId') {
const isAdmin = await this.isAdmin(ctx);
if (isAdmin) {
return true;
}
await service.checkUserId(id, ctx.user.id, userKey);
}
}
@@ -0,0 +1,53 @@
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '@certd/lib-server';
import { PermissionEntity } from '../entity/permission.js';
/**
* 权限资源
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class PermissionService extends BaseService<PermissionEntity> {
@InjectEntityModel(PermissionEntity)
repository: Repository<PermissionEntity>;
getRepository() {
return this.repository;
}
async tree(options: any = {}) {
if (options.order == null) {
options.order = {
sort: 'ASC',
};
}
const list = await this.find(options);
return this.buildTree(list);
}
buildTree(list: any) {
const idMap = {};
const root = [];
for (const item of list) {
idMap[item.id] = item;
if (item.parentId == null || item.parentId <= 0) {
root.push(item);
}
}
for (const item of list) {
if (item.parentId > 0) {
const parent = idMap[item.parentId];
if (parent) {
if (parent.children == null) {
parent.children = [];
}
parent.children.push(item);
}
}
}
return root;
}
}
@@ -0,0 +1,19 @@
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '@certd/lib-server';
import { RolePermissionEntity } from '../entity/role-permission.js';
/**
* 角色->权限
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class RolePermissionService extends BaseService<RolePermissionEntity> {
@InjectEntityModel(RolePermissionEntity)
repository: Repository<RolePermissionEntity>;
getRepository() {
return this.repository;
}
}
@@ -0,0 +1,127 @@
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { BaseService } from '@certd/lib-server';
import { RoleEntity } from '../entity/role.js';
import { UserRoleService } from './user-role-service.js';
import { RolePermissionEntity } from '../entity/role-permission.js';
import { PermissionService } from './permission-service.js';
import * as _ from 'lodash-es';
import { RolePermissionService } from './role-permission-service.js';
import { LRUCache } from 'lru-cache';
/**
* 角色
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class RoleService extends BaseService<RoleEntity> {
@InjectEntityModel(RoleEntity)
repository: Repository<RoleEntity>;
@Inject()
userRoleService: UserRoleService;
@Inject()
permissionService: PermissionService;
@Inject()
rolePermissionService: RolePermissionService;
permissionCache = new LRUCache<string, any>({
max: 1000,
ttl: 1000 * 60 * 10,
});
getRepository() {
return this.repository;
}
async getRoleIdsByUserId(id: any) {
const userRoles = await this.userRoleService.find({
where: { userId: id },
});
return userRoles.map(item => item.roleId);
}
async getByUserIds(ids: any) {
return await this.userRoleService.find({
where: {
userId: In(ids),
},
});
}
async getPermissionByRoleIds(roleIds: any) {
return await this.permissionService.repository
.createQueryBuilder('permission')
.innerJoinAndSelect(RolePermissionEntity, 'rp', 'rp.permissionId = permission.id and rp.roleId in (:...roleIds)', { roleIds })
.getMany();
}
async addRoles(userId: number, roles) {
if (roles == null || roles.length === 0) {
return;
}
for (const roleId of roles) {
await this.userRoleService.add({
userId,
roleId,
});
}
}
async updateRoles(userId, roles) {
if (roles == null) {
return;
}
const oldRoleIds = await this.getRoleIdsByUserId(userId);
if (_.xor(roles, oldRoleIds).length === 0) {
//如果两个数组相等,则不修改
return;
}
//先删除所有
await this.userRoleService.delete({ userId });
//再添加
await this.addRoles(userId, roles);
this.permissionCache.clear();
}
async getPermissionTreeByRoleId(id: any) {
const list = await this.getPermissionByRoleIds([id]);
return this.permissionService.buildTree(list);
}
async getPermissionIdsByRoleId(id: any) {
const list = await this.getPermissionByRoleIds([id]);
return list.map(item => item.id);
}
async authz(roleId: any, permissionIds: any) {
await this.rolePermissionService.delete({ roleId });
for (const permissionId of permissionIds) {
await this.rolePermissionService.add({
roleId,
permissionId,
});
}
this.permissionCache.clear();
}
async getPermissionSetByRoleIds(roleIds: number[]): Promise<Set<string>> {
const list = await this.getPermissionByRoleIds(roleIds);
const permissionSet = new Set<string>();
for (const entity of list) {
permissionSet.add(entity.permission);
}
return permissionSet;
}
async getCachedPermissionSetByRoleIds(roleIds: number[]): Promise<Set<string>> {
const roleIdsKey = roleIds.join(',');
let permissionSet = this.permissionCache.get(roleIdsKey);
if (permissionSet) {
return permissionSet;
}
permissionSet = await this.getPermissionSetByRoleIds(roleIds);
this.permissionCache.set(roleIdsKey, permissionSet);
return permissionSet;
}
}
@@ -0,0 +1,19 @@
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '@certd/lib-server';
import { UserRoleEntity } from '../entity/user-role.js';
/**
* 用户->角色
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class UserRoleService extends BaseService<UserRoleEntity> {
@InjectEntityModel(UserRoleEntity)
repository: Repository<UserRoleEntity>;
getRepository() {
return this.repository;
}
}
@@ -0,0 +1,219 @@
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '../entity/user.js';
import * as _ from 'lodash-es';
import md5 from 'md5';
import { CommonException } from '@certd/lib-server';
import { BaseService } from '@certd/lib-server';
import { RoleService } from './role-service.js';
import { PermissionService } from './permission-service.js';
import { UserRoleService } from './user-role-service.js';
import { Constants } from '@certd/lib-server';
import { UserRoleEntity } from '../entity/user-role.js';
import bcrypt from 'bcryptjs';
import { SysSettingsService } from '@certd/lib-server';
import { SysInstallInfo } from '@certd/lib-server';
import { RandomUtil } from '../../../../utils/random.js';
/**
* 系统用户
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class UserService extends BaseService<UserEntity> {
@InjectEntityModel(UserEntity)
repository: Repository<UserEntity>;
@Inject()
roleService: RoleService;
@Inject()
permissionService: PermissionService;
@Inject()
userRoleService: UserRoleService;
@Inject()
sysSettingsService: SysSettingsService;
getRepository() {
return this.repository;
}
/**
* 获得个人信息
*/
async mine(userId: number) {
const info = await this.repository.findOne({
where: {
id: userId,
},
});
delete info.password;
return info;
}
/**
* 新增
* @param param
*/
async add(param) {
const exists = await this.repository.findOne({
where: {
username: param.username,
},
});
if (!_.isEmpty(exists)) {
throw new CommonException('用户名已经存在');
}
const plainPassword = param.password ?? RandomUtil.randomStr(6);
param.passwordVersion = 2;
param.password = await this.genPassword(plainPassword, param.passwordVersion); // 默认密码 建议未改密码不能登陆
await super.add(param);
//添加角色
if (param.roles && param.roles.length > 0) {
await this.roleService.addRoles(param.id, param.roles);
}
return param.id;
}
/**
* 修改
* @param param 数据
*/
async update(param) {
if (param.id == null) {
throw new CommonException('id不能为空');
}
const userInfo = await this.repository.findOne({
where: { id: param.id },
});
if (!userInfo) {
throw new CommonException('用户不存在');
}
delete param.username;
if (!_.isEmpty(param.password)) {
param.passwordVersion = 2;
param.password = await this.genPassword(param.password, param.passwordVersion);
} else {
delete param.password;
}
await super.update(param);
await this.roleService.updateRoles(param.id, param.roles);
}
private async genPassword(rawPassword: any, passwordVersion: number) {
if (passwordVersion == null || passwordVersion <= 1) {
return md5(rawPassword);
}
const salt = bcrypt.genSaltSync(10);
const plainPassword = await this.buildPlainPassword(rawPassword);
return bcrypt.hashSync(plainPassword, salt);
}
async findOne(param: any) {
return this.repository.findOne({
where: param,
});
}
async checkPassword(rawPassword: any, hashPassword: any, passwordVersion: number) {
if (passwordVersion == null || passwordVersion <= 1) {
return (await this.genPassword(rawPassword, passwordVersion)) === hashPassword;
}
const plainPassword = await this.buildPlainPassword(rawPassword);
return bcrypt.compareSync(plainPassword, hashPassword);
}
async buildPlainPassword(rawPassword: string) {
const setting: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
const prefixSiteId = setting.siteId.substring(1, 5);
return rawPassword + prefixSiteId;
}
/**
* 获取用户的菜单资源列表
* @param id
*/
async getUserPermissions(id: any) {
const roleIds = await this.roleService.getRoleIdsByUserId(id);
return await this.roleService.getPermissionByRoleIds(roleIds);
}
async register(user: UserEntity) {
const old = await this.findOne({ username: user.username });
if (old != null) {
throw new CommonException('用户名已经存在');
}
let newUser: UserEntity = UserEntity.of({
username: user.username,
password: user.password,
nickName: user.nickName || user.username,
avatar: user.avatar || '',
email: user.email || '',
mobile: user.mobile || '',
phoneCode: user.phoneCode || '',
status: 1,
passwordVersion: 2,
});
if (!newUser.password) {
newUser.password = RandomUtil.randomStr(6);
}
newUser.password = await this.genPassword(newUser.password, newUser.passwordVersion);
await this.transaction(async txManager => {
newUser = await txManager.save(newUser);
const userRole: UserRoleEntity = UserRoleEntity.of(newUser.id, Constants.role.defaultUser);
await txManager.save(userRole);
});
delete newUser.password;
return newUser;
}
async changePassword(userId: any, form: any) {
const user = await this.info(userId);
const passwordChecked = await this.checkPassword(form.password, user.password, user.passwordVersion);
if (!passwordChecked) {
throw new CommonException('原密码错误');
}
const param = {
id: userId,
password: form.newPassword,
};
await this.update(param);
}
async resetPassword(userId: any, newPasswd: string) {
const param = {
id: userId,
password: newPasswd,
};
await this.update(param);
}
async delete(ids: any) {
if (typeof ids === 'string') {
ids = ids.split(',');
ids = ids.map(id => parseInt(id));
}
if (ids instanceof Array) {
if (ids.includes(1)) {
throw new CommonException('不能删除管理员');
}
}
await super.delete(ids);
}
async isAdmin(userId: any) {
const userRoles = await this.userRoleService.find({
where: {
userId,
},
});
const roleIds = userRoles.map(item => item.roleId);
if (roleIds.includes(1)) {
return true;
}
}
}
@@ -0,0 +1,66 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { CnameProviderService } from '../service/cname-provider-service.js';
import { merge } from 'lodash-es';
/**
* 授权
*/
@Provide()
@Controller('/api/sys/cname/provider')
export class CnameRecordController extends CrudController<CnameProviderService> {
@Inject()
service: CnameProviderService;
getService(): CnameProviderService {
return this.service;
}
@Post('/page', { summary: 'sys:settings:view' })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
return await super.page(body);
}
@Post('/list', { summary: 'sys:settings:view' })
async list(@Body(ALL) body: any) {
return super.list(body);
}
@Post('/add', { summary: 'sys:settings:edit' })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
disabled: false,
};
merge(bean, def);
return super.add(bean);
}
@Post('/update', { summary: 'sys:settings:edit' })
async update(@Body(ALL) bean: any) {
return super.update(bean);
}
@Post('/info', { summary: 'sys:settings:view' })
async info(@Query('id') id: number) {
return super.info(id);
}
@Post('/delete', { summary: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
return super.delete(id);
}
@Post('/setDefault', { summary: 'sys:settings:edit' })
async setDefault(@Body('id') id: number) {
await this.service.setDefault(id);
return this.ok();
}
@Post('/setDisabled', { summary: 'sys:settings:edit' })
async setDisabled(@Body('id') id: number, @Body('disabled') disabled: boolean) {
await this.service.setDisabled(id, disabled);
return this.ok();
}
}
@@ -0,0 +1,35 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
/**
* cname配置
*/
@Entity('cd_cname_provider')
export class CnameProviderEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ comment: '域名', length: 100 })
domain: string;
@Column({ comment: 'DNS提供商类型', name: 'dns_provider_type', length: 20 })
dnsProviderType: string;
@Column({ comment: 'DNS授权Id', name: 'access_id' })
accessId: number;
@Column({ comment: '是否默认', name: 'is_default' })
isDefault: boolean;
@Column({ comment: '是否禁用', name: 'disabled' })
disabled: boolean;
@Column({ comment: '备注', length: 200 })
remark: string;
@Column({
comment: '创建时间',
name: 'create_time',
default: () => 'CURRENT_TIMESTAMP',
})
createTime: Date;
@Column({
comment: '修改时间',
name: 'update_time',
default: () => 'CURRENT_TIMESTAMP',
})
updateTime: Date;
}
@@ -0,0 +1,85 @@
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService, ValidateException } from '@certd/lib-server';
import { CnameProviderEntity } from '../entity/cname_provider.js';
/**
* 授权
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class CnameProviderService extends BaseService<CnameProviderEntity> {
@InjectEntityModel(CnameProviderEntity)
repository: Repository<CnameProviderEntity>;
getRepository() {
return this.repository;
}
async getDefault() {
return await this.repository.findOne({ where: { isDefault: true } });
}
/**
* 新增
* @param param 数据
*/
async add(param: any) {
const def = await this.getDefault();
if (!def) {
param.isDefault = true;
}
const res = await super.add(param);
if (param.isDefault) {
await this.setDefault(res.id);
}
return res;
}
/**
* 修改
* @param param 数据
*/
async update(param: any) {
await super.update(param);
if (param.isDefault) {
await this.setDefault(param.id);
}
}
async delete(ids: any) {
if (!(ids instanceof Array)) {
ids = [ids];
}
for (const id of ids) {
const info = await this.info(id);
if (info.isDefault) {
throw new ValidateException('默认的CNAME服务不能删除,请先修改为非默认值');
}
}
await super.delete(ids);
}
async setDefault(id: number) {
await this.transaction(async em => {
await em.getRepository(CnameProviderEntity).update({ isDefault: true }, { isDefault: false });
await em.getRepository(CnameProviderEntity).update({ id }, { isDefault: true });
});
}
async setDisabled(id: number, disabled: boolean) {
await this.repository.update({ id }, { disabled });
}
async getByPriority() {
const def = await this.getDefault();
if (def) {
return def;
}
const found = await this.repository.findOne({ order: { createTime: 'DESC' } });
if (found) {
return found;
}
return null;
}
}
@@ -0,0 +1,55 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { SysSettingsService } from '@certd/lib-server';
import { BaseController } from '@certd/lib-server';
import { AppKey } from '@certd/pipeline';
import { SysInstallInfo } from '@certd/lib-server';
import { logger } from '@certd/pipeline';
import { PlusService } from '@certd/lib-server';
/**
*/
@Provide()
@Controller('/api/sys/plus')
export class SysPlusController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
plusService: PlusService;
@Post('/active', { summary: 'sys:settings:edit' })
async active(@Body(ALL) body) {
const { code } = body;
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
const siteId = installInfo.siteId;
const formData = {
appKey: AppKey,
code,
subjectId: siteId,
};
const res: any = await this.plusService.active(formData);
if (res.code > 0) {
logger.error('激活失败', res.message);
return this.fail(res.message, 1);
}
const license = res.data.license;
await this.plusService.updateLicense(license);
return this.ok(true);
}
@Post('/bindUrl', { summary: 'sys:settings:edit' })
async bindUrl(@Body(ALL) body: { url: string }) {
const { url } = body;
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
await this.plusService.bindUrl(installInfo.siteId, url);
installInfo.bindUrl = url;
await this.sysSettingsService.saveSetting(installInfo);
return this.ok(true);
}
}
@@ -0,0 +1,84 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { SysSettingsService } from '@certd/lib-server';
import { SysSettingsEntity } from '../entity/sys-settings.js';
import { SysPublicSettings } from '@certd/lib-server';
import * as _ from 'lodash-es';
import { PipelineService } from '../../../pipeline/service/pipeline-service.js';
/**
*/
@Provide()
@Controller('/api/sys/settings')
export class SysSettingsController extends CrudController<SysSettingsService> {
@Inject()
service: SysSettingsService;
@Inject()
pipelineService: PipelineService;
getService() {
return this.service;
}
@Post('/page', { summary: 'sys:settings:view' })
async page(@Body(ALL) body) {
body.query = body.query ?? {};
body.query.userId = this.ctx.user.id;
return super.page(body);
}
@Post('/list', { summary: 'sys:settings:view' })
async list(@Body(ALL) body) {
body.userId = this.ctx.user.id;
return super.list(body);
}
@Post('/add', { summary: 'sys:settings:edit' })
async add(@Body(ALL) bean) {
bean.userId = this.ctx.user.id;
return super.add(bean);
}
@Post('/update', { summary: 'sys:settings:edit' })
async update(@Body(ALL) bean) {
await this.service.checkUserId(bean.id, this.ctx.user.id);
return super.update(bean);
}
@Post('/info', { summary: 'sys:settings:view' })
async info(@Query('id') id: number) {
await this.service.checkUserId(id, this.ctx.user.id);
return super.info(id);
}
@Post('/delete', { summary: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
await this.service.checkUserId(id, this.ctx.user.id);
return super.delete(id);
}
@Post('/save', { summary: 'sys:settings:edit' })
async save(@Body(ALL) bean: SysSettingsEntity) {
await this.service.save(bean);
return this.ok({});
}
@Post('/get', { summary: 'sys:settings:view' })
async get(@Query('key') key: string) {
const entity = await this.service.getByKey(key);
return this.ok(entity);
}
// savePublicSettings
@Post('/savePublicSettings', { summary: 'sys:settings:edit' })
async savePublicSettings(@Body(ALL) body) {
const setting = new SysPublicSettings();
_.merge(setting, body);
await this.service.savePublicSettings(setting);
return this.ok({});
}
@Post('/stopOtherUserTimer', { summary: 'sys:settings:edit' })
async stopOtherUserTimer(@Body(ALL) body) {
await this.pipelineService.stopOtherUserPipeline(1);
return this.ok({});
}
}
@@ -0,0 +1,33 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
/**
*/
@Entity('sys_settings')
export class SysSettingsEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ comment: 'key', length: 100 })
key: string;
@Column({ comment: '名称', length: 100 })
title: string;
@Column({ name: 'setting', comment: '设置', length: 1024, nullable: true })
setting: string;
// public 公开读,私有写, private 私有读,私有写
@Column({ name: 'access', comment: '访问权限' })
access: string;
@Column({
name: 'create_time',
comment: '创建时间',
default: () => 'CURRENT_TIMESTAMP',
})
createTime: Date;
@Column({
name: 'update_time',
comment: '修改时间',
default: () => 'CURRENT_TIMESTAMP',
})
updateTime: Date;
}