356 lines
9.5 KiB
JavaScript
356 lines
9.5 KiB
JavaScript
'use strict';
|
|
|
|
const Service = require('egg').Service;
|
|
|
|
class RolePermissionService extends Service {
|
|
normalizePermissionSet(rawValue) {
|
|
if (rawValue === undefined || rawValue === null) {
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
|
|
if (Array.isArray(rawValue)) {
|
|
const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item));
|
|
if (normalizedItems.some(item => item === '*')) {
|
|
return { allAccess: true, permissionIds: [] };
|
|
}
|
|
|
|
const permissionIds = normalizedItems
|
|
.map(item => Number(item))
|
|
.filter(item => Number.isFinite(item) && item > 0)
|
|
.map(item => Math.floor(item));
|
|
|
|
return {
|
|
allAccess: false,
|
|
permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b),
|
|
};
|
|
}
|
|
|
|
if (typeof rawValue === 'number') {
|
|
return this.normalizePermissionSet([ rawValue ]);
|
|
}
|
|
|
|
if (typeof rawValue === 'string') {
|
|
const trimmed = rawValue.trim();
|
|
if (!trimmed) {
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
if (trimmed === '*') {
|
|
return { allAccess: true, permissionIds: [] };
|
|
}
|
|
|
|
try {
|
|
const parsed = JSON.parse(trimmed);
|
|
if (parsed !== rawValue) {
|
|
return this.normalizePermissionSet(parsed);
|
|
}
|
|
} catch (_) {
|
|
// ignore JSON parse failure and continue with string splitting.
|
|
}
|
|
|
|
if (trimmed.includes(',')) {
|
|
return this.normalizePermissionSet(trimmed.split(','));
|
|
}
|
|
|
|
return this.normalizePermissionSet([ trimmed ]);
|
|
}
|
|
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
|
|
toApiPermissionIds(rawValue) {
|
|
const state = this.normalizePermissionSet(rawValue);
|
|
return state.allAccess ? [ '*' ] : state.permissionIds;
|
|
}
|
|
|
|
serializePermissionSet(rawValue) {
|
|
const state = this.normalizePermissionSet(rawValue);
|
|
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
|
|
}
|
|
|
|
async getPermissionIdsForRoles(roleIds, options = {}) {
|
|
const { ctx, app } = this;
|
|
const { Op } = app.Sequelize;
|
|
const normalizedRoleIds = Array.from(new Set((roleIds || [])
|
|
.map(roleId => Number(roleId))
|
|
.filter(roleId => Number.isFinite(roleId) && roleId > 0)));
|
|
|
|
if (normalizedRoleIds.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const roleRows = await ctx.model.Role.findAll({
|
|
where: {
|
|
id: {
|
|
[Op.in]: normalizedRoleIds,
|
|
},
|
|
...(options.includeRoleDisabled === true ? {} : { status: 1 }),
|
|
},
|
|
attributes: [ 'id', 'permissions' ],
|
|
raw: true,
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
if (!roleRows || roleRows.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const directPermissionIds = [];
|
|
let allAccess = false;
|
|
|
|
for (const row of roleRows) {
|
|
const state = this.normalizePermissionSet(row.permissions);
|
|
if (state.allAccess) {
|
|
allAccess = true;
|
|
break;
|
|
}
|
|
|
|
if (state.permissionIds.length > 0) {
|
|
directPermissionIds.push(...state.permissionIds);
|
|
}
|
|
}
|
|
|
|
const permissionWhere = {
|
|
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
|
|
};
|
|
|
|
if (options.type) {
|
|
permissionWhere.type = options.type;
|
|
}
|
|
|
|
if (allAccess) {
|
|
const allPermissions = await ctx.model.Permission.findAll({
|
|
where: permissionWhere,
|
|
attributes: [ 'id' ],
|
|
raw: true,
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
return Array.from(new Set(allPermissions
|
|
.map(item => Number(item.id))
|
|
.filter(item => Number.isFinite(item) && item > 0)));
|
|
}
|
|
|
|
const permissionIds = Array.from(new Set(directPermissionIds
|
|
.filter(item => Number.isFinite(item) && item > 0)));
|
|
if (permissionIds.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const permissions = await ctx.model.Permission.findAll({
|
|
where: {
|
|
...permissionWhere,
|
|
id: {
|
|
[Op.in]: permissionIds,
|
|
},
|
|
},
|
|
attributes: [ 'id' ],
|
|
raw: true,
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
return Array.from(new Set(permissions
|
|
.map(item => Number(item.id))
|
|
.filter(item => Number.isFinite(item) && item > 0)));
|
|
}
|
|
|
|
async getPermissionPathsForRoles(roleIds, options = {}) {
|
|
const { ctx, app } = this;
|
|
const { Op } = app.Sequelize;
|
|
const permissionIds = await this.getPermissionIdsForRoles(roleIds, {
|
|
includeDisabled: options.includeDisabled === true,
|
|
type: options.type || null,
|
|
includeRoleDisabled: options.includeRoleDisabled === true,
|
|
useLegacyFallback: options.useLegacyFallback !== false,
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
if (permissionIds.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const where = {
|
|
id: {
|
|
[Op.in]: permissionIds,
|
|
},
|
|
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
|
|
};
|
|
|
|
if (options.type) {
|
|
where.type = options.type;
|
|
}
|
|
|
|
if (options.typeLike) {
|
|
where.type = {
|
|
[Op.like]: options.typeLike,
|
|
};
|
|
}
|
|
|
|
if (options.typeNotLike) {
|
|
where.type = {
|
|
[Op.notLike]: options.typeNotLike,
|
|
};
|
|
}
|
|
|
|
const rows = await ctx.model.Permission.findAll({
|
|
where,
|
|
attributes: [ 'path' ],
|
|
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
|
raw: true,
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
return Array.from(new Set(rows
|
|
.map(item => item && item.path)
|
|
.filter(Boolean)));
|
|
}
|
|
|
|
async bulkAssign(roleId, permissionIds, options = {}) {
|
|
const currentRole = await this.ctx.model.Role.findOne({
|
|
where: { id: roleId },
|
|
attributes: [ 'permissions' ],
|
|
raw: true,
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
const currentState = this.normalizePermissionSet(currentRole && currentRole.permissions);
|
|
const incomingState = this.normalizePermissionSet(permissionIds);
|
|
const nextState = incomingState.allAccess || currentState.allAccess
|
|
? '*'
|
|
: [ ...currentState.permissionIds, ...incomingState.permissionIds ];
|
|
|
|
await this.assignPermissions(roleId, nextState, options);
|
|
return this.toApiPermissionIds(nextState);
|
|
}
|
|
|
|
async clearRolePermissions(roleId, options = {}) {
|
|
const { ctx } = this;
|
|
|
|
return await ctx.model.Role.update({
|
|
permissions: JSON.stringify([]),
|
|
updated_at: new Date(),
|
|
}, {
|
|
where: { id: roleId },
|
|
transaction: options.transaction,
|
|
});
|
|
}
|
|
|
|
async getRolePermissions(roleId, includePermissionDetails = false) {
|
|
const { ctx } = this;
|
|
const permissionIds = await this.getPermissionIds(roleId);
|
|
if (permissionIds.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
if (!includePermissionDetails) {
|
|
return permissionIds.map(permissionId => ({
|
|
role_id: Number(roleId),
|
|
permission_id: Number(permissionId),
|
|
}));
|
|
}
|
|
|
|
const permissionRows = await ctx.model.Permission.findAll({
|
|
where: {
|
|
id: permissionIds,
|
|
status: 1,
|
|
},
|
|
});
|
|
const permissionMap = new Map(permissionRows.map(item => [ Number(item.id), item ]));
|
|
|
|
return permissionIds.map(permissionId => ({
|
|
role_id: Number(roleId),
|
|
permission_id: Number(permissionId),
|
|
permission: permissionMap.get(Number(permissionId)) || null,
|
|
}));
|
|
}
|
|
|
|
async hasPermission(roleId, permissionId) {
|
|
const permissionIds = await this.getPermissionIds(roleId, {
|
|
includeDisabled: true,
|
|
});
|
|
|
|
return permissionIds.includes(Number(permissionId));
|
|
}
|
|
|
|
async assignPermissions(roleId, permissionIds, options = {}) {
|
|
const { ctx } = this;
|
|
|
|
await ctx.model.Role.update({
|
|
permissions: this.serializePermissionSet(permissionIds),
|
|
updated_at: new Date(),
|
|
}, {
|
|
where: { id: roleId },
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
return true;
|
|
}
|
|
|
|
async getPermissionTree(roleId, permissionType = null) {
|
|
const { ctx } = this;
|
|
const permissionIds = await this.getPermissionIds(roleId, {
|
|
includeDisabled: false,
|
|
type: permissionType,
|
|
});
|
|
|
|
if (permissionIds.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const permissions = await ctx.model.Permission.findAll({
|
|
where: {
|
|
id: permissionIds,
|
|
status: 1,
|
|
...(permissionType ? { type: permissionType } : {}),
|
|
},
|
|
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
|
});
|
|
|
|
return ctx.model.Permission.buildPermissionTree(permissions);
|
|
}
|
|
|
|
async getPermissionIds(roleId, options = {}) {
|
|
return await this.getPermissionIdsForRoles([ roleId ], options);
|
|
}
|
|
|
|
async removePermissionsFromAllRoles(permissionIds, options = {}) {
|
|
const { ctx } = this;
|
|
const removeSet = new Set((permissionIds || [])
|
|
.map(item => Number(item))
|
|
.filter(item => Number.isFinite(item) && item > 0));
|
|
|
|
if (removeSet.size === 0) {
|
|
return 0;
|
|
}
|
|
|
|
const roleRows = await ctx.model.Role.findAll({
|
|
attributes: [ 'id', 'permissions' ],
|
|
transaction: options.transaction,
|
|
});
|
|
|
|
let updatedCount = 0;
|
|
for (const role of roleRows) {
|
|
const state = this.normalizePermissionSet(role.permissions);
|
|
if (state.allAccess || state.permissionIds.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
const nextPermissionIds = state.permissionIds.filter(permissionId => !removeSet.has(Number(permissionId)));
|
|
if (nextPermissionIds.length === state.permissionIds.length) {
|
|
continue;
|
|
}
|
|
|
|
await role.update({
|
|
permissions: JSON.stringify(nextPermissionIds),
|
|
updated_at: new Date(),
|
|
}, {
|
|
transaction: options.transaction,
|
|
});
|
|
updatedCount++;
|
|
}
|
|
|
|
return updatedCount;
|
|
}
|
|
}
|
|
|
|
module.exports = RolePermissionService;
|