CS2-123: Added models for user roles and permissions. Fixed auth UserToken.

This commit is contained in:
KharchenkoVladimir 2021-11-24 11:30:29 +05:00
parent 3dc7bc216e
commit 872598dcdd
14 changed files with 3383 additions and 56 deletions

View File

@ -4,8 +4,6 @@
{
public string Login { get; set; }
public int? Level { get; set; }
public string Name { get; set; }
public string Surname { get; set; }

View File

@ -6,8 +6,6 @@
public int? IdCompany { get; set; }
public int? IdRole { get; set; }
public string Password { get; set; }
public CompanyDto Company { get; set; }

View File

@ -1,10 +1,13 @@
namespace AsbCloudApp.Data
using System.Collections.Generic;
namespace AsbCloudApp.Data
{
public class UserTokenDto : UserBaseDto
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string RoleName { get; set; }
public IDictionary<string, int> Permissions { get; set; }
public IEnumerable<string> RoleNames { get; set; }
public string Token { get; set; }
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,184 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace AsbCloudDb.Migrations
{
public partial class Add_UserRoles_Permissions : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_t_user_t_user_role_id_role",
table: "t_user");
migrationBuilder.DropIndex(
name: "IX_t_user_id_role",
table: "t_user");
migrationBuilder.DropColumn(
name: "id_role",
table: "t_user");
migrationBuilder.DropColumn(
name: "level",
table: "t_user");
migrationBuilder.AddColumn<int>(
name: "id_parent",
table: "t_user_role",
type: "integer",
nullable: false,
defaultValue: 0,
comment: "От какой роли унаследована данная роль");
migrationBuilder.AddColumn<int>(
name: "role_type",
table: "t_user_role",
type: "integer",
nullable: false,
defaultValue: 0,
comment: "0-роль из стандартной матрицы, \n1-специальная роль для какого-либо пользователя");
migrationBuilder.CreateTable(
name: "t_permission",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
caption = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true, comment: "Название"),
type = table.Column<int>(type: "integer", nullable: false, comment: "1-чтение, 2-запись, 3-чтение и запись")
},
constraints: table =>
{
table.PrimaryKey("PK_t_permission", x => x.id);
},
comment: "Разрешения на доступ к данным");
migrationBuilder.CreateTable(
name: "t_relation_user_user_role",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_user = table.Column<int>(type: "integer", nullable: false),
id_user_role = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_t_relation_user_user_role", x => x.id);
table.ForeignKey(
name: "FK_t_relation_user_user_role_t_user_id_user",
column: x => x.id_user,
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_relation_user_user_role_t_user_role_id_user_role",
column: x => x.id_user_role,
principalTable: "t_user_role",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Отношение пользователей и ролей");
migrationBuilder.CreateTable(
name: "t_relation_user_role_permission",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_user_role = table.Column<int>(type: "integer", nullable: false),
id_permission = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_t_relation_user_role_permission", x => x.id);
table.ForeignKey(
name: "FK_t_relation_user_role_permission_t_permission_id_permission",
column: x => x.id_permission,
principalTable: "t_permission",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_relation_user_role_permission_t_user_role_id_user_role",
column: x => x.id_user_role,
principalTable: "t_user_role",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Отношение ролей пользователей и разрешений доступа");
migrationBuilder.CreateIndex(
name: "IX_t_relation_user_role_permission_id_permission",
table: "t_relation_user_role_permission",
column: "id_permission");
migrationBuilder.CreateIndex(
name: "IX_t_relation_user_role_permission_id_user_role",
table: "t_relation_user_role_permission",
column: "id_user_role");
migrationBuilder.CreateIndex(
name: "IX_t_relation_user_user_role_id_user",
table: "t_relation_user_user_role",
column: "id_user");
migrationBuilder.CreateIndex(
name: "IX_t_relation_user_user_role_id_user_role",
table: "t_relation_user_user_role",
column: "id_user_role");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_relation_user_role_permission");
migrationBuilder.DropTable(
name: "t_relation_user_user_role");
migrationBuilder.DropTable(
name: "t_permission");
migrationBuilder.DropColumn(
name: "id_parent",
table: "t_user_role");
migrationBuilder.DropColumn(
name: "role_type",
table: "t_user_role");
migrationBuilder.AddColumn<int>(
name: "id_role",
table: "t_user",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "level",
table: "t_user",
type: "integer",
nullable: true);
migrationBuilder.UpdateData(
table: "t_user",
keyColumn: "id",
keyValue: 1,
columns: new[] { "id_role", "level" },
values: new object[] { 1, 2147483647 });
migrationBuilder.CreateIndex(
name: "IX_t_user_id_role",
table: "t_user",
column: "id_role");
migrationBuilder.AddForeignKey(
name: "FK_t_user_t_user_role_id_role",
table: "t_user",
column: "id_role",
principalTable: "t_user_role",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
}
}
}

View File

@ -681,6 +681,33 @@ namespace AsbCloudDb.Migrations
});
});
modelBuilder.Entity("AsbCloudDb.Model.Permission", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Caption")
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("caption")
.HasComment("Название");
b.Property<int>("Type")
.HasColumnType("integer")
.HasColumnName("type")
.HasComment("1-чтение, 2-запись, 3-чтение и запись");
b.HasKey("Id");
b.ToTable("t_permission");
b
.HasComment("Разрешения на доступ к данным");
});
modelBuilder.Entity("AsbCloudDb.Model.RelationCompanyWell", b =>
{
b.Property<int>("IdCompany")
@ -701,6 +728,62 @@ namespace AsbCloudDb.Migrations
.HasComment("отношение скважин и компаний");
});
modelBuilder.Entity("AsbCloudDb.Model.RelationUserRolePermission", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("IdPermission")
.HasColumnType("integer")
.HasColumnName("id_permission");
b.Property<int>("IdUserRole")
.HasColumnType("integer")
.HasColumnName("id_user_role");
b.HasKey("Id");
b.HasIndex("IdPermission");
b.HasIndex("IdUserRole");
b.ToTable("t_relation_user_role_permission");
b
.HasComment("Отношение ролей пользователей и разрешений доступа");
});
modelBuilder.Entity("AsbCloudDb.Model.RelationUserUserRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user");
b.Property<int>("IdUserRole")
.HasColumnType("integer")
.HasColumnName("id_user_role");
b.HasKey("Id");
b.HasIndex("IdUser");
b.HasIndex("IdUserRole");
b.ToTable("t_relation_user_user_role");
b
.HasComment("Отношение пользователей и ролей");
});
modelBuilder.Entity("AsbCloudDb.Model.ReportProperty", b =>
{
b.Property<int>("Id")
@ -1549,14 +1632,6 @@ namespace AsbCloudDb.Migrations
.HasColumnType("integer")
.HasColumnName("id_company");
b.Property<int?>("IdRole")
.HasColumnType("integer")
.HasColumnName("id_role");
b.Property<int?>("Level")
.HasColumnType("integer")
.HasColumnName("level");
b.Property<string>("Login")
.HasMaxLength(255)
.HasColumnType("character varying(255)")
@ -1607,8 +1682,6 @@ namespace AsbCloudDb.Migrations
b.HasIndex("IdCompany");
b.HasIndex("IdRole");
b.HasIndex("Login")
.IsUnique();
@ -1622,8 +1695,6 @@ namespace AsbCloudDb.Migrations
{
Id = 1,
IdCompany = 1,
IdRole = 1,
Level = 2147483647,
Login = "dev",
Name = "Разработчик",
PasswordHash = "Vlcj|4fa529103dde7ff72cfe76185f344d4aa87931f8e1b2044e8a7739947c3d18923464eaad93843e4f809c5e126d013072"
@ -1644,6 +1715,16 @@ namespace AsbCloudDb.Migrations
.HasColumnName("caption")
.HasComment("Название");
b.Property<int>("IdParent")
.HasColumnType("integer")
.HasColumnName("id_parent")
.HasComment("От какой роли унаследована данная роль");
b.Property<int>("RoleType")
.HasColumnType("integer")
.HasColumnName("role_type")
.HasComment("0-роль из стандартной матрицы, \n1-специальная роль для какого-либо пользователя");
b.HasKey("Id");
b.ToTable("t_user_role");
@ -1655,12 +1736,16 @@ namespace AsbCloudDb.Migrations
new
{
Id = 1,
Caption = "Администратор"
Caption = "Администратор",
IdParent = 0,
RoleType = 0
},
new
{
Id = 2,
Caption = "Пользователь"
Caption = "Пользователь",
IdParent = 0,
RoleType = 0
});
});
@ -2472,6 +2557,44 @@ namespace AsbCloudDb.Migrations
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.RelationUserRolePermission", b =>
{
b.HasOne("AsbCloudDb.Model.Permission", "Permission")
.WithMany("RelationUserRolesPermissions")
.HasForeignKey("IdPermission")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.UserRole", "UserRole")
.WithMany("RelationUserRolesPermissions")
.HasForeignKey("IdUserRole")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Permission");
b.Navigation("UserRole");
});
modelBuilder.Entity("AsbCloudDb.Model.RelationUserUserRole", b =>
{
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany("RelationUsersUserRoles")
.HasForeignKey("IdUser")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.UserRole", "UserRole")
.WithMany("RelationUsersUserRoles")
.HasForeignKey("IdUserRole")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("UserRole");
});
modelBuilder.Entity("AsbCloudDb.Model.ReportProperty", b =>
{
b.HasOne("AsbCloudDb.Model.FileInfo", "File")
@ -2580,13 +2703,7 @@ namespace AsbCloudDb.Migrations
.HasConstraintName("t_user_t_company_id_fk")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("AsbCloudDb.Model.UserRole", "Role")
.WithMany("Users")
.HasForeignKey("IdRole");
b.Navigation("Company");
b.Navigation("Role");
});
modelBuilder.Entity("AsbCloudDb.Model.Well", b =>
@ -2702,6 +2819,11 @@ namespace AsbCloudDb.Migrations
b.Navigation("Measures");
});
modelBuilder.Entity("AsbCloudDb.Model.Permission", b =>
{
b.Navigation("RelationUserRolesPermissions");
});
modelBuilder.Entity("AsbCloudDb.Model.Telemetry", b =>
{
b.Navigation("Analysis");
@ -2724,11 +2846,15 @@ namespace AsbCloudDb.Migrations
b.Navigation("FileMarks");
b.Navigation("Files");
b.Navigation("RelationUsersUserRoles");
});
modelBuilder.Entity("AsbCloudDb.Model.UserRole", b =>
{
b.Navigation("Users");
b.Navigation("RelationUserRolesPermissions");
b.Navigation("RelationUsersUserRoles");
});
modelBuilder.Entity("AsbCloudDb.Model.Well", b =>

View File

@ -38,6 +38,9 @@ namespace AsbCloudDb.Model
public virtual DbSet<WellType> WellTypes { get; set; }
public virtual DbSet<DrillParams> DrillParams { get; set; }
public virtual DbSet<DrillFlowChart> DrillFlowChart { get; set; }
public virtual DbSet<RelationUserUserRole> RelationUserUserRoles { get; set; }
public virtual DbSet<RelationUserRolePermission> RelationUserRolesPermissions { get; set; }
public virtual DbSet<Permission> Permissions { get; set; }
//var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
// .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
@ -264,8 +267,6 @@ namespace AsbCloudDb.Model
new User{
Id = 1,
IdCompany = 1,
IdRole = 1,
Level = int.MaxValue,
Login = "dev",
PasswordHash = "Vlcj|4fa529103dde7ff72cfe76185f344d4aa87931f8e1b2044e8a7739947c3d18923464eaad93843e4f809c5e126d013072", // dev
Name = "Разработчик",
@ -437,7 +438,8 @@ namespace AsbCloudDb.Model
public IQueryable<User> GetUsersByLogin(string login)
=> Users
.Include(e => e.Role)
.Include(e => e.RelationUsersUserRoles)
.ThenInclude(r => r.UserRole)
.Include(e => e.Company)
.Where(e => e.Login == login);

View File

@ -36,6 +36,9 @@ namespace AsbCloudDb.Model
DbSet<TelemetryDataSpin> TelemetryDataSpin { get; set; }
DbSet<DrillParams> DrillParams { get; set; }
DbSet<DrillFlowChart> DrillFlowChart { get; set; }
DbSet<RelationUserUserRole> RelationUserUserRoles { get; set; }
DbSet<RelationUserRolePermission> RelationUserRolesPermissions { get; set; }
DbSet<Permission> Permissions { get; set; }
DatabaseFacade Database { get; }

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_permission"), Comment("Разрешения на доступ к данным")]
public class Permission
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("caption"), Comment("Название")]
[StringLength(255)]
public string Caption { get; set; }
[Column("type"), Comment("1-чтение, 2-запись, 3-чтение и запись")]
public int Type { get; set; }
[InverseProperty(nameof(RelationUserRolePermission.Permission))]
public virtual ICollection<RelationUserRolePermission> RelationUserRolesPermissions { get; set; }
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudDb.Model
{
[Table("t_relation_user_role_permission"), Comment("Отношение ролей пользователей и разрешений доступа")]
public class RelationUserRolePermission
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("id_user_role")]
public int IdUserRole { get; set; }
[Column("id_permission")]
public int IdPermission { get; set; }
[ForeignKey(nameof(IdUserRole))]
[InverseProperty(nameof(Model.UserRole.RelationUserRolesPermissions))]
public virtual UserRole UserRole { get; set; }
[ForeignKey(nameof(IdPermission))]
[InverseProperty(nameof(Model.Permission.RelationUserRolesPermissions))]
public virtual Permission Permission { get; set; }
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudDb.Model
{
[Table("t_relation_user_user_role"), Comment("Отношение пользователей и ролей")]
public class RelationUserUserRole
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("id_user")]
public int IdUser { get; set; }
[Column("id_user_role")]
public int IdUserRole { get; set; }
[ForeignKey(nameof(IdUser))]
[InverseProperty(nameof(Model.User.RelationUsersUserRoles))]
public virtual User User { get; set; }
[ForeignKey(nameof(IdUserRole))]
[InverseProperty(nameof(Model.UserRole.RelationUsersUserRoles))]
public virtual UserRole UserRole { get; set; }
}
}

