Skip to content

Commit

Permalink
Fixed bugs in services after moving the checking rules of the users r…
Browse files Browse the repository at this point in the history
…ights from controller to services. GetByFilter still doesn't work.
  • Loading branch information
andriitsylia committed Dec 17, 2023
1 parent dd2c30e commit 881081a
Show file tree
Hide file tree
Showing 14 changed files with 144 additions and 135 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -201,21 +201,21 @@ public async Task<ResponseDto> UpdateProviderAdminAsync(
_ = providerAdminUpdateDto ?? throw new ArgumentNullException(nameof(providerAdminUpdateDto));

if (await context.Users.AnyAsync(x => x.Email == providerAdminUpdateDto.Email
&& x.Id != providerAdminUpdateDto.Id).ConfigureAwait(false))
&& x.Id != providerAdminUpdateDto.UserId).ConfigureAwait(false))
{
logger.LogError("Cant update provider admin with duplicate email: {Email}", providerAdminUpdateDto.Email);
return CreateResponseDto(
HttpStatusCode.BadRequest,
$"Cant update provider admin with duplicate email: {providerAdminUpdateDto.Email}");
}

var providerAdmin = this.GetProviderAdmin(providerAdminUpdateDto.Id);
var providerAdmin = this.GetProviderAdmin(providerAdminUpdateDto.UserId);

if (providerAdmin is null)
{
logger.LogError(
"ProviderAdmin(id) {Id} not found. User(id): {UserId}",
providerAdminUpdateDto.Id,
providerAdminUpdateDto.UserId,
userId);
return CreateResponseDto(HttpStatusCode.NotFound);
}
Expand All @@ -226,7 +226,7 @@ public async Task<ResponseDto> UpdateProviderAdminAsync(
return CreateResponseDto(HttpStatusCode.BadRequest);
}

var user = await userManager.FindByIdAsync(providerAdminUpdateDto.Id);
var user = await userManager.FindByIdAsync(providerAdminUpdateDto.UserId);

var executionStrategy = context.Database.CreateExecutionStrategy();
return await executionStrategy.Execute(providerAdminUpdateDto, UpdateProviderAdminOperation).ConfigureAwait(false);
Expand Down Expand Up @@ -328,7 +328,7 @@ await providerAdminChangesLogService.SaveChangesLogAsync(

logger.LogInformation(
"ProviderAdmin(id):{Id} was successfully updated by User(id): {UserId}",
updateDto.Id,
updateDto.UserId,
userId);

return CreateResponseDto(HttpStatusCode.OK, null, updateDto);
Expand Down
2 changes: 2 additions & 0 deletions OutOfSchool/OutOfSchool.Common/Models/AdminBaseDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ namespace OutOfSchool.Common.Models;

public class AdminBaseDto
{
public string UserId { get; set; }

[Required(ErrorMessage = "FirstName is required")]
public string FirstName { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class CreateProviderAdminDto : AdminBaseDto

public Guid ProviderId { get; set; }

public string UserId { get; set; }
//public string UserId { get; set; }

Check warning on line 16 in OutOfSchool/OutOfSchool.Common/Models/CreateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Check warning on line 16 in OutOfSchool/OutOfSchool.Common/Models/CreateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Check warning on line 16 in OutOfSchool/OutOfSchool.Common/Models/CreateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)


// to specify if its assistant or deputy
public bool IsDeputy { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ public class MinistryAdminBaseDto : AdminBaseDto
[Required(ErrorMessage = "InstitutionId is required")]
public Guid InstitutionId { get; set; }

public string UserId { get; set; }
//public string UserId { get; set; }

Check warning on line 14 in OutOfSchool/OutOfSchool.Common/Models/MinistryAdminBaseDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Check warning on line 14 in OutOfSchool/OutOfSchool.Common/Models/MinistryAdminBaseDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Check warning on line 14 in OutOfSchool/OutOfSchool.Common/Models/MinistryAdminBaseDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//using System.ComponentModel.DataAnnotations;

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Single-line comments should not be followed by blank line (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1512.md)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Single-line comments should not be followed by blank line (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1512.md)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)

Single-line comments should not be followed by blank line (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1512.md)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)

Check warning on line 3 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)


namespace OutOfSchool.Common.Models;

public class UpdateProviderAdminDto : AdminBaseDto
{
[Required(ErrorMessage = "Id is required")]
public string Id { get; set; }
//[Required(ErrorMessage = "Id is required")]

Check warning on line 9 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Check warning on line 9 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Check warning on line 9 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)

