Browse Source

fix: 修改用户授权

old-3.0 4.3.0.5
WangJunZzz 5 years ago
parent
commit
ca6a6396fa
  1. 18
      content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Permissions/CompanyNameProjectNamePermissionDefinitionProvider.cs
  2. 7
      content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Permissions/CompanyNameProjectNamePermissions.cs
  3. 24
      content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Roles/Dtos/PermissionTreeDto.cs
  4. 6
      content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Users/Dtos/LoginOutputDto.cs
  5. 2
      content/aspnetcore/src/CompanyName.ProjectName.Application/Audits/AuditAppService.cs
  6. 80
      content/aspnetcore/src/CompanyName.ProjectName.Application/Roles/RoleAppService.cs
  7. 2
      content/aspnetcore/src/CompanyName.ProjectName.Application/Users/LoginAppService.cs
  8. 12
      content/aspnetcore/src/CompanyName.ProjectName.Application/Users/UserAppService.cs
  9. 5
      content/aspnetcore/src/CompanyName.ProjectName.Domain.Shared/Localization/CompanyNameProjectName/en.json
  10. 3
      content/aspnetcore/src/CompanyName.ProjectName.Domain.Shared/Localization/CompanyNameProjectName/zh-Hans.json
  11. 3
      content/vue/src/locales/lang/en/routes/admin.ts
  12. 4
      content/vue/src/locales/lang/zh_CN/routes/admin.ts
  13. 6
      content/vue/src/router/routes/modules/admin.ts
  14. 168
      content/vue/src/services/ServiceProxies.ts
  15. 2
      content/vue/src/services/ServiceProxyBase.ts
  16. 14
      content/vue/src/store/modules/user.ts
  17. 2
      content/vue/src/views/admin/roles/AbpRole.ts
  18. 105
      content/vue/src/views/admin/roles/PermissionAbpRole.vue
  19. 4
      content/vue/src/views/admin/users/AbpUser.vue
  20. 1
      content/vue/types/store.ts

18
content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Permissions/CompanyNameProjectNamePermissionDefinitionProvider.cs

@ -9,8 +9,22 @@ namespace CompanyNameProjectName.Permissions
public override void Define(IPermissionDefinitionContext context) public override void Define(IPermissionDefinitionContext context)
{ {
var abpIdentityGroup = context.GetGroup("AbpIdentity"); var abpIdentityGroup = context.GetGroup("AbpIdentity");
abpIdentityGroup.AddPermission("AbpIdentity.Users.Lock", L("Permission:Users:Enable")); var userManagement = abpIdentityGroup.GetPermissionOrNull("AbpIdentity.Users");
abpIdentityGroup.AddPermission("AbpIdentity.Users.AuditLog", L("Permission:Users:AuditLog"));
userManagement.AddChild("AbpIdentity.Users.Lock", L("Permission:Users:Enable"));
userManagement.AddChild("AbpIdentity.Users.Query", L("Permission:Query"));
var roleManagement = abpIdentityGroup.GetPermissionOrNull("AbpIdentity.Roles");
roleManagement.AddChild("AbpIdentity.Roles.Query", L("Permission:Query"));
var auditManagement = abpIdentityGroup.AddPermission("AbpIdentity.AuditLog", L("Permission:AuditLogMangament"));
auditManagement.AddChild("AbpIdentity.AuditLog.Query", L("Permission:Query"));
//abpIdentityGroup.AddPermission("AbpIdentity.Users.Lock", L("Permission:Users:Enable"));
//abpIdentityGroup.AddPermission("AbpIdentity.Users.AuditLog", L("Permission:Users:AuditLog"));
//Define your own permissions here. Example: //Define your own permissions here. Example:
//myGroup.AddPermission(CompanyNameProjectNamePermissions.MyPermission1, L("Permission:MyPermission1")); //myGroup.AddPermission(CompanyNameProjectNamePermissions.MyPermission1, L("Permission:MyPermission1"));
} }

7
content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Permissions/CompanyNameProjectNamePermissions.cs

@ -6,5 +6,12 @@
//Add your own permission names. Example: //Add your own permission names. Example:
//public const string MyPermission1 = GroupName + ".MyPermission1"; //public const string MyPermission1 = GroupName + ".MyPermission1";
public static class AuditLog
{
public const string Default = "AuditLog";
public const string AuditLogManagement = "AuditLog.AuditLogManagement";
public const string Query = "AuditLog.AuditLogManagement.Query";
}
} }
} }

24
content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Roles/Dtos/PermissionTreeDto.cs

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CompanyNameProjectName.Roles.Dtos
{
public class PermissionOutput {
public List<string> Grants { get; set; } = new List<string>();
public List<string> AllGrants { get; set; } = new List<string>();
public List<PermissionTreeDto> Permissions { get; set; } = new List<PermissionTreeDto>();
}
public class PermissionTreeDto
{
public string Title { get; set; }
public string Key { get; set; }
public List<PermissionTreeDto> Children { get; set; }=new List<PermissionTreeDto>();
}
}

