Skip to content

Commit

Permalink
small fixes
Browse files Browse the repository at this point in the history
add AuthService interface, adjust some data annotations, add correlation id to serilog logs
  • Loading branch information
lukegor committed Jan 18, 2024
1 parent a43315e commit 8bec597
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 31 deletions.
11 changes: 0 additions & 11 deletions PriceNegotiationApp.Tests/UnitTest1.cs

This file was deleted.

16 changes: 13 additions & 3 deletions PriceNegotiationApp/Controllers/AuthenticationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ namespace PriceNegotiationApp.Controllers
{
public class AuthenticationController : ControllerBase
{
private readonly AuthService _authService;
private readonly IAuthService _authService;

public AuthenticationController(AuthService authService)
public AuthenticationController(IAuthService authService)
{
_authService = authService;
}
Expand Down Expand Up @@ -63,11 +63,21 @@ public async Task<IActionResult> Logout()
public async Task<IActionResult> RegisterUser([FromBody] RegisterUserDTO userForRegistration)
{
var inputErrors = ModelStateHelper.GetErrors(ModelState);
bool isEmailInUse = await _authService.IsEmailInUse(userForRegistration.Email);
bool isUserNameInUse = await _authService.IsUsernameInUse(userForRegistration.UserName);

if (userForRegistration == null || inputErrors.Any())
{
return BadRequest(inputErrors);
}
else if (isEmailInUse)
{
return BadRequest("The email is already in use");
}
else if (isUserNameInUse)
{
return BadRequest("The username is already in use");
}

var result = await _authService.RegisterUserAsync(userForRegistration);

Expand All @@ -78,7 +88,7 @@ public async Task<IActionResult> RegisterUser([FromBody] RegisterUserDTO userFor
return BadRequest(errors);
}

public class LoginModel
public class LoginModel
{
[Required]
public string Username { get; set; }
Expand Down
9 changes: 6 additions & 3 deletions PriceNegotiationApp/Models/DTO/RegisterUserDTO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@ public class RegisterUserDTO
[Required]
public string Name { get; set; }
[Required]
[RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
public string? StreetAddress { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? PostalCode { get; set; }
[DataType(DataType.PostalCode)]
public string? PostalCode { get; set; }
[Required]
[DataType(DataType.Password)]
public string? Password { get; set; }
[Required]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
Expand Down
11 changes: 6 additions & 5 deletions PriceNegotiationApp/PriceNegotiationApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.QuickGrid.EntityFrameworkAdapter" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.QuickGrid.EntityFrameworkAdapter" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand All @@ -34,6 +34,7 @@
<PackageReference Include="NuGet.Common" Version="6.8.0" />
<PackageReference Include="NuGet.Protocol" Version="6.8.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Enrichers.CorrelationId" Version="3.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

Expand Down
14 changes: 7 additions & 7 deletions PriceNegotiationApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ public static void Main(string[] args)
// configure Serilog
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
.CreateLogger();

builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
Expand Down Expand Up @@ -87,7 +86,7 @@ public static void Main(string[] args)
// context.User.IsInRole("Staff") ||
// (context.User.IsInRole("Customer") && context.User.));
opt.AddPolicy(OperationRequirements.UpdateRequirement.Name, policy =>
opt.AddPolicy(OperationRequirements.UpdateRequirement.Name, policy =>
policy.Requirements.Add(OperationRequirements.UpdateRequirement));
opt.AddPolicy(OperationRequirements.DeleteRequirement.Name, policy =>
policy.Requirements.Add(OperationRequirements.DeleteRequirement));
Expand All @@ -96,14 +95,15 @@ public static void Main(string[] args)
// add negotiation policies handler
builder.Services.AddSingleton<IAuthorizationHandler, NegotiationOperationsAuthorizationHandler>();

// add handling JWT
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings"));
builder.Services.AddScoped<JwtManager>();

// add initializer
builder.Services.AddScoped<MainInitializer>();

// add services
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<INegotiationService, NegotiationService>();

Expand All @@ -118,9 +118,9 @@ public static void Main(string[] args)
using (var scope = serviceProvider.CreateScope())
{
var dbInitializer = scope.ServiceProvider.GetRequiredService<MainInitializer>();
dbInitializer.InitializeRolesAsync().Wait(); // Synchronously wait for completion
dbInitializer.InitializeAdminUserAsync().Wait();
dbInitializer.InitializeStaffUserAsync().Wait();
dbInitializer.InitializeRolesAsync().GetAwaiter().GetResult(); // Synchronously wait for completion
dbInitializer.InitializeAdminUserAsync().GetAwaiter().GetResult();
dbInitializer.InitializeStaffUserAsync().GetAwaiter().GetResult();
}

var app = builder.Build();
Expand Down
37 changes: 35 additions & 2 deletions PriceNegotiationApp/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,17 @@

namespace PriceNegotiationApp.Services
{
public class AuthService
public interface IAuthService
{
Task<AuthResponseDTO> AuthenticateAsync(LoginModel model);
Task SignOutAsync();
Task<IdentityResult> RegisterUserAsync(RegisterUserDTO userForRegistration);
Task<bool> IsEmailInUse(string email);
Task<bool> IsUsernameInUse(string username);
}

public class AuthService : IAuthService
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly JwtManager _jwtHandler;
Expand Down Expand Up @@ -65,5 +74,29 @@ public async Task<IdentityResult> RegisterUserAsync(RegisterUserDTO userForRegis

return result;
}
}

public async Task<bool> IsEmailInUse(string email)
{
var user = await _userManager.FindByEmailAsync(email);

if (user == null)
{
return false;
}

return true;
}

public async Task<bool> IsUsernameInUse(string username)
{
var user = await _userManager.FindByNameAsync(username);

if (user == null)
{
return false;
}

return true;
}
}
}
1 change: 1 addition & 0 deletions PriceNegotiationApp/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
},
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"Enrich": [ "FromLogContext", "WithCorrelationId" ],
"MinimumLevel": {
"Default": "Information"
},
Expand Down

0 comments on commit 8bec597

Please sign in to comment.