Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Romanchuk Lukashov/Fix the same code parts #606

Merged
merged 3 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System.Security.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Moq;
using NUnit.Framework;
using OutOfSchool.Common;
using OutOfSchool.WebApi.Common;

namespace OutOfSchool.WebApi.Tests.Common
{
[TestFixture]
public class GettingUserPropertiesTest
{
private readonly Claim userIdClaim = new Claim(IdentityResourceClaimsTypes.Sub, "38776161-734b-4aec-96eb-4a1f87a2e5f3");
private readonly Claim userRoleClaim = new Claim(IdentityResourceClaimsTypes.Role, "Parent");
private readonly Claim userSubroleClaim = new Claim(IdentityResourceClaimsTypes.Subrole, "None");
private Mock<HttpContext> httpContextMoq;

[SetUp]
public void Setup()
{
httpContextMoq = new Mock<HttpContext>();
httpContextMoq.Setup(x => x.User.FindFirst("sub")).Returns(userIdClaim);
httpContextMoq.Setup(x => x.User.FindFirst("role")).Returns(userRoleClaim);
httpContextMoq.Setup(x => x.User.FindFirst("subrole")).Returns(userSubroleClaim);
}

[Test]
public void GetUserId_ByHttpContext_ReturnsClaim()
{
// Assert
Assert.AreEqual(userIdClaim.Value, GettingUserProperties.GetUserId(httpContextMoq.Object));
}

[Test]
public void GetUserId_ByHttpContext_ThrowsAuthenticationException()
{
// Assert
Assert.Throws<AuthenticationException>(
() => GettingUserProperties.GetUserId((HttpContext)null));
}

[Test]
public void GetUserId_ByClaimsPrincipal_ReturnNull()
{
// Assert
Assert.IsNull(GettingUserProperties.GetUserId((ClaimsPrincipal)null));
}

[Test]
public void GetUserRole_ByHttpContext_ReturnsClaim()
{
// Assert
Assert.AreEqual(userRoleClaim.Value, GettingUserProperties.GetUserRole(httpContextMoq.Object).ToString());
}

[Test]
public void GetUserRole_ByHttpContext_ThrowsAuthenticationException()
{
// Assert
Assert.Throws<AuthenticationException>(
() => GettingUserProperties.GetUserRole((HttpContext)null));
}

[Test]
public void GetUserRole_ByClaimsPrincipal_ReturnNull()
{
// Assert
Assert.IsNull(GettingUserProperties.GetUserRole((ClaimsPrincipal)null));
}

[Test]
public void GetUserSubrole_ByHttpContext_ReturnsClaim()
{
// Assert
Assert.AreEqual(userSubroleClaim.Value, GettingUserProperties.GetUserSubrole(httpContextMoq.Object).ToString());
}

[Test]
public void GetUserSubrole_ByHttpContext_ThrowsAuthenticationException()
{
// Assert
Assert.Throws<AuthenticationException>(
() => GettingUserProperties.GetUserSubrole((HttpContext)null));
}

[Test]
public void GetUserSubrole_ByClaimsPrincipal_ReturnNull()
{
// Assert
Assert.IsNull(GettingUserProperties.GetUserSubrole((ClaimsPrincipal)null));
}
}
}
71 changes: 71 additions & 0 deletions OutOfSchool/OutOfSchool.WebApi/Common/GettingUserProperties.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Security.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using OutOfSchool.Common;
using OutOfSchool.Common.Extensions;
using OutOfSchool.Services.Enums;

namespace OutOfSchool.WebApi.Common
{
public static class GettingUserProperties
{
public static string GetUserId(HttpContext httpContext)
{
var userId = GetUserId(httpContext?.User);

if (userId is null)
{
ThrowAuthenticationException(nameof(IdentityResourceClaimsTypes.Sub));
}

return userId;
}

public static string GetUserId(ClaimsPrincipal user)
{
return user?.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
}

public static Role GetUserRole(HttpContext httpContext)
{
var userRoleName = GetUserRole(httpContext?.User);

if (userRoleName is null)
{
ThrowAuthenticationException(nameof(IdentityResourceClaimsTypes.Role));
}

Role userRole = (Role)Enum.Parse(typeof(Role), userRoleName, true);

return userRole;
}

public static string GetUserRole(ClaimsPrincipal user)
{
return user?.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Role);
}

public static Subrole GetUserSubrole(HttpContext httpContext)
{
var userSubroleName = GetUserSubrole(httpContext?.User);

if (userSubroleName is null)
{
ThrowAuthenticationException(nameof(IdentityResourceClaimsTypes.Subrole));
}

Subrole userSubrole = (Subrole)Enum.Parse(typeof(Subrole), userSubroleName, true);

return userSubrole;
}

public static string GetUserSubrole(ClaimsPrincipal user)
{
return user?.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Subrole);
}