6
content/aspnetcore/src/CompanyName.ProjectName.Application.Contracts/Users/Dtos/LoginOutputDto.cs

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
namespace CompanyNameProjectName.Dtos.Users namespace CompanyNameProjectName.Dtos.Users
{ {
@ -12,9 +13,6 @@ namespace CompanyNameProjectName.Dtos.Users
public string Token { get; set; } public string Token { get; set; }
/// <summary> public List<string> Roles { get; set; } = new List<string>();
/// 过期时间
/// </summary>
public DateTime Expiration { get; set; }
} }
} }

2
content/aspnetcore/src/CompanyName.ProjectName.Application/Audits/AuditAppService.cs

@ -14,7 +14,7 @@ using Volo.Abp.Domain.Repositories;
namespace CompanyNameProjectName.Audits namespace CompanyNameProjectName.Audits
{ {
[Authorize("AbpIdentity.Users.AuditLog")] [Authorize("AbpIdentity.AuditLog.Query")]
public class AuditAppService : ApplicationService public class AuditAppService : ApplicationService
{ {
private readonly IRepository<AuditLog, Guid> _auditLogRepository; private readonly IRepository<AuditLog, Guid> _auditLogRepository;

80
content/aspnetcore/src/CompanyName.ProjectName.Application/Roles/RoleAppService.cs

@ -14,11 +14,13 @@ using Volo.Abp.PermissionManagement;
namespace CompanyNameProjectName.Roles namespace CompanyNameProjectName.Roles
{ {
[Authorize]
public class RoleAppService : ApplicationService public class RoleAppService : ApplicationService
{ {
private readonly IIdentityRoleAppService _identityRoleAppService; private readonly IIdentityRoleAppService _identityRoleAppService;
private readonly IPermissionAppService _permissionAppService; private readonly IPermissionAppService _permissionAppService;
protected IIdentityRoleRepository _roleRepository; private readonly IIdentityRoleRepository _roleRepository;
public RoleAppService(IIdentityRoleAppService identityRoleAppService, IPermissionAppService permissionAppService, IIdentityRoleRepository roleRepository) public RoleAppService(IIdentityRoleAppService identityRoleAppService, IPermissionAppService permissionAppService, IIdentityRoleRepository roleRepository)
{ {
_identityRoleAppService = identityRoleAppService; _identityRoleAppService = identityRoleAppService;
@ -37,13 +39,17 @@ namespace CompanyNameProjectName.Roles
[HttpPost] [HttpPost]
[SwaggerOperation(summary: "分页获取角色列表", Tags = new[] { "Role" })] [SwaggerOperation(summary: "分页获取角色列表", Tags = new[] { "Role" })]
[Authorize("AbpIdentity.Roles.Query")]
public async Task<PagedResultDto<IdentityRoleDto>> ListAsync(GetRoleListInput input) public async Task<PagedResultDto<IdentityRoleDto>> ListAsync(GetRoleListInput input)
{ {
var request = new GetIdentityRolesInput(); var request = new GetIdentityRolesInput();
request.Filter = input.filter?.Trim(); request.Filter = input.filter?.Trim();
request.MaxResultCount = input.PageSize; request.MaxResultCount = input.PageSize;
request.SkipCount = (input.PageIndex - 1) * input.PageSize; request.SkipCount = (input.PageIndex - 1) * input.PageSize;
return await _identityRoleAppService.GetListAsync(request); List<IdentityRole> list = await _roleRepository.GetListAsync(request.Sorting, request.MaxResultCount, request.SkipCount, request.Filter).ConfigureAwait(continueOnCapturedContext: false);
return new PagedResultDto<IdentityRoleDto>(await _roleRepository.GetCountAsync(request.Filter).ConfigureAwait(continueOnCapturedContext: false), base.ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list));
//return await _identityRoleAppService.GetListAsync(request);
} }
[Authorize("AbpIdentity.Roles.Create")] [Authorize("AbpIdentity.Roles.Create")]
@ -70,9 +76,10 @@ namespace CompanyNameProjectName.Roles
} }
[SwaggerOperation(summary: "获取角色权限", Tags = new[] { "Role" })] [SwaggerOperation(summary: "获取角色权限", Tags = new[] { "Role" })]
public async Task<GetPermissionListResultDto> GetPermissionAsync(string providerName, string providerKey) public async Task<PermissionOutput> GetPermissionAsync(string providerName, string providerKey)
{ {
return await _permissionAppService.GetAsync(providerName, providerKey); var permissions = await _permissionAppService.GetAsync(providerName, providerKey);
return BuildTreeData(permissions.Groups);
} }
[SwaggerOperation(summary: "修改角色权限", Tags = new[] { "Role" })] [SwaggerOperation(summary: "修改角色权限", Tags = new[] { "Role" })]
@ -82,5 +89,70 @@ namespace CompanyNameProjectName.Roles
{ {
await _permissionAppService.UpdateAsync(input.ProviderName, input.ProviderKey, input.UpdatePermissionsDto); await _permissionAppService.UpdateAsync(input.ProviderName, input.ProviderKey, input.UpdatePermissionsDto);
} }
private PermissionOutput BuildTreeData(List<PermissionGroupDto> input)
{
var result = new PermissionOutput();
var excludes = new List<string> {
"AbpIdentity.Users.ManagePermissions",
"FeatureManagement",
"FeatureManagement.ManageHostFeatures",
"AbpTenantManagement",
"AbpTenantManagement.Tenants",
"AbpTenantManagement.Tenants.Create",
"AbpTenantManagement.Tenants.Update",
"AbpTenantManagement.Tenants.Delete",
"AbpTenantManagement.Tenants.ManageFeatures",
"AbpTenantManagement.Tenants.ManageConnectionStrings"
};
var permissions = new List<PermissionTreeDto>();
foreach (var group in input)
{
if (excludes.Any(e => e == group.Name)) continue;
var groupPermission = new PermissionTreeDto();
groupPermission.Key = group.Name;
groupPermission.Title = group.DisplayName;
foreach (var item in group.Permissions)
{
result.AllGrants.Add(item.Name);
if (item.IsGranted)
{
result.Grants.Add(item.Name);
}
//获取ParentName=null的权限
var management = group.Permissions.Where(e => e.ParentName.IsNullOrWhiteSpace()).ToList();
foreach (var managementItem in management)
{
if (!groupPermission.Children.Any(e => e.Key == managementItem.Name))
{
var managementPermission = new PermissionTreeDto()
{
Key = managementItem.Name,
Title = managementItem.DisplayName
};
// 获取management下权限
var childrenPermission = group.Permissions.Where(e => e.ParentName==managementItem.Name).ToList();
foreach (var childrenPermissionItem in childrenPermission)
{
managementPermission.Children.Add(new PermissionTreeDto()
{
Key = childrenPermissionItem.Name,
Title = childrenPermissionItem.DisplayName
});
}
groupPermission.Children.Add(managementPermission);
}
}
}
permissions.Add(groupPermission);
}
result.Permissions = permissions;
return result;
}
} }
} }

2
content/aspnetcore/src/CompanyName.ProjectName.Application/Users/LoginAppService.cs

@ -50,7 +50,7 @@ namespace CompanyNameProjectName.Users
var token = GenerateJwt(user, roles.ToList()); var token = GenerateJwt(user, roles.ToList());
var loginOutputDto = ObjectMapper.Map<IdentityUser, LoginOutputDto>(user); var loginOutputDto = ObjectMapper.Map<IdentityUser, LoginOutputDto>(user);
loginOutputDto.Token = token; loginOutputDto.Token = token;
loginOutputDto.Expiration = DateTime.Now.AddHours(_jwtOptions.ExpirationTime); loginOutputDto.Roles = roles.ToList();
return loginOutputDto; return loginOutputDto;
} }
catch(Exception ex) catch(Exception ex)

12
content/aspnetcore/src/CompanyName.ProjectName.Application/Users/UserAppService.cs

@ -20,15 +20,17 @@ namespace CompanyNameProjectName.Users
{ {
private readonly IIdentityUserAppService _identityUserAppService; private readonly IIdentityUserAppService _identityUserAppService;
private readonly IdentityUserManager _userManager; private readonly IdentityUserManager _userManager;
public UserAppService(IIdentityUserAppService identityUserAppService, IdentityUserManager userManager) protected IIdentityUserRepository _userRepository;
public UserAppService(IIdentityUserAppService identityUserAppService, IdentityUserManager userManager, IIdentityUserRepository userRepository)
{ {
_identityUserAppService = identityUserAppService; _identityUserAppService = identityUserAppService;
_userManager = userManager; _userManager = userManager;
_userRepository = userRepository;
} }
[SwaggerOperation(summary: "分页获取用户信息", Tags = new[] { "User" })] [SwaggerOperation(summary: "分页获取用户信息", Tags = new[] { "User" })]
[Authorize("AbpIdentity.Users")]
[HttpPost] [HttpPost]
[Authorize("AbpIdentity.Users.Query")]
public async Task<PagedResultDto<IdentityUserDto>> ListAsync(GetUserListInput input) public async Task<PagedResultDto<IdentityUserDto>> ListAsync(GetUserListInput input)
{ {
var request = new GetIdentityUsersInput(); var request = new GetIdentityUsersInput();
@ -36,7 +38,11 @@ namespace CompanyNameProjectName.Users
request.MaxResultCount = input.PageSize; request.MaxResultCount = input.PageSize;
request.SkipCount = (input.PageIndex - 1) * input.PageSize; request.SkipCount = (input.PageIndex - 1) * input.PageSize;
request.Sorting = " LastModificationTime desc"; request.Sorting = " LastModificationTime desc";
return await _identityUserAppService.GetListAsync(request); long count = await _userRepository.GetCountAsync(request.Filter).ConfigureAwait(continueOnCapturedContext: false);
List<Volo.Abp.Identity.IdentityUser> source = await _userRepository.GetListAsync(request.Sorting, request.MaxResultCount, request.SkipCount, request.Filter).ConfigureAwait(continueOnCapturedContext: false);
return new PagedResultDto<IdentityUserDto>(count, base.ObjectMapper.Map<List<Volo.Abp.Identity.IdentityUser>, List<IdentityUserDto>>(source));
// return await _identityUserAppService.GetListAsync(request);
} }
[SwaggerOperation(summary: "创建用户", Tags = new[] { "User" })] [SwaggerOperation(summary: "创建用户", Tags = new[] { "User" })]

5
content/aspnetcore/src/CompanyName.ProjectName.Domain.Shared/Localization/CompanyNameProjectName/en.json

@ -7,9 +7,10 @@
"DataExistence": "Existence", "DataExistence": "Existence",
"DataNotExistence": "Not Existence", "DataNotExistence": "Not Existence",
"TestSettings": "TestSettings", "TestSettings": "TestSettings",
"Permission:Query": "Query",
"Permission:Users:Enable": "Enable|Disable", "Permission:Users:Enable": "Enable|Disable",
"Permission:Users:AuditLog": "AuditLog" "Permission:AuditLogMangament": "AuditLogMangament",
"Permission:AuditLogMangament:Query": "Query"
} }
} }

