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

#144 Logging and localization for exceptions were added. #524

Merged
merged 1 commit into from
Jan 26, 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
Expand Up @@ -6,6 +6,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
Expand Down Expand Up @@ -36,6 +37,7 @@ public class ChatWorkshopHubTests
private Mock<IClientProxy> clientProxyMock;
private Mock<HubCallerContext> hubCallerContextMock;
private Mock<IGroupManager> groupsMock;
private Mock<IStringLocalizer<SharedResource>> localizerMock;

[SetUp]
public void SetUp()
Expand All @@ -51,14 +53,16 @@ public void SetUp()
clientProxyMock = new Mock<IClientProxy>();
hubCallerContextMock = new Mock<HubCallerContext>();
groupsMock = new Mock<IGroupManager>();
localizerMock = new Mock<IStringLocalizer<SharedResource>>();

chatHub = new ChatWorkshopHub(
loggerMock.Object,
messageServiceMock.Object,
roomServiceMock.Object,
validationServiceMock.Object,
workshopRepositoryMock.Object,
parentRepositoryMock.Object)
parentRepositoryMock.Object,
localizerMock.Object)
{
Clients = clientsMock.Object,
Context = hubCallerContextMock.Object,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,13 +232,13 @@ private async Task<IActionResult> GetRoomByIdAsync(Guid chatRoomId, Func<ChatRoo
catch (AuthenticationException exception)
{
logger.LogWarning(exception.Message);
var messageForUser = "Cannot get some user's claims. Please check your authentication or contact technical support.";
var messageForUser = localizer["Can not get some user's claims. Please check your authentication or contact technical support."];
return BadRequest(messageForUser);
}
catch (Exception exception)
{
logger.LogError(exception.Message);
var messageForUser = "Server error. Please try again later or contact technical support.";
var messageForUser = localizer["Server error. Please try again later or contact technical support."];
return new ObjectResult(messageForUser) { StatusCode = 500 };
}
}
Expand Down Expand Up @@ -276,13 +276,13 @@ private async Task<IActionResult> GetMessagesByRoomIdAsync(Guid chatRoomId, Offs
catch (AuthenticationException exception)
{
logger.LogWarning(exception.Message);
var messageForUser = "Cannot get some user's claims. Please check your authentication or contact technical support.";
var messageForUser = localizer["Can not get some user's claims. Please check your authentication or contact technical support."];
return BadRequest(messageForUser);
}
catch (Exception exception)
{
logger.LogError(exception.Message);
var messageForUser = "Server error. Please try again later or contact technical support.";
var messageForUser = localizer["Server error. Please try again later or contact technical support."];
return new ObjectResult(messageForUser) { StatusCode = 500 };
}
}
Expand All @@ -308,13 +308,13 @@ private async Task<IActionResult> GetUsersRoomsAsync(Func<Guid, Task<IEnumerable
catch (AuthenticationException exception)
{
logger.LogWarning(exception.Message);
var messageForUser = "Cannot get some user's claims. Please check your authentication or contact technical support.";
var messageForUser = localizer["Can not get some user's claims. Please check your authentication or contact technical support."];
return BadRequest(messageForUser);
}
catch (Exception exception)
{
logger.LogError(exception.Message);
var messageForUser = "Server error. Please try again later or contact technical support.";
var messageForUser = localizer["Server error. Please try again later or contact technical support."];
return new ObjectResult(messageForUser) { StatusCode = 500 };
}
}
Expand Down
47 changes: 31 additions & 16 deletions OutOfSchool/OutOfSchool.WebApi/Hubs/ChatWorkshopHub.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Authentication;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OutOfSchool.Common;
Expand All @@ -21,7 +23,6 @@ namespace OutOfSchool.WebApi.Hubs
[Authorize(Roles = "provider,parent")]
public class ChatWorkshopHub : Hub
{
// TODO: add/change proper logging of all exceptions
// TODO: split method SendMessageToOthersInGroupAsync into two separate for parent and provider

// This collection tracks users with their connections.
Expand All @@ -34,39 +35,43 @@ private static readonly ConcurrentDictionary<string, HashSet<string>> UsersConne
private readonly IValidationService validationService;
private readonly IWorkshopRepository workshopRepository;
private readonly IParentRepository parentRepository;
private readonly IStringLocalizer<SharedResource> localizer;

/// <summary>
/// Initializes a new instance of the <see cref="ChatWorkshopHub"/> class.
/// </summary>
/// <param name="logger">Logger.</param>
/// <param name="chatMessageService">Service for ChatMessage entities.</param>
/// <param name="chatRoomService">Service for ChatRoom entities.</param>
/// <param name="validationService">Service for validation parameters.</param>
/// <param name="workshopRepository">Repository for workshop entities.</param>
/// <param name="parentRepository">Repository for parent entities.</param>
/// <param name="logger">Logger.</param>
/// <param name="localizer">Localizer.</param>
public ChatWorkshopHub(
ILogger<ChatWorkshopHub> logger,
IChatMessageWorkshopService chatMessageService,
IChatRoomWorkshopService chatRoomService,
IValidationService validationService,
IWorkshopRepository workshopRepository,
IParentRepository parentRepository)
IParentRepository parentRepository,
IStringLocalizer<SharedResource> localizer)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.messageService = chatMessageService ?? throw new ArgumentNullException(nameof(chatMessageService));
this.roomService = chatRoomService ?? throw new ArgumentNullException(nameof(chatRoomService));
this.validationService = validationService ?? throw new ArgumentNullException(nameof(validationService));
this.workshopRepository = workshopRepository ?? throw new ArgumentNullException(nameof(workshopRepository));
this.parentRepository = parentRepository ?? throw new ArgumentNullException(nameof(parentRepository));
this.localizer = localizer;
}