private static void ThrowAuthenticationException(string claimType)
=> throw new AuthenticationException($"Can not get user's claim {claimType} from Context.");
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
using System;
using System.Security.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OutOfSchool.Common;
using OutOfSchool.Common.Extensions;
using OutOfSchool.Common.PermissionsModule;
using OutOfSchool.WebApi.Common;
using OutOfSchool.WebApi.Models.BlockedProviderParent;
using OutOfSchool.WebApi.Services;

Expand Down Expand Up @@ -46,7 +44,7 @@ public BlockedProviderParentController(
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Block(BlockedProviderParentBlockDto blockedProviderParentBlockDto)
{
var userId = GetUserId();
var userId = GettingUserProperties.GetUserId(HttpContext);
var result = await blockedProviderParentService.Block(blockedProviderParentBlockDto, userId).ConfigureAwait(false);

if (!result.Succeeded)
Expand Down Expand Up @@ -79,7 +77,7 @@ public async Task<IActionResult> Block(BlockedProviderParentBlockDto blockedProv
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UnBlock(BlockedProviderParentUnblockDto blockedProviderParentUnblockDto)
{
var userId = GetUserId();
var userId = GettingUserProperties.GetUserId(HttpContext);
var result = await blockedProviderParentService.Unblock(blockedProviderParentUnblockDto, userId).ConfigureAwait(false);

if (!result.Succeeded)
Expand Down Expand Up @@ -112,13 +110,5 @@ public async Task<IActionResult> GetBlock(Guid parentId, Guid providerId)
{
return Ok(await blockedProviderParentService.GetBlock(parentId, providerId).ConfigureAwait(false));
}

private string GetUserId()
{
var userId = HttpContext.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Sub)} from HttpContext.");

return userId;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using OutOfSchool.Common;
using OutOfSchool.Common.Extensions;
using OutOfSchool.Services.Enums;
using OutOfSchool.WebApi.Common;
using OutOfSchool.WebApi.Models;
using OutOfSchool.WebApi.Models.ChatWorkshop;
using OutOfSchool.WebApi.Services;
Expand Down Expand Up @@ -155,7 +156,7 @@ public Task<IActionResult> GetProvidersRoomsAsync()

private async Task<bool> IsParentAChatRoomParticipantAsync(ChatRoomWorkshopDto chatRoom)
{
var userId = this.GetUserId();
var userId = GettingUserProperties.GetUserId(HttpContext);

var result = await validationService.UserIsParentOwnerAsync(userId, chatRoom.ParentId).ConfigureAwait(false);

Expand All @@ -169,8 +170,8 @@ private async Task<bool> IsParentAChatRoomParticipantAsync(ChatRoomWorkshopDto c

private async Task<bool> IsProviderAChatRoomParticipantAsync(ChatRoomWorkshopDto chatRoom)
{
var userId = this.GetUserId();
var userSubrole = this.GetUserSubrole();
var userId = GettingUserProperties.GetUserId(HttpContext);
var userSubrole = GettingUserProperties.GetUserSubrole(HttpContext);

var result = await validationService.UserIsWorkshopOwnerAsync(userId, chatRoom.WorkshopId, userSubrole).ConfigureAwait(false);

Expand All @@ -182,34 +183,6 @@ private async Task<bool> IsProviderAChatRoomParticipantAsync(ChatRoomWorkshopDto
return result;
}

private string GetUserId()
{
var userId = HttpContext.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Sub)} from HttpContext.");

return userId;
}

private Role GetUserRole()
{
var userRoleName = HttpContext.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Role)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Role)} from HttpContext.");

Role userRole = (Role)Enum.Parse(typeof(Role), userRoleName, true);

return userRole;
}

private Subrole GetUserSubrole()
{
var userSubroleName = HttpContext.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Subrole)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Subrole)} from HttpContext.");

Subrole userSubrole = (Subrole)Enum.Parse(typeof(Subrole), userSubroleName, true);

return userSubrole;
}