3
content/aspnetcore/src/CompanyName.ProjectName.Domain.Shared/Localization/CompanyNameProjectName/zh-Hans.json

@ -10,6 +10,7 @@
"TestSettings": "测试Settings", "TestSettings": "测试Settings",
"Permission:Users:Enable": "启用|禁用", "Permission:Users:Enable": "启用|禁用",
"Permission:Users:AuditLog": "审计日志" "Permission:AuditLogMangament": "审计日志",
"Permission:AuditLogMangament:Query": "查询"
} }
} }

3
content/vue/src/locales/lang/en/routes/admin.ts

@ -33,5 +33,6 @@ export default {
audit_url: "URL", audit_url: "URL",
audit_entityInfo: "EntityInformation", audit_entityInfo: "EntityInformation",
audit_message: "Entity Message", audit_message: "Entity Message",
audit_applicationName:"ApplicationName" audit_applicationName:"ApplicationName",
grantedMessage:"Authorization Successful, Please Login Again."
}; };

4
content/vue/src/locales/lang/zh_CN/routes/admin.ts

@ -31,5 +31,7 @@ export default {
audit_url: "Url地址", audit_url: "Url地址",
audit_entityInfo: "实体信息", audit_entityInfo: "实体信息",
audit_message: "实体信息", audit_message: "实体信息",
audit_applicationName:"应用名称" audit_applicationName:"应用名称",
grantedMessage:"授权成功,请重新登录."
}; };