public override async Task OnConnectedAsync()
{
var userId = Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Sub)} from HttpContext.");
var userId = Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
LogErrorThrowExceptionIfPropertyIsNull(userId, nameof(userId));

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

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

Expand All @@ -92,8 +97,8 @@ public override async Task OnConnectedAsync()

public override async Task OnDisconnectedAsync(Exception exception)
{
var userId = Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Sub)} from HttpContext.");
var userId = Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
LogErrorThrowExceptionIfPropertyIsNull(userId, nameof(userId));

logger.LogDebug($"UserId: {userId} connection:{Context.ConnectionId} disconnected.");

Expand Down Expand Up @@ -121,7 +126,7 @@ public async Task SendMessageToOthersInGroupAsync(string chatNewMessage)
var messageToLog = $"{Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Role)} with UserId:{Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub)} is trying to send message with one of not his own parameters: {nameof(chatMessageWorkshopCreateDto.WorkshopId)} {chatMessageWorkshopCreateDto.WorkshopId}, {nameof(chatMessageWorkshopCreateDto.ParentId)} {chatMessageWorkshopCreateDto.ParentId}";
logger.LogWarning(messageToLog);

var messageForUser = "Some of the message parameters were wrong. Please check your message and try again.";
var messageForUser = localizer["Some of the message parameters were wrong. Please check your message and try again."];
await Clients.Caller.SendAsync("ReceiveMessageInChatGroup", messageForUser).ConfigureAwait(false);
return;
}
Expand All @@ -147,13 +152,13 @@ await Clients.OthersInGroup(createdMessageDto.ChatRoomId.ToString())
catch (AuthenticationException exception)
{
logger.LogWarning(exception.Message);
var messageForUser = "Can not get some user's claims. Please check your authentication or contact technical support.";
var messageForUser = localizer["Can not get some user's claims. Please check your authentication or contact technical support."];
await Clients.Caller.SendAsync("ReceiveMessageInChatGroup", messageForUser).ConfigureAwait(false);
}
catch (Exception exception)
{
logger.LogError(exception.Message);
var messageForUser = "Server error. Please try again later or contact technical support.";
var messageForUser = localizer["Server error. Please try again later or contact technical support."];
await Clients.Caller.SendAsync("ReceiveMessageInChatGroup", messageForUser).ConfigureAwait(false);
}
}
Expand Down Expand Up @@ -200,11 +205,11 @@ private async Task AddConnectionsToGroupAsync(string userId, string chatRoomUniq

private Task<bool> UserHasRigtsForChatRoomAsync(Guid workshopId, Guid parentId)
{
var userId = Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub)
?? throw new AuthenticationException($"Can not get user's claim {nameof(IdentityResourceClaimsTypes.Sub)} from HttpContext.");
var userId = Context.User.GetUserPropertyByClaimType(IdentityResourceClaimsTypes.Sub);
LogErrorThrowExceptionIfPropertyIsNull(userId, nameof(userId));

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

bool userRoleIsProvider = userRole.Equals(Role.Provider.ToString(), StringComparison.OrdinalIgnoreCase);

Expand All @@ -215,5 +220,15 @@ private Task<bool> UserHasRigtsForChatRoomAsync(Guid workshopId, Guid parentId)

return validationService.UserIsParentOwnerAsync(userId, parentId);
}

