Skip to content

Commit

Permalink
fix(User): fix conflicts.
Browse files Browse the repository at this point in the history
  • Loading branch information
K-Kabiri committed Sep 2, 2024
2 parents dcdae01 + 3dd69f0 commit e43d04f
Show file tree
Hide file tree
Showing 18 changed files with 239 additions and 36 deletions.
30 changes: 30 additions & 0 deletions AnalysisData/AnalysisData/Authorization.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Text;
using AnalysisData.Repository.RoleRepository.Abstraction;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

namespace AnalysisData;

public class Authorization
{
private readonly IRoleRepository _roleRepository;

public Authorization(IRoleRepository roleRepository)
{
_roleRepository = roleRepository;
}

public async Task ConfigureAuthorizationPolicies(IServiceCollection services)
{
var goldRoles = await _roleRepository.GetRolesByPolicyAsync("Gold");
var silverRoles = await _roleRepository.GetRolesByPolicyAsync("Silver");
var bronzeRoles = await _roleRepository.GetRolesByPolicyAsync("Bronze");

services.AddAuthorization(options =>
{
options.AddPolicy("gold", policy => policy.RequireRole(goldRoles.ToArray()));
options.AddPolicy("silver", policy => policy.RequireRole(silverRoles.ToArray()));
options.AddPolicy("bronze", policy => policy.RequireRole(bronzeRoles.ToArray()));
});
}
}
4 changes: 2 additions & 2 deletions AnalysisData/AnalysisData/ConfigService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
using AnalysisData.Services;
using AnalysisData.Services.AdminService;
using AnalysisData.Services.AdminService.Abstraction;
using AnalysisData.Services.PemissionService;
using AnalysisData.Services.PemissionService.Abstraction;
using AnalysisData.Services.PermissionService;
using AnalysisData.Services.PermissionService.Abstraction;
using AnalysisData.Services.RoleService;
using AnalysisData.Services.RoleService.Abstraction;
using AnalysisData.Services.S3FileStorageService;
Expand Down
26 changes: 26 additions & 0 deletions AnalysisData/AnalysisData/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,30 @@ public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
public DbSet<FileEntity> FileUploadedDb { get; set; }
public DbSet<UserFile> UserFiles { get; set; }
public DbSet<Category> Categories { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<Role>().HasData(
new Role { Id = 1, RoleName = "admin", RolePolicy = "gold" },
new Role { Id = 2, RoleName = "Data-Analyst", RolePolicy = "bronze" },
new Role { Id = 3, RoleName = "Data-Manager", RolePolicy = "silver" }
);

modelBuilder.Entity<User>().HasData(
new User
{
Id = Guid.NewGuid(),
Username = "admin",
Password = ("admin"),
PhoneNumber = "09131111111",
FirstName = "admin",
LastName = "admin",
Email = "[email protected]",
RoleId = 1
}
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public async Task<IActionResult> GetUsersAsync([FromQuery] string username)
return Ok(users);
}

[HttpPost("files/{fileId}/access")]
[HttpPost("files/access")]
public async Task<IActionResult> AccessFileToUser([FromBody] AccessFileToUserDto request)
{
await _filePermissionService.AccessFileToUserAsync(request.UserGuidIds.ToList(), request.FileId);
Expand All @@ -42,7 +42,7 @@ public async Task<IActionResult> AccessFileToUser([FromBody] AccessFileToUserDto
});
}

[HttpGet("files/{fileId}/users")]
[HttpGet("files/users")]
public async Task<IActionResult> WhoAccessToThisFile([FromQuery] int fileId)
{
var file = await _userFileRepository.GetByFileIdAsync(fileId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ public async Task<IActionResult> GetNodesAsync([FromQuery] int pageIndex = 0, [F
return Ok(paginatedNodes);
}

[HttpGet("nodes/{headerUniqueId}/attributes")]
public async Task<IActionResult> GetNodeAttributes(int id)
[HttpGet("nodes/{nodeId}/attributes")]
public async Task<IActionResult> GetNodeAttributes(int nodeId)
{
var user = User;
var output = await _nodeAndEdgeInfo.GetNodeInformationAsync(user, id);
var output = await _nodeAndEdgeInfo.GetNodeInformationAsync(user, nodeId);
return Ok(output);
}

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

#nullable disable

#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional

namespace AnalysisData.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
public partial class initials : Migration

Check warning on line 12 in AnalysisData/AnalysisData/Migrations/20240902084123_initials.cs

View workflow job for this annotation

GitHub Actions / test

The type name 'initials' only contains lower-cased ascii characters. Such names may become reserved for the language.
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
Expand Down Expand Up @@ -231,6 +233,21 @@ protected override void Up(MigrationBuilder migrationBuilder)
onDelete: ReferentialAction.Cascade);
});

migrationBuilder.InsertData(
table: "Roles",
columns: new[] { "Id", "RoleName", "RolePolicy" },
values: new object[,]
{
{ 1, "admin", "gold" },
{ 2, "Data-Analyst", "bronze" },
{ 3, "Data-Manager", "silver" }
});

migrationBuilder.InsertData(
table: "Users",
columns: new[] { "Id", "Email", "FirstName", "ImageURL", "LastName", "Password", "PhoneNumber", "RoleId", "Username" },
values: new object[] { new Guid("85906ba5-c7bb-4708-83db-46734d4adf09"), "[email protected]", "admin", null, "admin", "admin", "09131111111", 1, "admin" });