View File

@ -17,9 +17,6 @@ namespace AsbCloudDb.Model
[Column("id_company")]
public int? IdCompany { get; set; }
[Column("id_role")]
public int? IdRole { get; set; }
[Column("login")]
[StringLength(255)]
public string Login { get; set; }
@ -31,9 +28,6 @@ namespace AsbCloudDb.Model
[Column("state"), Comment("состояние:\n100 - удален")]
public short? State { get; set; }
[Column("level")]
public int? Level { get; set; }
[Column("name"), Comment("имя")]
[StringLength(255)]
public string Name { get; set; }
@ -62,12 +56,10 @@ namespace AsbCloudDb.Model
[ForeignKey(nameof(IdCompany))]
[InverseProperty(nameof(Model.Company.Users))]
public virtual Company Company { get; set; }
[ForeignKey(nameof(IdRole))]
[InverseProperty(nameof(Model.UserRole.Users))]
public virtual UserRole Role { get; set; }
[InverseProperty(nameof(RelationUserUserRole.User))]
public virtual ICollection<RelationUserUserRole> RelationUsersUserRoles { get; set; }
[InverseProperty(nameof(FileInfo.Author))]
public virtual ICollection<FileInfo> Files { get; set; }

View File

@ -9,11 +9,6 @@ namespace AsbCloudDb.Model
[Table("t_user_role"), Comment("Роли пользователей в системе")]
public class UserRole : IId
{
public UserRole()
{
Users = new HashSet<User>();
}
[Key]
[Column("id")]
public int Id { get; set; }
@ -22,7 +17,17 @@ namespace AsbCloudDb.Model
[StringLength(255)]
public string Caption { get; set; }
[InverseProperty(nameof(User.Role))]
public virtual ICollection<User> Users { get; set; }
[Column("role_type"), Comment("0-роль из стандартной матрицы, \n1-специальная роль для какого-либо пользователя")]
public int RoleType { get; set; }
[Column("id_parent"), Comment("От какой роли унаследована данная роль")]
public int IdParent { get; set; }
[InverseProperty(nameof(RelationUserUserRole.UserRole))]
public virtual ICollection<RelationUserUserRole> RelationUsersUserRoles { get; set; }
[InverseProperty(nameof(RelationUserRolePermission.UserRole))]
public virtual ICollection<RelationUserRolePermission> RelationUserRolesPermissions { get; set; }
}
}