private void LogErrorThrowExceptionIfPropertyIsNull(string claim, string nameofClaim)
{
if (claim is null)
{
var errorText = "Can not get user's claim {0} from HttpContext.";
logger.LogError(string.Format(CultureInfo.InvariantCulture, errorText, nameofClaim));
throw new AuthenticationException(localizer[errorText, nameofClaim]);
}
}
}
}
16 changes: 16 additions & 0 deletions OutOfSchool/OutOfSchool.WebApi/Resources/SharedResource.en.resx
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@
<value>Address is null.</value>
<comment>AdressController</comment>
</data>
<data name="Can not get some user's claims. Please check your authentication or contact technical support." xml:space="preserve">
<value>Can not get some user's claims. Please check your authentication or contact technical support.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="Can not get user's claim {0} from HttpContext." xml:space="preserve">
<value>Can not get user's claim {0} from HttpContext.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="Error! Please check the number is correct" xml:space="preserve">
<value>Error! Please check the number is correct</value>
<comment>PhoneNumberValidation</comment>
Expand All @@ -129,6 +137,14 @@
<value>Id cannot be 0 or less than 0.</value>
<comment>AdressController</comment>
</data>
<data name="Server error. Please try again later or contact technical support." xml:space="preserve">
<value>Server error. Please try again later or contact technical support.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="Some of the message parameters were wrong. Please check your message and try again." xml:space="preserve">
<value>Some of the message parameters were wrong. Please check your message and try again.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="The id cannot be greater than number of table entities." xml:space="preserve">
<value>The id cannot be greater than number of table entities.</value>
<comment>AdressService, ChildService, ProviderService</comment>
Expand Down
16 changes: 16 additions & 0 deletions OutOfSchool/OutOfSchool.WebApi/Resources/SharedResource.uk.resx
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,28 @@
<data name="Address is null." xml:space="preserve">
<value>Адреса null (пуста).</value>
</data>
<data name="Can not get some user's claims. Please check your authentication or contact technical support." xml:space="preserve">
<value>Не вдається отримати деякі user's claims. Будь ласка, перевірте свою аутентифікацію або зверніться до технічної підтримки.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="Can not get user's claim {0} from HttpContext." xml:space="preserve">
<value>Не вдається отримати user's claim {0} з HttpContext.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="Error! Please check the number is correct" xml:space="preserve">
<value>Помилка!Перевірте будь ласка правильність номеру</value>
</data>
<data name="Id cannot be 0 or less than 0." xml:space="preserve">
<value>Id не може бути 0 або меншим за 0.</value>
</data>
<data name="Server error. Please try again later or contact technical support." xml:space="preserve">
<value>Помилка на сервері. Будь ласка, спробуйте пізніше або зверніться до технічної підтримки.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="Some of the message parameters were wrong. Please check your message and try again." xml:space="preserve">
<value>Деякі параметри повідомлення були неправильними. Перевірте своє повідомлення та спробуйте ще раз.</value>
<comment>ChatWorkshopHub</comment>
</data>
<data name="The id cannot be greater than number of table entities." xml:space="preserve">
<value>Id не може бути більшим ніж кількість записів у таблиці.</value>
</data>
Expand Down