//public string Id { get; set; }

Check warning on line 10 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Check warning on line 10 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Check warning on line 10 in OutOfSchool/OutOfSchool.Common/Models/UpdateProviderAdminDto.cs

View workflow job for this annotation

GitHub Actions / test (macOS-latest)


// to specify workshops, which can be managed by provider admin
public List<Guid> ManagedWorkshopIds { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,34 +181,6 @@ public async Task<ActionResult> Update(Area2AdminDto areaAdminDto)
return BadRequest(ModelState);
}

//if (currentUserId != adminDto.Id)
//{
// if (!(currentUserRole == nameof(Role.TechAdmin).ToLower() ||
// currentUserRole == nameof(Role.MinistryAdmin).ToLower()))
// {
// logger.LogDebug("Forbidden to update another user if you don't have TechAdmin or MinistryAdmin role.");
// return StatusCode(403,
// "Forbidden to update another user if you don't have TechAdmin or MinistryAdmin role.");
// }

// if ((currentUserRole == nameof(Role.MinistryAdmin).ToLower()
// && !await areaAdminService.IsAreaAdminSubordinatedToMinistryAdminAsync(currentUserId, adminDto.Id)) ||
// (currentUserRole == nameof(Role.RegionAdmin).ToLower()
// && !await areaAdminService.IsAreaAdminSubordinatedToRegionAdminAsync(currentUserId, adminDto.Id)))
// {
// logger.LogDebug("Forbidden to update AreaAdmin. AreaAdmin doesn't subordinate to MinistryAdmin.");
// return StatusCode(403,
// "Forbidden to update AreaAdmin. AreaAdmin doesn't subordinate to MinistryAdmin.");
// }

// var updatedRegionAdmin = await areaAdminService.GetByIdAsync(adminDto.Id);
// if (updatedRegionAdmin.AccountStatus == AccountStatus.Accepted)
// {
// logger.LogDebug("Forbidden to update accepted user.");
// return StatusCode(403, "Forbidden to update accepted user.");
// }
//}

