Merge branch 'v2_admin_mode' of https://github.com/certd/certd into v2_admin_mode

This commit is contained in:
xiaojunnuo
2026-02-11 16:28:53 +08:00
54 changed files with 1486 additions and 205 deletions
@@ -4,6 +4,7 @@ CREATE TABLE "cd_project"
"id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"user_id" integer NOT NULL,
"name" varchar(512) NOT NULL,
"admin_id" integer NOT NULL,
"disabled" boolean NOT NULL DEFAULT (false),
"create_time" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
"update_time" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP)
@@ -11,6 +12,7 @@ CREATE TABLE "cd_project"
CREATE INDEX "index_project_user_id" ON "cd_project" ("user_id");
CREATE INDEX "index_project_admin_id" ON "cd_project" ("admin_id");
INSERT INTO cd_project (id, user_id, "name", "disabled") VALUES (1, 1, 'default', false);
@@ -38,7 +38,11 @@ export class SysProjectController extends CrudController<ProjectEntity> {
};
merge(bean, def);
bean.userId = this.getUserId();
return super.add(bean);
return super.add({
...bean,
userId:0,
adminId: bean.userId,
});
}
@Post("/update", { summary: "sys:settings:edit" })
@@ -3,6 +3,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c
import { ProjectMemberEntity } from "../../../modules/sys/enterprise/entity/project-member.js";
import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js";
import { merge } from "lodash-es";
import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js";
/**
*/
@@ -15,6 +16,9 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
projectService: ProjectService;
getService<T>() {
return this.service;
}
@@ -37,29 +41,71 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
disabled: false,
};
merge(bean, def);
bean.userId = this.getUserId();
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId: bean.projectId,
});
return super.add(bean);
}
@Post("/update", { summary: "sys:settings:edit" })
async update(@Body(ALL) bean: any) {
bean.userId = this.getUserId();
return super.update(bean);
if (!bean.id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(bean.id)
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId: projectId,
});
return super.update({
id: bean.id,
permission: bean.permission,
});
}
@Post("/info", { summary: "sys:settings:view" })
async info(@Query("id") id: number) {
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
await this.projectService.checkReadPermission({
userId: this.getUserId(),
projectId:projectId,
});
return super.info(id);
}
@Post("/delete", { summary: "sys:settings:edit" })
async delete(@Query("id") id: number) {
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId:projectId,
});
return super.delete(id);
}
@Post("/deleteByIds", { summary: "sys:settings:edit" })
async deleteByIds(@Body("ids") ids: number[]) {
const res = await this.service.delete(ids);
return this.ok(res);
for (const id of ids) {
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId:projectId,
});
await this.service.delete(id as any);
}
return this.ok({});
}
}
@@ -20,7 +20,7 @@ export class UserProjectController extends BaseController {
@Post('/list', { summary: Constants.per.authOnly })
async list(@Body(ALL) body: any) {
const userId= this.getUserId();
const res = await this.service.getByUserId(userId);
const res = await this.service.getUserProjects(userId);
return this.ok(res);
}
@@ -1,11 +1,11 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController, SysSettingsService } from '@certd/lib-server';
import { PipelineService } from '../../../modules/pipeline/service/pipeline-service.js';
import { isPlus } from '@certd/plus-core';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { SiteInfoService } from '../../../modules/monitor/index.js';
import { PipelineEntity } from '../../../modules/pipeline/entity/pipeline.js';
import { HistoryService } from '../../../modules/pipeline/service/history-service.js';
import { PipelineService } from '../../../modules/pipeline/service/pipeline-service.js';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { SiteInfoService } from '../../../modules/monitor/index.js';
import { isPlus } from '@certd/plus-core';
/**
* 证书
@@ -25,6 +25,7 @@ export class PipelineController extends CrudController<PipelineService> {
@Inject()
siteInfoService: SiteInfoService;
getService() {
return this.service;
}
@@ -34,6 +35,8 @@ export class PipelineController extends CrudController<PipelineService> {
const isAdmin = await this.authService.isAdmin(this.ctx);
const publicSettings = await this.sysSettingsService.getPublicSettings();
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
let onlyOther = false
if (isAdmin) {
if (publicSettings.managerOtherUserPipeline) {
@@ -44,10 +47,10 @@ export class PipelineController extends CrudController<PipelineService> {
delete body.query.userId;
}
} else {
body.query.userId = this.getUserId();
body.query.userId = userId;
}
} else {
body.query.userId = this.getUserId();
body.query.userId = userId;
}
const title = body.query.title;
@@ -76,30 +79,43 @@ export class PipelineController extends CrudController<PipelineService> {
@Post('/getSimpleByIds', { summary: Constants.per.authOnly })
async getSimpleById(@Body(ALL) body) {
const ret = await this.getService().getSimplePipelines(body.ids, this.getUserId());
const { projectId, userId } = await this.getProjectUserIdRead()
const ret = await this.getService().getSimplePipelines(body.ids, userId, projectId);
return this.ok(ret);
}
@Post('/add', { summary: Constants.per.authOnly })
async add(@Body(ALL) bean: PipelineEntity) {
bean.userId = this.getUserId();
const { projectId, userId } = await this.getProjectUserIdWrite()
bean.userId = userId
bean.projectId = projectId
return super.add(bean);
}
@Post('/update', { summary: Constants.per.authOnly })
async update(@Body(ALL) bean) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), bean.id);
const { projectId } = await this.getProjectUserIdWrite()
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, bean.id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), bean.id);
}
delete bean.userId;
return super.update(bean);
}
@Post('/save', { summary: Constants.per.authOnly })
async save(@Body(ALL) bean: { addToMonitorEnabled: boolean, addToMonitorDomains: string } & PipelineEntity) {
const { projectId, userId } = await this.getProjectUserIdWrite()
if (bean.id > 0) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), bean.id);
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, bean.id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), bean.id);
}
} else {
bean.userId = this.getUserId();
bean.userId = userId;
}
if (!this.isAdmin()) {
@@ -115,7 +131,7 @@ export class PipelineController extends CrudController<PipelineService> {
//增加证书监控
await this.siteInfoService.doImport({
text: bean.addToMonitorDomains,
userId: this.getUserId(),
userId: userId,
});
}
}
@@ -124,14 +140,24 @@ export class PipelineController extends CrudController<PipelineService> {
@Post('/delete', { summary: Constants.per.authOnly })
async delete(@Query('id') id: number) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
const { projectId } = await this.getProjectUserIdWrite()
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
}
await this.service.delete(id);
return this.ok({});
}
@Post('/disabled', { summary: Constants.per.authOnly })
async disabled(@Body(ALL) bean) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), bean.id);
const { projectId } = await this.getProjectUserIdWrite()
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, bean.id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), bean.id);
}
delete bean.userId;
await this.service.disabled(bean.id, bean.disabled);
return this.ok({});
@@ -139,75 +165,140 @@ export class PipelineController extends CrudController<PipelineService> {
@Post('/detail', { summary: Constants.per.authOnly })
async detail(@Query('id') id: number) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
const { projectId } = await this.getProjectUserIdRead()
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
}
const detail = await this.service.detail(id);
return this.ok(detail);
}
@Post('/trigger', { summary: Constants.per.authOnly })
async trigger(@Query('id') id: number, @Query('stepId') stepId?: string) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
const { projectId } = await this.getProjectUserIdWrite()
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
}
await this.service.trigger(id, stepId, true);
return this.ok({});
}
@Post('/cancel', { summary: Constants.per.authOnly })
async cancel(@Query('historyId') historyId: number) {
await this.authService.checkEntityUserId(this.ctx, this.historyService, historyId);
const { projectId } = await this.getProjectUserIdWrite()
if (projectId) {
await this.authService.checkEntityProjectId(this.historyService, projectId, historyId);
} else {
await this.authService.checkEntityUserId(this.ctx, this.historyService, historyId);
}
await this.service.cancel(historyId);
return this.ok({});
}
@Post('/count', { summary: Constants.per.authOnly })
async count() {
const count = await this.service.count({ userId: this.getUserId() });
const { userId } = await this.getProjectUserIdRead()
const count = await this.service.count({ userId: userId });
return this.ok({ count });
}
private async checkPermissionCall(callback:any){
let { projectId ,userId} = await this.getProjectUserIdWrite()
if(projectId){
return await callback({userId,projectId});
}
const isAdmin = await this.authService.isAdmin(this.ctx);
userId = isAdmin ? undefined : userId;
return await callback({userId});
}
@Post('/batchDelete', { summary: Constants.per.authOnly })
async batchDelete(@Body('ids') ids: number[]) {
const isAdmin = await this.authService.isAdmin(this.ctx);
const userId = isAdmin ? undefined : this.getUserId();
await this.service.batchDelete(ids, userId);
return this.ok({});
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchDelete(ids, null,projectId);
// return this.ok({});
// }
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : userId;
// await this.service.batchDelete(ids, userId);
// return this.ok({});
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchDelete(ids, userId,projectId);
})
return this.ok({})
}
@Post('/batchUpdateGroup', { summary: Constants.per.authOnly })
async batchUpdateGroup(@Body('ids') ids: number[], @Body('groupId') groupId: number) {
const isAdmin = await this.authService.isAdmin(this.ctx);
const userId = isAdmin ? undefined : this.getUserId();
await this.service.batchUpdateGroup(ids, groupId, userId);
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchUpdateGroup(ids, groupId, null,projectId);
// return this.ok({});
// }
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateGroup(ids, groupId, userId);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateGroup(ids, groupId, userId,projectId);
})
return this.ok({});
}
@Post('/batchUpdateTrigger', { summary: Constants.per.authOnly })
async batchUpdateTrigger(@Body('ids') ids: number[], @Body('trigger') trigger: any) {
const isAdmin = await this.authService.isAdmin(this.ctx);
const userId = isAdmin ? undefined : this.getUserId();
await this.service.batchUpdateTrigger(ids, trigger, userId);
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchUpdateTrigger(ids, trigger, null,projectId);
// return this.ok({});
// }
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateTrigger(ids, trigger, userId);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateTrigger(ids, trigger, userId,projectId);
})
return this.ok({});
}
@Post('/batchUpdateNotification', { summary: Constants.per.authOnly })
async batchUpdateNotification(@Body('ids') ids: number[], @Body('notification') notification: any) {
const isAdmin = await this.authService.isAdmin(this.ctx);
const userId = isAdmin ? undefined : this.getUserId();
await this.service.batchUpdateNotifications(ids, notification, userId);
// const isAdmin = await this.authService.isAdmin(this.ctx);
// const userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateNotifications(ids, notification, userId);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateNotifications(ids, notification, userId,projectId);
})
return this.ok({});
}
@Post('/batchRerun', { summary: Constants.per.authOnly })
async batchRerun(@Body('ids') ids: number[], @Body('force') force: boolean) {
await this.service.batchRerun(ids, this.getUserId(), force);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchRerun(ids, force,userId,projectId);
})
return this.ok({});
}
@Post('/refreshWebhookKey', { summary: Constants.per.authOnly })
async refreshWebhookKey(@Body('id') id: number) {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
const { projectId } = await this.getProjectUserIdWrite()
if (projectId) {
await this.authService.checkEntityProjectId(this.getService(), projectId, id);
} else {
await this.authService.checkEntityUserId(this.ctx, this.getService(), id);
}
const res = await this.service.refreshWebhookKey(id);
return this.ok({
webhookKey: res,
@@ -51,7 +51,8 @@ export class AutoAInitSite {
//加载一次密钥
await this.sysSettingsService.getSecret();
await this.sysSettingsService.reloadPrivateSettings();
//加载设置
await this.sysSettingsService.reloadSettings();
// 授权许可
try {
@@ -4,6 +4,7 @@ import { In, MoreThan, Repository } from "typeorm";
import {
AccessService,
BaseService,
isEnterprise,
NeedSuiteException,
NeedVIPException,
PageReq,
@@ -38,7 +39,7 @@ import { CnameRecordService } from "../../cname/service/cname-record-service.js"
import { PluginConfigGetter } from "../../plugin/service/plugin-config-getter.js";
import dayjs from "dayjs";
import { DbAdapter } from "../../db/index.js";
import { isComm, isPlus } from "@certd/plus-core";
import { checkPlus, isComm, isPlus } from "@certd/plus-core";
import { logger, utils } from "@certd/basic";
import { UrlService } from "./url-service.js";
import { NotificationService } from "./notification-service.js";
@@ -301,6 +302,12 @@ export class PipelineService extends BaseService<PipelineEntity> {
// throw new NeedVIPException(`基础版最多只能创建${freeCount}条流水线`);
// }
// }
if(isEnterprise()){
//企业模式不限制
checkPlus()
return;
}
if (isComm()) {
//校验pipelineCount
const suiteSetting = await this.userSuiteService.getSuiteSetting();
@@ -328,6 +335,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
}
}
}
}
async foreachPipeline(callback: (pipeline: PipelineEntity) => void) {
@@ -559,6 +567,12 @@ export class PipelineService extends BaseService<PipelineEntity> {
}
async beforeCheck(entity: PipelineEntity) {
if(isEnterprise()){
checkPlus()
return {}
}
const validTimeEnabled = await this.isPipelineValidTimeEnabled(entity)
if (!validTimeEnabled) {
throw new Error(`流水线${entity.id}已过期,不予执行`);
@@ -582,7 +596,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
const res = await this.beforeCheck(entity);
suite = res.suite
} catch (e) {
logger.error(`流水线${entity.id}触发${triggerId}失败${e.message}`);
logger.error(`流水线${entity.id}触发失败(${triggerId}${e.message}`);
}
const id = entity.id;
@@ -625,7 +639,10 @@ export class PipelineService extends BaseService<PipelineEntity> {
const userId = entity.userId;
const historyId = await this.historyService.start(entity, triggerType);
const userIsAdmin = await this.userService.isAdmin(userId);
let userIsAdmin = false
if(userId){
userIsAdmin = await this.userService.isAdmin(userId);
}
const user: UserInfo = {
id: userId,
role: userIsAdmin ? "admin" : "user"
@@ -836,7 +853,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
return result;
}
async batchDelete(ids: number[], userId: number) {
async batchDelete(ids: number[], userId?: number,projectId?:number) {
if (!isPlus()) {
throw new NeedVIPException("此功能需要升级专业版");
}
@@ -844,11 +861,14 @@ export class PipelineService extends BaseService<PipelineEntity> {
if (userId) {
await this.checkUserId(id, userId);
}
if(projectId){
await this.checkUserId(id,projectId,"projectId")
}
await this.delete(id);
}
}
async batchUpdateGroup(ids: number[], groupId: number, userId: any) {
async batchUpdateGroup(ids: number[], groupId: number, userId: any,projectId?:number) {
if (!isPlus()) {
throw new NeedVIPException("此功能需要升级专业版");
}
@@ -856,6 +876,9 @@ export class PipelineService extends BaseService<PipelineEntity> {
if (userId && userId > 0) {
query.userId = userId;
}
if(projectId){
query.projectId = projectId;
}
await this.repository.update(
{
id: In(ids),
@@ -866,7 +889,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
}
async batchUpdateTrigger(ids: number[], trigger: any, userId: any) {
async batchUpdateTrigger(ids: number[], trigger: any, userId: any,projectId?:number) {
if (!isPlus()) {
throw new NeedVIPException("此功能需要升级专业版");
}
@@ -874,6 +897,9 @@ export class PipelineService extends BaseService<PipelineEntity> {
if (userId && userId > 0) {
query.userId = userId;
}
if(projectId){
query.projectId = projectId;
}
const list = await this.find({
where: {
id: In(ids),
@@ -915,7 +941,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
}
async batchUpdateNotifications(ids: number[], notification: Notification, userId: any) {
async batchUpdateNotifications(ids: number[], notification: Notification, userId: any,projectId?:number) {
if (!isPlus()) {
throw new NeedVIPException("此功能需要升级专业版");
}
@@ -923,6 +949,9 @@ export class PipelineService extends BaseService<PipelineEntity> {
if (userId && userId > 0) {
query.userId = userId;
}
if(projectId){
query.projectId = projectId;
}
const list = await this.find({
where: {
id: In(ids),
@@ -950,7 +979,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
}
}
async batchRerun(ids: number[], userId: any, force: boolean) {
async batchRerun(ids: number[], force: boolean,userId: any, projectId?:number) {
if (!isPlus()) {
throw new NeedVIPException("此功能需要升级专业版");
}
@@ -958,14 +987,18 @@ export class PipelineService extends BaseService<PipelineEntity> {
if (!userId || ids.length === 0) {
return;
}
const where:any = {
id: In(ids),
userId,
}
if(projectId){
where.projectId = projectId
}
const list = await this.repository.find({
select: {
id: true
},
where: {
id: In(ids),
userId
}
where:where
});
ids = list.map(item => item.id);
@@ -993,7 +1026,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
return await this.repository.count({ where: { userId } });
}
async getSimplePipelines(pipelineIds: number[], userId?: number) {
async getSimplePipelines(pipelineIds: number[], userId?: number,projectId?:number) {
return await this.repository.find({
select: {
id: true,
@@ -1001,7 +1034,8 @@ export class PipelineService extends BaseService<PipelineEntity> {
},
where: {
id: In(pipelineIds),
userId
userId,
projectId
}
});
}
@@ -35,4 +35,8 @@ export class AuthService {
}
await service.checkUserId(id, ctx.user.id, userKey);
}
async checkEntityProjectId(service:any,projectId = 0,id:any=0){
await service.checkUserId(id, projectId , "projectId");
}
}
@@ -10,6 +10,9 @@ export class ProjectEntity {
@Column({ name: 'user_id', comment: 'UserId' })
userId: number;
@Column({ name: 'admin_id', comment: '管理员Id' })
adminId: number;
@Column({ name: 'name', comment: '项目名称' })
name: string;
@@ -46,4 +46,26 @@ export class ProjectMemberService extends BaseService<ProjectMemberEntity> {
});
}
async getMember(projectId: number,userId: number) {
return await this.repository.findOne({
where: {
userId,
projectId,
},
});
}
async getProjectId(id: number) {
const member = await this.repository.findOne({
select: ['projectId'],
where: {
id: id,
},
});
if (!member) {
throw new Error('项目成员记录不存在');
}
return member.projectId;
}
}
@@ -1,7 +1,7 @@
import {Inject, Provide, Scope, ScopeEnum} from '@midwayjs/core';
import {BaseService, SysSettingsService} from '@certd/lib-server';
import {InjectEntityModel} from '@midwayjs/typeorm';
import {In, Repository} from 'typeorm';
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 { ProjectEntity } from '../entity/project.js';
import { ProjectMemberService } from './project-member-service.js';
@@ -30,45 +30,34 @@ export class ProjectService extends BaseService<ProjectEntity> {
const exist = await this.repository.findOne({
where: {
name,
userId:0,
userId: 0,
},
});
if (exist) {
throw new Error('项目名称已存在');
}
bean.userId = 0
bean.disabled = false
return await super.add(bean)
}
async setDisabled(id: number, disabled: boolean) {
const project = await this.repository.findOne({
where: {
id,
userId:0,
},
});
if (!project) {
throw new Error('项目不存在');
}
await this.repository.update({
id,
userId:0,
}, {
disabled,
});
project.disabled = disabled;
await this.repository.save(project);
}
async getByUserId(userId: number) {
async getUserProjects(userId: number) {
const memberList = await this.projectMemberService.getByUserId(userId);
const projectIds = memberList.map(item => item.projectId);
const projectList = await this.repository.find({
where: {
id: In(projectIds),
},
});
const projectList = await this.repository.createQueryBuilder('project')
.where(' project.disabled = false')
.where(' project.userId = :userId', { userId:0 })
.where(' project.id IN (:...projectIds) or project.adminId = :userId', { projectIds, userId })
.getMany();
const memberPermissionMap = memberList.reduce((prev, cur) => {
prev[cur.projectId] = cur.permission;
@@ -76,9 +65,81 @@ export class ProjectService extends BaseService<ProjectEntity> {
}, {} as Record<number, string>);
projectList.forEach(item => {
item.permission = memberPermissionMap[item.id] || 'read';
if (item.adminId === userId) {
item.permission = 'admin';
}else{
item.permission = memberPermissionMap[item.id] || 'read';
}
})
return projectList
}
async checkAdminPermission({userId, projectId}: {userId: number, projectId: number}) {
return await this.checkPermission({
userId,
projectId,
permission: 'admin',
})
}
async checkWritePermission({userId, projectId}: {userId: number, projectId: number}) {
return await this.checkPermission({
userId,
projectId,
permission: 'write',
})
}
async checkReadPermission({userId, projectId}: {userId: number, projectId: number}) {
return await this.checkPermission({
userId,
projectId,
permission: 'read',
})
}
async checkPermission({userId, projectId, permission}: {userId: number, projectId: number, permission: string}) {
if (permission !== 'admin' && permission !== 'write' && permission !== 'read') {
throw new Error('权限类型错误');
}
if (!userId ){
throw new Error('用户ID不能为空');
}
if (!projectId ){
throw new Error('项目ID不能为空');
}
const project = await this.findOne({
select: ['id', 'userId', 'adminId', 'disabled'],
where: {
id: projectId,
},
});
if (!project) {
throw new Error('项目不存在');
}
if (project.adminId === userId) {
//创建者拥有管理权限
return true
}
if (project.disabled) {
throw new Error('项目已禁用');
}
const member = await this.projectMemberService.getMember(projectId,userId);
if (!member) {
throw new Error('项目成员不存在');
}
if (permission === 'read') {
return true
}
if (permission === 'write') {
if (member.permission === 'admin' || member.permission === 'write') {
return true
}else{
throw new Error('权限不足');
}
}
if (member.permission !== permission) {
throw new Error('权限不足');
}
return true
}
}