View File

@ -12,12 +12,17 @@ using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudInfrastructure.Services.Cache;
namespace AsbCloudInfrastructure.Services
{
public class AuthService : IAuthService
{
private readonly IAsbCloudDbContext db;
private readonly CacheTable<UserRole> cacheUserRoles;
private readonly CacheTable<RelationUserUserRole> cacheUsersUserRoles;
private readonly CacheTable<Permission> cachePermissions;
private readonly CacheTable<RelationUserRolePermission> cacheUserRolesPermissions;
public const string issuer = "a";
public const string audience = "a";
@ -32,15 +37,19 @@ namespace AsbCloudInfrastructure.Services
private readonly HashAlgorithm hashAlgoritm;
private readonly Random rnd;
public AuthService(IAsbCloudDbContext db)
public AuthService(IAsbCloudDbContext db, CacheDb cacheDb)
{
this.db = db;
cacheUserRoles = cacheDb.GetCachedTable<UserRole>((AsbCloudDbContext)db);
cacheUsersUserRoles = cacheDb.GetCachedTable<RelationUserUserRole>((AsbCloudDbContext)db);
cachePermissions = cacheDb.GetCachedTable<Permission>((AsbCloudDbContext)db);
cacheUserRolesPermissions = cacheDb.GetCachedTable<RelationUserRolePermission>((AsbCloudDbContext)db);
hashAlgoritm = SHA384.Create();
rnd = new Random((int)(DateTime.Now.Ticks % 2147480161));
}
public async Task<UserTokenDto> LoginAsync(string login, string password,
CancellationToken token = default)
CancellationToken token)
{
var (identity, user) = await GetClaimsUserAsync(login, password, token)
.ConfigureAwait(false);
@ -48,15 +57,19 @@ namespace AsbCloudInfrastructure.Services
if (identity == default || user.State == 0)
return null;
var idCaptionRoles = GetUserRolesIdsNames(user.Id);
var userPermissions = GetUserPermissions(idCaptionRoles.Select(r => r.Id));
return new UserTokenDto
{
Id = user.Id,
Name = user.Name,
CompanyName = user.Company.Caption,
Level = user.Level,
Login = user.Login,
Patronymic = user.Patronymic,
RoleName = user.Role.Caption,
RoleNames = idCaptionRoles.Select(r => r.Caption),
Permissions = userPermissions,
Surname = user.Surname,
Token = MakeToken(identity.Claims),
};
@ -94,7 +107,6 @@ namespace AsbCloudInfrastructure.Services
var newUser = new User
{
IdCompany = userDto.IdCompany,
IdRole = userDto.IdRole ?? 2, // simple user
State = 0,
Name = userDto.Name,
Surname = userDto.Surname,
@ -102,15 +114,21 @@ namespace AsbCloudInfrastructure.Services
Email = userDto.Email,
Phone = userDto.Phone,
Position = userDto.Position,
Level = userDto.Level,
Login = userDto.Login,
PasswordHash = salt + ComputeHash(salt, userDto.Password),
};
db.Users.Add(newUser);
try
{
db.SaveChanges();
db.RelationUserUserRoles.Add(new RelationUserUserRole()
{
IdUser = newUser.Id,
IdUserRole = 2
});
db.SaveChanges();
}
catch //(Exception ex)
{
@ -159,6 +177,24 @@ namespace AsbCloudInfrastructure.Services
return new JwtSecurityTokenHandler().WriteToken(jwt);
}
private IEnumerable<(int Id, string Caption)> GetUserRolesIdsNames(int idUser)
{
var userRolesIds = cacheUsersUserRoles.Where(r =>
r.IdUser == idUser).Select(r => r.IdUserRole);
return cacheUserRoles.Where(r => userRolesIds.Contains(r.Id))
.Select(r => (r.Id, r.Caption));
}
private IDictionary<string, int> GetUserPermissions(IEnumerable<int> idRoles)
{
var userPermissionIds = cacheUserRolesPermissions.Where(p =>
idRoles.Contains(p.IdUserRole)).Select(r => r.IdPermission);
return cachePermissions.Where(r => userPermissionIds.Contains(r.Id))
.ToDictionary(k => k.Caption, v => v.Type);
}
private async Task<(ClaimsIdentity Identity, User User)> GetClaimsUserAsync(string login,
string password, CancellationToken token = default)
{
@ -174,13 +210,18 @@ namespace AsbCloudInfrastructure.Services
if (!CheckPassword(user.PasswordHash, password))
return default;
var userRolesNames = GetUserRolesIdsNames(user.Id)
.Select(r => r.Caption);
var claims = new List<Claim>
{
new Claim(claimIdUser, user.Id.ToString()),
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role?.Caption??"GUEST"),
new Claim(claimNameidCompany, user.IdCompany.ToString()),
};
claims.AddRange(userRolesNames.Select(roleName => new Claim(ClaimsIdentity.DefaultRoleClaimType, roleName)));
var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
return (claimsIdentity, user);
}