try
{
var response = await areaAdminService.UpdateAsync(
Expand Down Expand Up @@ -253,16 +225,6 @@ public async Task<ActionResult> Delete(string areaAdminId)
{
logger.LogInformation("The deleting of the area admin {areaAdminId} by the user {UserId} was started.", areaAdminId, userId);

//if ((currentUserRole == nameof(Role.MinistryAdmin).ToLower()
// && !await areaAdminService.IsAreaAdminSubordinatedToMinistryAdminAsync(userId, areaAdminId)) ||
//(currentUserRole == nameof(Role.RegionAdmin).ToLower()
// && !await areaAdminService.IsAreaAdminSubordinatedToRegionAdminAsync(userId, areaAdminId)))
//{
// logger.LogDebug("Forbidden to update AreaAdmin. AreaAdmin doesn't subordinate to MinistryAdmin.");
// return StatusCode(403,
// "Forbidden to update AreaAdmin. AreaAdmin doesn't subordinate to MinistryAdmin.");
//}

var response = await areaAdminService.DeleteAsync(
areaAdminId,
userId,
Expand Down Expand Up @@ -300,16 +262,6 @@ public async Task<ActionResult> Block(string areaAdminId, bool? isBlocked)
{
logger.LogInformation("The blocking of the area admin {areaAdminId} by the user {UserId} was started.", areaAdminId, userId);

//if ((currentUserRole == nameof(Role.MinistryAdmin).ToLower()
// && !await areaAdminService.IsAreaAdminSubordinatedToMinistryAdminAsync(userId, areaAdminId)) ||
//(currentUserRole == nameof(Role.RegionAdmin).ToLower()
// && !await areaAdminService.IsAreaAdminSubordinatedToRegionAdminAsync(userId, areaAdminId)))
//{
// logger.LogDebug("Forbidden to update AreaAdmin. AreaAdmin doesn't subordinate to MinistryAdmin.");
// return StatusCode(403,
// "Forbidden to update AreaAdmin. AreaAdmin doesn't subordinate to MinistryAdmin.");
//}

if (isBlocked is null)
{
logger.LogDebug("The IsBlocked parameter is not specified");
Expand Down Expand Up @@ -343,7 +295,7 @@ await HttpContext.GetTokenAsync("access_token"),
/// </summary>
/// <param name="areaAdminId">Entity's id.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpPut("{adminId}")]
[HttpPut("{areaAdminId}")]
[HasPermission(Permissions.AreaAdminEdit)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ await HttpContext.GetTokenAsync("access_token"),
/// </summary>
/// <param name="ministryAdminId">Entity's id.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpPut("{adminId}")]
[HttpPut("{ministryAdminId}")]
[HasPermission(Permissions.MinistryAdminEdit)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ public async Task<ActionResult> Delete(string regionAdminId)
/// <summary>
/// Block the RegionAdmin.
/// </summary>
/// <param name="regionAdminId">Entity's id to delete.</param>
/// <param name="regionAdminId">Entity's id to block.</param>
/// <param name="isBlocked">Blocking status.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpPut]
Expand Down Expand Up @@ -295,7 +295,7 @@ await HttpContext.GetTokenAsync("access_token"),
/// </summary>
/// <param name="regionAdminId">Entity's id.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpPut("{adminId}")]
[HttpPut("{regionAdminId}")]
[HasPermission(Permissions.RegionAdminEdit)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
Expand Down
98 changes: 67 additions & 31 deletions OutOfSchool/OutOfSchool.WebApi/Services/Admins/Area2AdminService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ protected override async Task<bool> IsUserHasRightsToGetAdminsByFilter(BaseAdmin

if (((filter as Area2AdminFilter).InstitutionId != regionAdmin.InstitutionId
&& (filter as Area2AdminFilter).InstitutionId != Guid.Empty)
|| !(childrenCATOTTGIds.Contains((filter as Area2AdminFilter).CATOTTGId)
|| (!childrenCATOTTGIds.Contains((filter as Area2AdminFilter).CATOTTGId)
&& (filter as Area2AdminFilter).CATOTTGId > 0))
{
return false;
Expand Down Expand Up @@ -212,7 +212,7 @@ protected override Expression<Func<InstitutionAdminBase, bool>> PredicateBuild(B

foreach (var word in filter.SearchString.Split(' ', ',', StringSplitOptions.RemoveEmptyEntries))
{
tempPredicate = tempPredicate.Or(
tempPredicate = tempPredicate.Or<AreaAdmin>(
x => x.Institution.Title.Contains(word, StringComparison.InvariantCultureIgnoreCase)
|| x.CATOTTG.Name.Contains(word, StringComparison.InvariantCultureIgnoreCase));
}
Expand All @@ -222,23 +222,39 @@ protected override Expression<Func<InstitutionAdminBase, bool>> PredicateBuild(B

if ((filter as Area2AdminFilter).InstitutionId != Guid.Empty)
{
predicate = predicate.And(a => a.Institution.Id == (filter as Area2AdminFilter).InstitutionId);
predicate = predicate.And<AreaAdmin>(a => a.Institution.Id == (filter as Area2AdminFilter).InstitutionId);
}

var childrenCATOTTGIds = codeficatorService.GetAllChildrenIdsByParentIdAsync((filter as Area2AdminFilter).CATOTTGId).Result;

if (childrenCATOTTGIds.Any())
{
predicate = predicate.And(a => childrenCATOTTGIds.Contains(a.CATOTTGId));
}
else if ((filter as Area2AdminFilter).CATOTTGId > 0)
if ((filter as Area2AdminFilter).CATOTTGId > 0)
{
predicate = predicate.And(c => c.CATOTTG.Id == (filter as Area2AdminFilter).CATOTTGId);
var childrenCATOTTGIds = codeficatorService.GetAllChildrenIdsByParentIdAsync((filter as Area2AdminFilter).CATOTTGId).Result;

if (childrenCATOTTGIds.Any())
{
predicate = predicate.And<AreaAdmin>(a => childrenCATOTTGIds.Contains(a.CATOTTGId));
}
else
{
predicate = predicate.And<AreaAdmin>(a => a.CATOTTG.Id == (filter as Area2AdminFilter).CATOTTGId);
}
}

predicate = predicate.And(x => !x.Institution.IsDeleted);
//var childrenCATOTTGIds = codeficatorService.GetAllChildrenIdsByParentIdAsync((filter as Area2AdminFilter).CATOTTGId).Result;

//if (childrenCATOTTGIds.Any())
//{
// predicate = predicate.And(a => childrenCATOTTGIds.Contains(a.CATOTTGId));
//}
//else if ((filter as Area2AdminFilter).CATOTTGId > 0)
//{
// predicate = predicate.And(c => c.CATOTTG.Id == (filter as Area2AdminFilter).CATOTTGId);
//}

predicate = predicate.And<AreaAdmin>(x => !x.Institution.IsDeleted);

return expressionConverter2.Convert(predicate);
var newPredicate = expressionConverter2.Convert(predicate);

return newPredicate;
}

/// <inheritdoc/>
Expand Down Expand Up @@ -270,7 +286,7 @@ protected override async Task<bool> IsUserHasRightsToCreateAdmin(BaseAdminDto ad
{
if (currentUserService.IsMinistryAdmin())
{
var ministryAdmin = await ministryAdminService.GetByIdAsync((adminDto as Area2AdminDto).Id) as Ministry2AdminDto;
var ministryAdmin = await ministryAdminService.GetByIdAsync(currentUserService.UserId) as Ministry2AdminDto;

if (ministryAdmin.InstitutionId != (adminDto as Area2AdminDto).InstitutionId)
{
Expand All @@ -281,7 +297,7 @@ protected override async Task<bool> IsUserHasRightsToCreateAdmin(BaseAdminDto ad
}
else if (currentUserService.IsRegionAdmin())
{
var regionAdmin = await regionAdminService.GetByIdAsync((adminDto as Area2AdminDto).Id) as Region2AdminDto;
var regionAdmin = await regionAdminService.GetByIdAsync(currentUserService.UserId) as Region2AdminDto;

var subSettlementsIds = await codeficatorService.GetAllChildrenIdsByParentIdAsync(regionAdmin.CATOTTGId);

Expand Down Expand Up @@ -343,39 +359,59 @@ protected override async Task<bool> IsUserHasRightsToUpdateAdmin(string adminId)

protected override async Task<bool> IsUserHasRightsToDeleteAdmin(string adminId)
{
if (!(currentUserService.IsMinistryAdmin()
&& await IsAreaAdminSubordinatedToMinistryAdminAsync(currentUserService.UserId, adminId)))
if (currentUserService.IsTechAdmin())
{
logger.LogDebug("Forbidden to delete area admin. Area admin isn't subordinated to ministry admin.");
return true;
}

return false;
if (currentUserService.IsMinistryAdmin())
{
if (!await IsAreaAdminSubordinatedToMinistryAdminAsync(currentUserService.UserId, adminId))
{
logger.LogDebug("Forbidden to delete area admin. Area admin isn't subordinated to ministry admin.");

return false;
}
}
else if (!(currentUserService.IsRegionAdmin()
&& await IsAreaAdminSubordinatedToRegionAdminAsync(currentUserService.UserId, adminId)))

if (currentUserService.IsRegionAdmin())
{
logger.LogDebug("Forbidden to delete area admin. Area admin isn't subordinated to region admin.");
if (!await IsAreaAdminSubordinatedToRegionAdminAsync(currentUserService.UserId, adminId))
{
logger.LogDebug("Forbidden to delete area admin. Area admin isn't subordinated to region admin.");

return false;
return false;
}
}

return true;
}

protected override async Task<bool> IsUserHasRightsToBlockAdmin(string adminId)
{
if (!(currentUserService.IsMinistryAdmin()
&& await IsAreaAdminSubordinatedToMinistryAdminAsync(currentUserService.UserId, adminId)))
if (currentUserService.IsTechAdmin())
{
return true;
}

if (currentUserService.IsMinistryAdmin())
{
logger.LogDebug("Forbidden to block area admin. Area admin isn't subordinated to ministry admin.");
if (!await IsAreaAdminSubordinatedToMinistryAdminAsync(currentUserService.UserId, adminId))
{
logger.LogDebug("Forbidden to block area admin. Area admin isn't subordinated to ministry admin.");

return false;
return false;
}
}
else if (!(currentUserService.IsRegionAdmin()
&& await IsAreaAdminSubordinatedToRegionAdminAsync(currentUserService.UserId, adminId)))

if (currentUserService.IsRegionAdmin())
{
logger.LogDebug("Forbidden to block area admin. Area admin isn't subordinated to region admin.");
if (!await IsAreaAdminSubordinatedToRegionAdminAsync(currentUserService.UserId, adminId))
{
logger.LogDebug("Forbidden to block area admin. Area admin isn't subordinated to region admin.");

return false;
return false;
}
}

return true;
Expand Down
Loading

0 comments on commit 881081a

Please sign in to comment.