private void LogWarningAboutUsersTryingToGetNotOwnChatRoom(Guid chatRoomId, string userId)
{
var messageToLog = $"User with {nameof(userId)}:{userId} is trying to get not his own chat room: {nameof(chatRoomId)}={chatRoomId}.";
Expand All @@ -230,7 +203,7 @@ private async Task<IActionResult> GetRoomByIdAsync(Guid chatRoomId, Func<ChatRoo

if (chatRoom is null)
{
this.LogInfoAboutUsersTryingToGetNotExistingChatRoom(chatRoomId, this.GetUserId());
this.LogInfoAboutUsersTryingToGetNotExistingChatRoom(chatRoomId, GettingUserProperties.GetUserId(HttpContext));

return NoContent();
}
Expand Down Expand Up @@ -266,7 +239,7 @@ private async Task<IActionResult> GetMessagesByRoomIdAsync(Guid chatRoomId, Offs

if (chatRoom is null)
{
var messageToLog = $"User with userId:{this.GetUserId()} is trying to get messages from not existing chat room: {nameof(chatRoomId)}={chatRoomId}.";
var messageToLog = $"User with userId:{GettingUserProperties.GetUserId(HttpContext)} is trying to get messages from not existing chat room: {nameof(chatRoomId)}={chatRoomId}.";
logger.LogInformation(messageToLog);

return NoContent();
Expand All @@ -276,7 +249,7 @@ private async Task<IActionResult> GetMessagesByRoomIdAsync(Guid chatRoomId, Offs

if (isChatRoomValid)
{
var messages = await messageService.GetMessagesForChatRoomAndSetReadDateTimeIfItIsNullAsync(chatRoomId, offsetFilter, this.GetUserRole()).ConfigureAwait(false);
var messages = await messageService.GetMessagesForChatRoomAndSetReadDateTimeIfItIsNullAsync(chatRoomId, offsetFilter, GettingUserProperties.GetUserRole(HttpContext)).ConfigureAwait(false);

if (messages.Any())
{
Expand Down Expand Up @@ -306,9 +279,9 @@ private async Task<IActionResult> GetUsersRoomsAsync(Func<Guid, Task<IEnumerable
{
try
{
var userId = this.GetUserId();
var userRole = this.GetUserRole();
var userSubrole = this.GetUserSubrole();
var userId = GettingUserProperties.GetUserId(HttpContext);
var userRole = GettingUserProperties.GetUserRole(HttpContext);
var userSubrole = GettingUserProperties.GetUserSubrole(HttpContext);

if (userSubrole == Subrole.ProviderAdmin)
{
Expand Down
15 changes: 6 additions & 9 deletions OutOfSchool/OutOfSchool.WebApi/Controllers/V1/ChildController.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OutOfSchool.Common;
using OutOfSchool.Common.Extensions;
using OutOfSchool.Common.PermissionsModule;
using OutOfSchool.WebApi.Common;
using OutOfSchool.WebApi.Models;
using OutOfSchool.WebApi.Services;

Expand Down Expand Up @@ -80,7 +77,7 @@ public async Task<IActionResult> GetByParentIdForAdmin(Guid parentId, [FromQuery
[HttpGet]
public async Task<IActionResult> GetUsersChildren([FromQuery] OffsetFilter offsetFilter)
{
string userId = User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
string userId = GettingUserProperties.GetUserId(User);

return Ok(await service.GetByUserId(userId, offsetFilter).ConfigureAwait(false));
}
Expand All @@ -99,7 +96,7 @@ public async Task<IActionResult> GetUsersChildren([FromQuery] OffsetFilter offse
[HttpGet("{id}")]
public async Task<IActionResult> GetUsersChildById(Guid id)
{
string userId = User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
string userId = GettingUserProperties.GetUserId(User);

return Ok(await service.GetByIdAndUserId(id, userId).ConfigureAwait(false));
}
Expand All @@ -118,7 +115,7 @@ public async Task<IActionResult> GetUsersChildById(Guid id)
[HttpPost]
public async Task<IActionResult> Create(ChildDto childDto)
{
string userId = User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
string userId = GettingUserProperties.GetUserId(User);

var child = await service.CreateChildForUser(childDto, userId).ConfigureAwait(false);

Expand All @@ -142,7 +139,7 @@ public async Task<IActionResult> Create(ChildDto childDto)
[HttpPut]
public async Task<IActionResult> Update(ChildDto dto)
{
string userId = User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
string userId = GettingUserProperties.GetUserId(User);

return Ok(await service.UpdateChildCheckingItsUserIdProperty(dto, userId).ConfigureAwait(false));
}
Expand All @@ -161,7 +158,7 @@ public async Task<IActionResult> Update(ChildDto dto)
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(Guid id)
{
string userId = User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
string userId = GettingUserProperties.GetUserId(User);

await service.DeleteChildCheckingItsUserIdProperty(id, userId).ConfigureAwait(false);

Expand Down
Loading