6
content/vue/src/router/routes/modules/admin.ts

@ -17,7 +17,7 @@ const admin: AppRouteModule = {
component: () => import('/@/views/admin/users/AbpUser.vue'), component: () => import('/@/views/admin/users/AbpUser.vue'),
meta: { meta: {
title: t('routes.admin.userManagement'), title: t('routes.admin.userManagement'),
policy: 'AbpIdentity.Users', policy: 'AbpIdentity.Users.Query',
icon: 'ant-design:skin-outlined' icon: 'ant-design:skin-outlined'
}, },
}, },
@ -27,7 +27,7 @@ const admin: AppRouteModule = {
component: () => import('/@/views/admin/roles/AbpRole.vue'), component: () => import('/@/views/admin/roles/AbpRole.vue'),
meta: { meta: {
title: t('routes.admin.roleManagement'), title: t('routes.admin.roleManagement'),
policy: 'AbpIdentity.Roles', policy: 'AbpIdentity.Roles.Query',
icon: 'ant-design:lock-outlined' icon: 'ant-design:lock-outlined'
}, },
}, },
@ -37,7 +37,7 @@ const admin: AppRouteModule = {
component: () => import('/@/views/admin/audits/AuditLog.vue'), component: () => import('/@/views/admin/audits/AuditLog.vue'),
meta: { meta: {
title: t('routes.admin.auditManagement'), title: t('routes.admin.auditManagement'),
policy: "AbpIdentity.Users.AuditLog", policy: "AbpIdentity.AuditLog.Query",
icon: 'ant-design:audit-outlined' icon: 'ant-design:audit-outlined'
}, },
} }

168
content/vue/src/services/ServiceProxies.ts

