Skip to content
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
28 changes: 28 additions & 0 deletions TableBooking.Api/Extensions/RolesExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace TableBooking.Api.Extensions;

using Microsoft.AspNetCore.Identity;
using Model.Models;

public static class RolesExtension
{
public static async Task SeedRolesAsync(IServiceProvider serviceProvider)
{
using var scope = serviceProvider.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<AppRole>>();

if (!await roleManager.RoleExistsAsync("User"))
{
await roleManager.CreateAsync(new AppRole { Name = "User" });
}

if (!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new AppRole { Name = "Admin" });
}

if (!await roleManager.RoleExistsAsync("Restaurant"))
{
await roleManager.CreateAsync(new AppRole { Name = "Restaurant" });
}
}
}
2 changes: 1 addition & 1 deletion TableBooking.Api/Interfaces/IUserService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace TableBooking.Api.Interfaces;

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Model.Dtos.UserDtos;

Expand All @@ -9,5 +10,4 @@ public interface IUserService
public Task<IActionResult> Login(UserLoginDto userLoginDto);
public Task<IActionResult> Logout(string? authHeader);
public Task<AppUserDto> GetUserInfo(Guid id, CancellationToken cancellationToken);
public Task SeedRoles();
}
7 changes: 7 additions & 0 deletions TableBooking.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Serilog;
using TableBooking.Api.Configuration.DbSetup;
using TableBooking.Api.Configuration.HealthCheck;
using TableBooking.Api.Extensions;
using TableBooking.Api.Interfaces;
using TableBooking.Api.Middleware;
using TableBooking.Api.Services;
Expand Down Expand Up @@ -163,6 +164,12 @@

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
await RolesExtension.SeedRolesAsync(serviceProvider);
}

app.UseMiddleware<TokenRevocationMiddleware>();

if (app.Environment.IsDevelopment())
Expand Down
35 changes: 16 additions & 19 deletions TableBooking.Api/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Extensions;
using Interfaces;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -18,7 +19,6 @@ public class UserService : IUserService
private readonly UserManager<AppUser> _userManager;
private readonly RoleManager<AppRole> _roleManager;
private readonly IConfiguration _configuration;
private const string UserRoleId = "5ad1268f-f61f-4b1c-b690-cbf8c3d35019";
private readonly TableBookingContext _dbContext;

public UserService(UserManager<AppUser> userManager,
Expand All @@ -42,36 +42,38 @@ public async Task<IActionResult> Register(UserRegisterDto dto)
if (emailExists != null)
return new BadRequestObjectResult($"User with the same email found: {dto.Email}.");

var appUserRole = await _roleManager.FindByIdAsync(UserRoleId);
var appUserRole = await _roleManager.FindByNameAsync("User");
if (appUserRole == null)
return new BadRequestObjectResult($"Can't find role by UserRoleId: {UserRoleId}");
return new BadRequestObjectResult($"Can't find role by name 'User'.");

var user = new AppUser
{
Email = dto.Email,
SecurityStamp = Guid.NewGuid().ToString(),
UserName = dto.Username,
AppRoleId = appUserRole.Id
AppRoleId = appUserRole.Id,
AppRole = appUserRole
};

var result = await _userManager.CreateAsync(user, dto.Password);

if (!result.Succeeded)
return new BadRequestObjectResult("Invalid password lenght Or Bad Email");
return new BadRequestObjectResult("Invalid password length or Bad Email");

return new OkObjectResult(new ResultDto { Status = "Success", Message = "User created successfully!" });
}

public async Task<IActionResult> Login(UserLoginDto dto)
{
var user = await _userManager.FindByNameAsync(dto.Username) ;
if (user == null || !await _userManager.CheckPasswordAsync(user, dto.Password))
{
return new UnauthorizedResult();
}
var user = await _userManager.FindByNameAsync(dto.Username);
if (user == null)
return new BadRequestObjectResult($"User with username '{dto.Username}' does not exist.");

if (!await _userManager.CheckPasswordAsync(user, dto.Password))
return new BadRequestObjectResult($"Wrong password.");

var role = await _roleManager.FindByIdAsync(user.AppRoleId.ToString());
if (role == null) return new BadRequestObjectResult($"Can't login. Role for this user {user.Id} is null");
var role = await _roleManager.FindByNameAsync("User");
if (role == null) return new BadRequestObjectResult($"Can't login. Role named 'User' is not found.");

if (string.IsNullOrEmpty(user.UserName))
{
Expand All @@ -92,7 +94,7 @@ public async Task<IActionResult> Login(UserLoginDto dto)
};

var token = GetToken(authClaims);

return new OkObjectResult(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
Expand Down Expand Up @@ -144,9 +146,4 @@ private JwtSecurityToken GetToken(List<Claim> authClaims)

return token;
}

public Task SeedRoles()
{
throw new NotImplementedException();
}
}
4 changes: 1 addition & 3 deletions TableBooking.Model/Models/AppRole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@

using Microsoft.AspNetCore.Identity;

public class AppRole : IdentityRole<Guid>
{
}
public class AppRole : IdentityRole<Guid>;
2 changes: 1 addition & 1 deletion TableBooking.Model/Models/AppUser.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace TableBooking.Model.Models;

using System.ComponentModel.DataAnnotations.Schema;
using Dtos.UserDtos;
using Microsoft.AspNetCore.Identity;

Expand All @@ -10,7 +11,6 @@ public class AppUser : IdentityUser<Guid>
public IEnumerable<Booking> Bookings { get; set; } = new List<Booking>();
public Guid AppRoleId { get; set; }
public AppRole AppRole { get; set; } = new();

public AppUserDto ToDto()
{
return new AppUserDto
Expand Down
11 changes: 8 additions & 3 deletions TableBooking.Model/Seed/migration-deploy.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
"MigrationId" character varying(150) NOT NULL,
"ProductVersion" character varying(32) NOT NULL,
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);
"ProductVersion" character varying(32) NOT NULL,
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

START TRANSACTION;
CREATE TABLE "Restaurants" (
Expand Down Expand Up @@ -143,4 +143,9 @@ ALTER TABLE "RevokedTokens" ALTER COLUMN "Token" TYPE character varying(512);
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20250117211021_RevokedTokensTableMaxLength', '9.0.0');

ALTER TABLE "Bookings" ADD "RestaurantId" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20250119150709_BookingChanges', '9.0.0');

COMMIT;