migrationBuilder.CreateIndex(
name: "IX_EntityNodes_NodeFileReferenceId",
table: "EntityNodes",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,26 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.HasKey("Id");
b.ToTable("Roles");
b.HasData(
new
{
Id = 1,
RoleName = "admin",
RolePolicy = "gold"
},
new
{
Id = 2,
RoleName = "Data-Analyst",
RolePolicy = "bronze"
},
new
{
Id = 3,
RoleName = "Data-Manager",
RolePolicy = "silver"
});
});

modelBuilder.Entity("AnalysisData.UserManage.Model.User", b =>
Expand Down Expand Up @@ -282,6 +302,19 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.HasIndex("RoleId");
b.ToTable("Users");
b.HasData(
new
{
Id = new Guid("85906ba5-c7bb-4708-83db-46734d4adf09"),
Email = "[email protected]",
FirstName = "admin",
LastName = "admin",
Password = "admin",
PhoneNumber = "09131111111",
RoleId = 1,
Username = "admin"
});
});

modelBuilder.Entity("AnalysisData.EAV.Model.EntityNode", b =>
Expand Down
27 changes: 24 additions & 3 deletions AnalysisData/AnalysisData/Program.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
using System.Text;
using AnalysisData;
using AnalysisData.Data;
using AnalysisData.MiddleWare;
using AnalysisData.Repository.RoleRepository.Abstraction;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);


builder.Configuration.AddJsonFile("appsettings.json").AddEnvironmentVariables();
var connectionString = builder.Configuration["CONNECTION_STRING"];

builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));
// builder.Services.AddScoped<Authorization>();
builder.Services.AddRepositories();
builder.Services.AddServices();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpContextAccessor();
var connectionString = builder.Configuration["CONNECTION_STRING"];
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));




var app = builder.Build();

// using (var scope = app.Services.CreateScope())
// {
// var services = scope.ServiceProvider;
// var authorization = services.GetRequiredService<Authorization>();
// await authorization.ConfigureAuthorizationPolicies(builder.Services);
// }


if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand Down
9 changes: 9 additions & 0 deletions AnalysisData/AnalysisData/User/Controllers/AdminController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,14 @@ public async Task<IActionResult> DeleteUser(Guid id)

return NotFound(new { message = "User not found." });
}

[Authorize(Roles = "admin")]
[HttpPut("users/{id}")]
public async Task<IActionResult> UpdateUser(Guid id, [FromBody] UpdateAdminDto updateAdminDto)
{
await _adminService.UpdateUserInformationByAdminAsync(id, updateAdminDto);
return Ok(new { massage = "updated successfully" });
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public async Task<IActionResult> GetAllRoles(int page = 0, int limit = 10)
var rolesCount = await _roleManagementService.GetRoleCount();
return Ok(new
{
users = rolesPagination,
roles = rolesPagination,
count = rolesCount,
thisPage = page,
});
Expand Down
11 changes: 6 additions & 5 deletions AnalysisData/AnalysisData/User/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Security.Claims;
using AnalysisData.Exception;
using AnalysisData.Services;
using AnalysisData.Services.PemissionService.Abstraction;
using AnalysisData.Services.PermissionService.Abstraction;
using AnalysisData.Services.UserService.Abstraction;
using AnalysisData.UserDto.PasswordDto;
using AnalysisData.UserDto.UserDto;
Expand Down Expand Up @@ -33,18 +33,18 @@ public async Task<IActionResult> Login([FromBody] UserLoginDto userLoginDto)
}

[HttpGet("permissions")]
public IActionResult GetPermissions()
public async Task<IActionResult> GetPermissions()
{
var userClaims = User;
var permission = _permissionService.GetPermission(userClaims);
var permission = await _permissionService.GetPermission(userClaims);
var firstName = userClaims.FindFirstValue("firstname");
var lastName = userClaims.FindFirstValue("lastname");
var image = userClaims.FindFirstValue("image");

return Ok(new { image, firstName, lastName, permission });
}

[Authorize(Roles = "admin")]
// [Authorize(Policy = "gold")]
// [Authorize(Roles = "admin")]
[HttpPost("reset-passadword")]
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordDto resetPasswordDto)
{
Expand Down Expand Up @@ -73,6 +73,7 @@ public async Task<IActionResult> UploadImage(IFormFile file)
return Ok(new { massage = "Uploaded successfully." });
}

// [Authorize(Policy = "gold")]
[HttpPut("update-user")]
public async Task<IActionResult> UpdateUser([FromBody] UpdateUserDto updateUserDto)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ public interface IRoleRepository
Task<bool> DeleteRoleAsync(string roleId);
Task<List<Role>> GetAllRolesPaginationAsync(int page, int limit);
Task<int> GetRolesCountAsync();
Task<IEnumerable<string>> GetRolesByPolicyAsync(string policy);
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,14 @@ public async Task<int> GetRolesCountAsync()
{
return await _context.Roles.CountAsync();
}



public async Task<IEnumerable<string>> GetRolesByPolicyAsync(string policy)
{
return await _context.Roles
.Where(r => r.RolePolicy.ToLower() == policy.ToLower())
.Select(r => r.RoleName.ToLower())
.ToListAsync();
}
}
Loading

0 comments on commit e43d04f

Please sign in to comment.