@ -1001,7 +1001,7 @@ export class RoleServiceProxy extends ServiceProxyBase {
* @param providerKey (optional) * @param providerKey (optional)
* @return Success * @return Success
*/ */
permission(providerName: string | undefined, providerKey: string | undefined , cancelToken?: CancelToken | undefined): Promise<GetPermissionListResultDto> { permission(providerName: string | undefined, providerKey: string | undefined , cancelToken?: CancelToken | undefined): Promise<PermissionOutput> {
let url_ = this.baseUrl + "/api/app/role/permission?"; let url_ = this.baseUrl + "/api/app/role/permission?";
if (providerName === null) if (providerName === null)
throw new Error("The parameter 'providerName' cannot be null."); throw new Error("The parameter 'providerName' cannot be null.");
@ -1035,7 +1035,7 @@ export class RoleServiceProxy extends ServiceProxyBase {
}); });
} }
protected processPermission(response: AxiosResponse): Promise<GetPermissionListResultDto> { protected processPermission(response: AxiosResponse): Promise<PermissionOutput> {
const status = response.status; const status = response.status;
let _headers: any = {}; let _headers: any = {};
if (response.headers && typeof response.headers === "object") { if (response.headers && typeof response.headers === "object") {
@ -1049,7 +1049,7 @@ export class RoleServiceProxy extends ServiceProxyBase {
const _responseText = response.data; const _responseText = response.data;
let result200: any = null; let result200: any = null;
let resultData200 = _responseText; let resultData200 = _responseText;
result200 = GetPermissionListResultDto.fromJS(resultData200); result200 = PermissionOutput.fromJS(resultData200);
return result200; return result200;
} else if (status === 403) { } else if (status === 403) {
const _responseText = response.data; const _responseText = response.data;
@ -1091,7 +1091,7 @@ export class RoleServiceProxy extends ServiceProxyBase {
const _responseText = response.data; const _responseText = response.data;
return throwException("An unexpected server error occurred.", status, _responseText, _headers); return throwException("An unexpected server error occurred.", status, _responseText, _headers);
} }
return Promise.resolve<GetPermissionListResultDto>(<any>null); return Promise.resolve<PermissionOutput>(<any>null);
} }
/** /**
@ -5085,7 +5085,7 @@ export class LoginOutputDto implements ILoginOutputDto {
name?: string | undefined; name?: string | undefined;
userName?: string | undefined; userName?: string | undefined;
token?: string | undefined; token?: string | undefined;
expiration?: Date; roles?: string[] | undefined;
constructor(data?: ILoginOutputDto) { constructor(data?: ILoginOutputDto) {
if (data) { if (data) {
@ -5102,7 +5102,11 @@ export class LoginOutputDto implements ILoginOutputDto {
this.name = _data["name"]; this.name = _data["name"];
this.userName = _data["userName"]; this.userName = _data["userName"];
this.token = _data["token"]; this.token = _data["token"];
this.expiration = _data["expiration"] ? new Date(_data["expiration"].toString()) : <any>undefined; if (Array.isArray(_data["roles"])) {
this.roles = [] as any;
for (let item of _data["roles"])
this.roles!.push(item);
}
} }
} }
@ -5119,7 +5123,11 @@ export class LoginOutputDto implements ILoginOutputDto {
data["name"] = this.name; data["name"] = this.name;
data["userName"] = this.userName; data["userName"] = this.userName;
data["token"] = this.token; data["token"] = this.token;
data["expiration"] = this.expiration ? this.expiration.toISOString() : <any>undefined; if (Array.isArray(this.roles)) {
data["roles"] = [];
for (let item of this.roles)
data["roles"].push(item);
}
return data; return data;
} }
} }
@ -5129,7 +5137,7 @@ export interface ILoginOutputDto {
name?: string | undefined; name?: string | undefined;
userName?: string | undefined; userName?: string | undefined;
token?: string | undefined; token?: string | undefined;
expiration?: Date; roles?: string[] | undefined;
} }
export enum LoginResultType { export enum LoginResultType {
@ -5660,6 +5668,126 @@ export interface IPermissionGroupDto {
permissions?: PermissionGrantInfoDto[] | undefined; permissions?: PermissionGrantInfoDto[] | undefined;
} }
export class PermissionOutput implements IPermissionOutput {
grants?: string[] | undefined;
allGrants?: string[] | undefined;
permissions?: PermissionTreeDto[] | undefined;
constructor(data?: IPermissionOutput) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
if (Array.isArray(_data["grants"])) {
this.grants = [] as any;
for (let item of _data["grants"])
this.grants!.push(item);
}
if (Array.isArray(_data["allGrants"])) {
this.allGrants = [] as any;
for (let item of _data["allGrants"])
this.allGrants!.push(item);
}
if (Array.isArray(_data["permissions"])) {
this.permissions = [] as any;
for (let item of _data["permissions"])
this.permissions!.push(PermissionTreeDto.fromJS(item));
}
}
}
static fromJS(data: any): PermissionOutput {
data = typeof data === 'object' ? data : {};
let result = new PermissionOutput();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
if (Array.isArray(this.grants)) {
data["grants"] = [];
for (let item of this.grants)
data["grants"].push(item);
}
if (Array.isArray(this.allGrants)) {
data["allGrants"] = [];
for (let item of this.allGrants)
data["allGrants"].push(item);
}
if (Array.isArray(this.permissions)) {
data["permissions"] = [];
for (let item of this.permissions)
data["permissions"].push(item.toJSON());
}
return data;
}
}
export interface IPermissionOutput {
grants?: string[] | undefined;
allGrants?: string[] | undefined;
permissions?: PermissionTreeDto[] | undefined;
}
export class PermissionTreeDto implements IPermissionTreeDto {
title?: string | undefined;
key?: string | undefined;
children?: PermissionTreeDto[] | undefined;
constructor(data?: IPermissionTreeDto) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.title = _data["title"];
this.key = _data["key"];
if (Array.isArray(_data["children"])) {
this.children = [] as any;
for (let item of _data["children"])
this.children!.push(PermissionTreeDto.fromJS(item));
}
}
}
static fromJS(data: any): PermissionTreeDto {
data = typeof data === 'object' ? data : {};
let result = new PermissionTreeDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["title"] = this.title;
data["key"] = this.key;
if (Array.isArray(this.children)) {
data["children"] = [];
for (let item of this.children)
data["children"].push(item.toJSON());
}
return data;
}
}
export interface IPermissionTreeDto {
title?: string | undefined;
key?: string | undefined;
children?: PermissionTreeDto[] | undefined;
}
export class ProfileDto implements IProfileDto { export class ProfileDto implements IProfileDto {
readonly extraProperties?: { [key: string]: any; } | undefined; readonly extraProperties?: { [key: string]: any; } | undefined;
userName?: string | undefined; userName?: string | undefined;
@ -5965,8 +6093,6 @@ export class QueryAuditLogOutput implements IQueryAuditLogOutput {
exceptions?: string | undefined; exceptions?: string | undefined;
comments?: string | undefined; comments?: string | undefined;
httpStatusCode?: number | undefined; httpStatusCode?: number | undefined;
readonly entityChanges?: QueryEntityChangeOutput[] | undefined;
readonly actions?: PropertyChangesDto[] | undefined;
constructor(data?: IQueryAuditLogOutput) { constructor(data?: IQueryAuditLogOutput) {
if (data) { if (data) {
@ -5999,16 +6125,6 @@ export class QueryAuditLogOutput implements IQueryAuditLogOutput {
this.exceptions = _data["exceptions"]; this.exceptions = _data["exceptions"];
this.comments = _data["comments"]; this.comments = _data["comments"];
this.httpStatusCode = _data["httpStatusCode"]; this.httpStatusCode = _data["httpStatusCode"];
if (Array.isArray(_data["entityChanges"])) {
(<any>this).entityChanges = [] as any;
for (let item of _data["entityChanges"])
(<any>this).entityChanges!.push(QueryEntityChangeOutput.fromJS(item));
}
if (Array.isArray(_data["actions"])) {
(<any>this).actions = [] as any;
for (let item of _data["actions"])
(<any>this).actions!.push(PropertyChangesDto.fromJS(item));
}
} }
} }
@ -6041,16 +6157,6 @@ export class QueryAuditLogOutput implements IQueryAuditLogOutput {
data["exceptions"] = this.exceptions; data["exceptions"] = this.exceptions;
data["comments"] = this.comments; data["comments"] = this.comments;
data["httpStatusCode"] = this.httpStatusCode; data["httpStatusCode"] = this.httpStatusCode;
if (Array.isArray(this.entityChanges)) {
data["entityChanges"] = [];
for (let item of this.entityChanges)
data["entityChanges"].push(item.toJSON());
}
if (Array.isArray(this.actions)) {
data["actions"] = [];
for (let item of this.actions)
data["actions"].push(item.toJSON());
}
return data; return data;
} }
} }
@ -6076,8 +6182,6 @@ export interface IQueryAuditLogOutput {
exceptions?: string | undefined; exceptions?: string | undefined;
comments?: string | undefined; comments?: string | undefined;
httpStatusCode?: number | undefined; httpStatusCode?: number | undefined;
entityChanges?: QueryEntityChangeOutput[] | undefined;
actions?: PropertyChangesDto[] | undefined;
} }
export class QueryAuditLogOutputPagedResultDto implements IQueryAuditLogOutputPagedResultDto { export class QueryAuditLogOutputPagedResultDto implements IQueryAuditLogOutputPagedResultDto {

2
content/vue/src/services/ServiceProxyBase.ts

@ -9,7 +9,7 @@ export class ServiceProxyBase {
protected transformOptions(options: AxiosRequestConfig) { protected transformOptions(options: AxiosRequestConfig) {
options.baseURL = import.meta.env.VITE_API_URL as string; // 'http://localhost:50010' options.baseURL = import.meta.env.VITE_API_URL as string;
const guard: boolean = this.urlGuard(options.url as string); const guard: boolean = this.urlGuard(options.url as string);
if (!guard) { if (!guard) {
const { token, language } = this.getHeaderInfo(); const { token, language } = this.getHeaderInfo();

14
content/vue/src/store/modules/user.ts

@ -11,11 +11,10 @@ import { ROLES_KEY, TOKEN_KEY, USER_INFO_KEY, ABP_LOCALE_KEY } from '/@/enums/ca
import { getAuthCache, setAuthCache } from '/@/utils/auth'; import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { import {
GetUserInfoByUserIdModel, GetUserInfoByUserIdModel,
GetUserInfoByUserIdParams,
LoginParams, LoginParams,
} from '/@/api/sys/model/userModel'; } from '/@/api/sys/model/userModel';
import { usePermissionStore } from './permission' import { usePermissionStore } from './permission'
import { getUserInfoById, login, getAbpApplicationConfiguration } from '/@/api/sys/user'; import { login, getAbpApplicationConfiguration } from '/@/api/sys/user';
import { LoginInputDto } from '/@/services/ServiceProxies' import { LoginInputDto } from '/@/services/ServiceProxies'
import { useI18n } from '/@/hooks/web/useI18n'; import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage'; import { useMessage } from '/@/hooks/web/useMessage';
@ -93,7 +92,7 @@ export const useUserStore = defineStore({
const data = await login(request); const data = await login(request);
this.setToken(data.token as string); this.setToken(data.token as string);
this.setUserInfo({ userId: data.id as string, username: data.userName as string, realName: data.name as string }); this.setUserInfo({ userId: data.id as string, username: data.userName as string, realName: data.name as string,roles:data.roles as [] });
await this.getAbpApplicationConfigurationAsync(); await this.getAbpApplicationConfigurationAsync();
goHome && (await router.replace(PageEnum.BASE_HOME)); goHome && (await router.replace(PageEnum.BASE_HOME));
@ -109,14 +108,7 @@ export const useUserStore = defineStore({
permissionStore.setPermCodeList(grantPolicy); permissionStore.setPermCodeList(grantPolicy);
}, },
async getUserInfoAction({ userId }: GetUserInfoByUserIdParams) {
const userInfo = await getUserInfoById({ userId });
const { roles } = userInfo;
const roleList = roles.map((item) => item.value) as RoleEnum[];
this.setUserInfo(userInfo);
this.setRoleList(roleList);
return userInfo;
},
/** /**

2
content/vue/src/views/admin/roles/AbpRole.ts

@ -155,7 +155,7 @@ export async function updateRolePermissionAsync({ request, closeDrawer, setDrawe
const _roleServiceProxy = new RoleServiceProxy(); const _roleServiceProxy = new RoleServiceProxy();
await _roleServiceProxy.updatePermission(request); await _roleServiceProxy.updatePermission(request);
setDrawerProps({ loading: false }); setDrawerProps({ loading: false });
message.success(t('common.operationSuccess'));
closeDrawer(); closeDrawer();
} }

105
content/vue/src/views/admin/roles/PermissionAbpRole.vue

@ -4,18 +4,10 @@
:title="t('routes.admin.roleManagement_permission')" :title="t('routes.admin.roleManagement_permission')"
width="20%" width="20%"
> >
<!-- <a-tree
checkable
:tree-data="allPermissionsRef"
v-model:checkedKeys="currentRolePermissionsRef"
>
<template #title0010><span style="color: #1890ff"></span></template>
</a-tree> -->
<BasicTree <BasicTree
:treeData="allPermissionsRef" :treeData="allPermissionsRef"
checkable checkable
v-model:checkedKeys="currentRolePermissionsRef" ref="treeRef"
/> />
<div <div
:style="{ :style="{
@ -41,19 +33,18 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, reactive, ref } from 'vue'; import { defineComponent, reactive, ref,unref,toRaw } from 'vue';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'; import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { getRolePermissionAsync, updateRolePermissionAsync, excludePermission } from './AbpRole'; import { getRolePermissionAsync, updateRolePermissionAsync } from './AbpRole';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
import { useI18n } from '/@/hooks/web/useI18n'; import { useI18n } from '/@/hooks/web/useI18n';
import { BasicTree } from '/@/components/Tree/index'; import { BasicTree,TreeActionType } from '/@/components/Tree/index';
import { usePermissionStore } from '/@/store/modules/permission'; import { useUserStoreWidthOut } from '/@/store/modules/user';
import { import {
UpdateRolePermissionsDto, UpdateRolePermissionsDto,
UpdatePermissionDto, UpdatePermissionDto,
UpdatePermissionsDto, UpdatePermissionsDto,
} from '/@/services/ServiceProxies'; } from '/@/services/ServiceProxies';
import { message } from 'ant-design-vue';
export default defineComponent({ export default defineComponent({
name: 'PermissionAbpRole', name: 'PermissionAbpRole',
components: { BasicDrawer, BasicTree }, components: { BasicDrawer, BasicTree },
@ -65,71 +56,87 @@
await getRolePermissions(data.record.name); await getRolePermissions(data.record.name);
//loading.value = false; //loading.value = false;
}); });
const currentRolePermissionsRef = ref<string[]>([]); const treeRef = ref<Nullable<TreeActionType>>(null);
let allPermissions: TreeDataItem[] = [];
let allPermissionsRef = reactive(allPermissions); const totalRolePermissionsRef = reactive([]);
let allPermissionsRef = reactive([]);
const getTree =()=> {
const tree = unref(treeRef);
if (!tree) {
throw new Error('tree is null!');
}
return tree;
}
/** /**
* 获取权限信息并且构造权限树 * 获取权限信息并且构造权限树
*/ */
const getRolePermissions = async (roleName: string) => { const getRolePermissions = async (roleName: string) => {
setDrawerProps({ loading: true }); setDrawerProps({ loading: true });
currentRolePermissionsRef.value.splice(0, currentRolePermissionsRef.value.length); totalRolePermissionsRef.splice(0, totalRolePermissionsRef.length);
allPermissionsRef.splice(0, allPermissionsRef.length); allPermissionsRef.splice(0, allPermissionsRef.length);
const permissions = await getRolePermissionAsync(roleName); const permissions = await getRolePermissionAsync(roleName);
permissions.groups?.forEach((item) => { totalRolePermissionsRef.push(...permissions.allGrants as []);
if (excludePermission(item.name as string)) return; allPermissionsRef.push(...permissions.permissions as []);
let temp: TreeDataItem = { getTree().setCheckedKeys(permissions.grants as [])
title: item.displayName,
key: item.name,
children: [],
};
item.permissions?.forEach((perItem) => {
if (excludePermission(perItem.name as string)) return;
let childrenItem: TreeDataItem = {};
childrenItem.title = perItem.displayName;
childrenItem.key = perItem.name;
temp.children?.push(childrenItem);
if (perItem.isGranted) {
currentRolePermissionsRef.value.push(perItem.name as string);
}
});
allPermissionsRef.push(temp);
});
setDrawerProps({ loading: false }); setDrawerProps({ loading: false });
}; };
const submitRolePermisstionAsync = async () => { const submitRolePermisstionAsync = async () => {
debugger;
let request: UpdateRolePermissionsDto = new UpdateRolePermissionsDto(); let request: UpdateRolePermissionsDto = new UpdateRolePermissionsDto();
request.updatePermissionsDto = new UpdatePermissionsDto(); request.updatePermissionsDto = new UpdatePermissionsDto();
let permisstions: UpdatePermissionDto[] = []; let permisstions: UpdatePermissionDto[] = [];
request.providerName = 'R'; request.providerName = 'R';
request.providerKey = roleName; request.providerKey = roleName;
const keys = toRaw(getTree().getCheckedKeys()) as [];
currentRolePermissionsRef.value.forEach((item) => { const noSelectedPermissions = totalRolePermissionsRef.filter(e=>{return !(keys.indexOf(e)>-1)});
if (item.indexOf('.') > 0) { noSelectedPermissions.forEach((item:string) => {
let permisstion = new UpdatePermissionDto();
if(item.includes('.'))
{
let permisstion = new UpdatePermissionDto();
permisstion.name = item; permisstion.name = item;
permisstion.isGranted = true; permisstion.isGranted = false;
permisstions.push(permisstion); permisstions.push(permisstion);
} }
});
keys.forEach((item:string) => {
if(item.includes('.')){
let permisstion = new UpdatePermissionDto();
permisstion.name = item;
permisstion.isGranted = true;
permisstions.push(permisstion);
}
}); });
request.updatePermissionsDto.permissions = permisstions; request.updatePermissionsDto.permissions = permisstions;
await updateRolePermissionAsync({ request, closeDrawer, setDrawerProps }); await updateRolePermissionAsync({ request, closeDrawer, setDrawerProps });
const permissionStore = usePermissionStore(); const userStore = useUserStoreWidthOut();
const grantPolicy = Object.values(currentRolePermissionsRef.value as object); if(userStore.getUserInfo.roles.includes(roleName))
permissionStore.setPermCodeList(grantPolicy); {
message.success(t('routes.admin.grantedMessage'))
userStore.logout(true);
}else
{
message.success(t('common.operationSuccess'));
}
}; };
return { return {
t, t,
registerDrawer, registerDrawer,
allPermissionsRef, allPermissionsRef,
currentRolePermissionsRef,
submitRolePermisstionAsync, submitRolePermisstionAsync,
closeDrawer, closeDrawer,
treeRef
}; };
}, },
}); });

4
content/vue/src/views/admin/users/AbpUser.vue

@ -11,8 +11,8 @@
</a-button> </a-button>
</template> </template>
<template #lockoutEnabled="{ record }"> <template #lockoutEnabled="{ record }">
<Tag :color="record.lockoutEnabled && record.lockoutEnd!=null ? 'red' : 'green'"> <Tag :color="!record.lockoutEnabled ? 'green' : 'red'">
{{ record.lockoutEnabled && record.lockoutEnd!=null ? t('common.enable') : t('common.disable') }} {{ !record.lockoutEnabled ? t('common.enable') : t('common.disable') }}
</Tag> </Tag>
</template> </template>
<template #action="{ record }"> <template #action="{ record }">

1
content/vue/types/store.ts

@ -34,6 +34,7 @@ export interface UserInfo {
username: string; username: string;
realName: string; realName: string;
desc?: string; desc?: string;
roles:string[]
} }
export interface BeforeMiniState { export interface BeforeMiniState {

Loading…
Cancel
Save