Skip to content

Commit

Permalink
update localization service and add login exception messages
Browse files Browse the repository at this point in the history
  • Loading branch information
emrecoskun705 committed Sep 21, 2023
1 parent c7c0f3e commit c4112c5
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ namespace Unitagram.Application.Contracts.Localization;
public interface ILocalizationService
{
string GetLocalizedString(string key);
string this[string key] { get; }
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
using FluentValidation;
using Unitagram.Application.Contracts.Localization;

namespace Unitagram.Application.Models.Identity.Authentication;

public class AuthRequestValidator : AbstractValidator<AuthRequest>
{
public AuthRequestValidator()
public AuthRequestValidator(ILocalizationService localization)
{
RuleFor(a => a.UserName)
.NotEmpty().WithMessage("{PropertyName} shouldn't be empty")
.NotEmpty().WithMessage(localization["UsernameShouldntEmpty"])
.NotNull()
.MaximumLength(100).WithMessage("{PropertyName} should maximum of 100 characters");
.MaximumLength(100).WithMessage(localization["UsernameMaxChar"]);

RuleFor(a => a.Password)
.NotEmpty().WithMessage("{PropertyName} shouldn't be empty")
.NotEmpty().WithMessage(localization["PasswordShouldntEmpty"])
.NotNull()
.MaximumLength(50).WithMessage("{PropertyName} should maximum of 50 characters");;
.MaximumLength(50).WithMessage(localization["PasswordMaxChar"]);;
}

}
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
using System.Text.RegularExpressions;
using FluentValidation;
using Unitagram.Application.Contracts.Localization;
using Unitagram.Application.Models.Identity.Authentication;

namespace Unitagram.Application.Models.Identity.Register;

public class RegisterRequestValidator : AbstractValidator<RegisterRequest>
{
public RegisterRequestValidator()
public RegisterRequestValidator(ILocalizationService localization)
{
RuleFor(a => a.Email)
.EmailAddress().WithMessage("{PropertyName} should be in a proper email address format")
.EmailAddress().WithMessage(localization["EmailInvalidFormat"])
.NotEmpty().WithMessage("{PropertyName} can't be blank")
.NotNull();

Expand Down
20 changes: 13 additions & 7 deletions Unitagram.Identity/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ public AuthService(UserManager<ApplicationUser> userManager,
IUniversityRepository universityRepository,
IUniversityUserRepository universityUserRepository,
UnitagramIdentityDbContext databaseContext,
IEmailVerificationService verificationService, ILocalizationService localization)
IEmailVerificationService verificationService,
ILocalizationService localization)
{
_userManager = userManager;
_signInManager = signInManager;
Expand All @@ -53,7 +54,7 @@ public AuthService(UserManager<ApplicationUser> userManager,

public async Task<Result<AuthResponse>> Login(AuthRequest request)
{
var validator = new AuthRequestValidator();
var validator = new AuthRequestValidator(_localization);
var validationResult = await validator.ValidateAsync(request);
if (validationResult.Errors.Any())
{
Expand All @@ -65,7 +66,7 @@ public async Task<Result<AuthResponse>> Login(AuthRequest request)

if (user == null)
{
var notFoundException = new UserNotFoundException();
var notFoundException = new UserNotFoundException(_localization["UserNotFound"]);
return new Result<AuthResponse>(notFoundException);
}

Expand All @@ -74,7 +75,9 @@ public async Task<Result<AuthResponse>> Login(AuthRequest request)
var lockoutEndDate = await _userManager.GetLockoutEndDateAsync(user);
if (lockoutEndDate >= DateTimeOffset.UtcNow)
{
var lockoutException = new AccountLockoutException();
TimeSpan timeDifference = lockoutEndDate.Value - DateTimeOffset.UtcNow;
int minutesDifference = (int)timeDifference.TotalMinutes + 1;
var lockoutException = new AccountLockoutException(string.Format(_localization["AccountLockout"], minutesDifference));
return new Result<AuthResponse>(lockoutException);
}

Expand All @@ -93,11 +96,14 @@ public async Task<Result<AuthResponse>> Login(AuthRequest request)
{
await _userManager.SetLockoutEndDateAsync(user,
DateTimeOffset.UtcNow.Add(_userManager.Options.Lockout.DefaultLockoutTimeSpan));
var lockoutException = new AccountLockoutException();
var lockoutEndDate = await _userManager.GetLockoutEndDateAsync(user);
TimeSpan timeDifference = lockoutEndDate!.Value - DateTimeOffset.UtcNow;
int minutesDifference = (int)timeDifference.TotalMinutes + 1;
var lockoutException = new AccountLockoutException(string.Format(_localization["AccountLockout"], minutesDifference));
return new Result<AuthResponse>(lockoutException);
}

var badRequestException = new InvalidAccountCredentialsException();
var badRequestException = new InvalidAccountCredentialsException(_localization["InvalidAccountCredentials"]);
return new Result<AuthResponse>(badRequestException);
}

Expand All @@ -114,7 +120,7 @@ await _userManager.SetLockoutEndDateAsync(user,

public async Task<Result<RegisterResponse>> Register(RegisterRequest request)
{
var validator = new RegisterRequestValidator();
var validator = new RegisterRequestValidator(_localization);
var validationResult = await validator.ValidateAsync(request);

if (validationResult.Errors.Any())
Expand Down
3 changes: 3 additions & 0 deletions Unitagram.Infrastructure/Localization/LocalizationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public LocalizationService(IStringLocalizerFactory factory)
_localizer = factory.Create("SharedResources", assemblyName.Name!);
}

public string this[string key] => _localizer[key];


public string GetLocalizedString(string key)
{
return _localizer[key];
Expand Down
25 changes: 23 additions & 2 deletions Unitagram.Infrastructure/Resources/SharedResources.en-us.resx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,28 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="PropertyNameRequired" xml:space="preserve">
<value>{PropertyName} is required.</value>
<data name="UsernameShouldntEmpty" xml:space="preserve">
<value>Username shouldn't be empty.</value>
</data>
<data name="UsernameMaxChar" xml:space="preserve">
<value>Username should be maximum of 100 characters.</value>
</data>
<data name="PasswordShouldntEmpty" xml:space="preserve">
<value>Password shouldn't be empty.</value>
</data>
<data name="PasswordMaxChar" xml:space="preserve">
<value>Password should be maximum of 50 characters.</value>
</data>
<data name="UserNotFound" xml:space="preserve">
<value>User not found.</value>
</data>
<data name="AccountLockout" xml:space="preserve">
<value>Please try again in {0} minutes later.</value>
</data>
<data name="InvalidAccountCredentials" xml:space="preserve">
<value>Account login information is invalid.</value>
</data>
<data name="EmailInvalidFormat" xml:space="preserve">
<value>Email should be in a proper email address format</value>
</data>
</root>
25 changes: 23 additions & 2 deletions Unitagram.Infrastructure/Resources/SharedResources.tr-TR.resx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,28 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="PropertyNameRequired" xml:space="preserve">
<value>{PropertyName} gereklidir.</value>
<data name="UsernameShouldntEmpty" xml:space="preserve">
<value>Kullanıcı adı boş olmamalı.</value>
</data>
<data name="UsernameMaxChar" xml:space="preserve">
<value>Kullanıcı adı en fazla 100 karakter olmalıdır.</value>
</data>
<data name="PasswordShouldntEmpty" xml:space="preserve">
<value>Şifre boş olmamalı.</value>
</data>
<data name="PasswordMaxChar" xml:space="preserve">
<value>Şifre en fazla 50 karakter olmalıdır.</value>
</data>
<data name="UserNotFound" xml:space="preserve">
<value>Kullanıcı bulunamadı.</value>
</data>
<data name="AccountLockout" xml:space="preserve">
<value>Lütfen {0} dakika sonra tekrar deneyiniz.</value>
</data>
<data name="InvalidAccountCredentials" xml:space="preserve">
<value>Hesap giriş bilgileri geçersiz.</value>
</data>
<data name="EmailInvalidFormat" xml:space="preserve">
<value>Mail adresi düzgün bir formatta olmalıdır.</value>
</data>
</root>

0 comments on commit c4112c5

Please sign in to comment.