Skip to content

Commit 89dd5b2

Browse files
committed
New role added and some fixes for roles
1 parent f665072 commit 89dd5b2

File tree

7 files changed

+62
-27
lines changed

7 files changed

+62
-27
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
namespace TableBooking.Api.Extensions;
2+
3+
using Microsoft.AspNetCore.Identity;
4+
using Model.Models;
5+
6+
public static class RolesExtension
7+
{
8+
public static async Task SeedRolesAsync(IServiceProvider serviceProvider)
9+
{
10+
using var scope = serviceProvider.CreateScope();
11+
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<AppRole>>();
12+
13+
if (!await roleManager.RoleExistsAsync("User"))
14+
{
15+
await roleManager.CreateAsync(new AppRole { Name = "User" });
16+
}
17+
18+
if (!await roleManager.RoleExistsAsync("Admin"))
19+
{
20+
await roleManager.CreateAsync(new AppRole { Name = "Admin" });
21+
}
22+
23+
if (!await roleManager.RoleExistsAsync("Restaurant"))
24+
{
25+
await roleManager.CreateAsync(new AppRole { Name = "Restaurant" });
26+
}
27+
}
28+
}

TableBooking.Api/Interfaces/IUserService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace TableBooking.Api.Interfaces;
22

3+
using Microsoft.AspNetCore.Identity;
34
using Microsoft.AspNetCore.Mvc;
45
using Model.Dtos.UserDtos;
56

@@ -9,5 +10,4 @@ public interface IUserService
910
public Task<IActionResult> Login(UserLoginDto userLoginDto);
1011
public Task<IActionResult> Logout(string? authHeader);
1112
public Task<AppUserDto> GetUserInfo(Guid id, CancellationToken cancellationToken);
12-
public Task SeedRoles();
1313
}

TableBooking.Api/Program.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using Serilog;
1111
using TableBooking.Api.Configuration.DbSetup;
1212
using TableBooking.Api.Configuration.HealthCheck;
13+
using TableBooking.Api.Extensions;
1314
using TableBooking.Api.Interfaces;
1415
using TableBooking.Api.Middleware;
1516
using TableBooking.Api.Services;
@@ -163,6 +164,12 @@
163164

164165
var app = builder.Build();
165166

167+
using (var scope = app.Services.CreateScope())
168+
{
169+
var serviceProvider = scope.ServiceProvider;
170+
await RolesExtension.SeedRolesAsync(serviceProvider);
171+
}
172+
166173
app.UseMiddleware<TokenRevocationMiddleware>();
167174

168175
if (app.Environment.IsDevelopment())

TableBooking.Api/Services/UserService.cs

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.IdentityModel.Tokens.Jwt;
44
using System.Security.Claims;
55
using System.Text;
6+
using Extensions;
67
using Interfaces;
78
using Microsoft.AspNetCore.Identity;
89
using Microsoft.AspNetCore.Mvc;
@@ -18,7 +19,6 @@ public class UserService : IUserService
1819
private readonly UserManager<AppUser> _userManager;
1920
private readonly RoleManager<AppRole> _roleManager;
2021
private readonly IConfiguration _configuration;
21-
private const string UserRoleId = "5ad1268f-f61f-4b1c-b690-cbf8c3d35019";
2222
private readonly TableBookingContext _dbContext;
2323

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

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

4949
var user = new AppUser
5050
{
5151
Email = dto.Email,
5252
SecurityStamp = Guid.NewGuid().ToString(),
5353
UserName = dto.Username,
54-
AppRoleId = appUserRole.Id
54+
AppRoleId = appUserRole.Id,
55+
AppRole = appUserRole
5556
};
56-
57+
5758
var result = await _userManager.CreateAsync(user, dto.Password);
5859

5960
if (!result.Succeeded)
60-
return new BadRequestObjectResult("Invalid password lenght Or Bad Email");
61+
return new BadRequestObjectResult("Invalid password length or Bad Email");
6162

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

6566
public async Task<IActionResult> Login(UserLoginDto dto)
6667
{
67-
var user = await _userManager.FindByNameAsync(dto.Username) ;
68-
if (user == null || !await _userManager.CheckPasswordAsync(user, dto.Password))
69-
{
70-
return new UnauthorizedResult();
71-
}
68+
var user = await _userManager.FindByNameAsync(dto.Username);
69+
if (user == null)
70+
return new BadRequestObjectResult($"User with username '{dto.Username}' does not exist.");
71+
72+
if (!await _userManager.CheckPasswordAsync(user, dto.Password))
73+
return new BadRequestObjectResult($"Wrong password.");
7274

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

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

9496
var token = GetToken(authClaims);
95-
97+
9698
return new OkObjectResult(new
9799
{
98100
token = new JwtSecurityTokenHandler().WriteToken(token),
@@ -144,9 +146,4 @@ private JwtSecurityToken GetToken(List<Claim> authClaims)
144146

145147
return token;
146148
}
147-
148-
public Task SeedRoles()
149-
{
150-
throw new NotImplementedException();
151-
}
152149
}

TableBooking.Model/Models/AppRole.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,4 @@
22

33
using Microsoft.AspNetCore.Identity;
44

5-
public class AppRole : IdentityRole<Guid>
6-
{
7-
}
5+
public class AppRole : IdentityRole<Guid>;

TableBooking.Model/Models/AppUser.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace TableBooking.Model.Models;
22

3+
using System.ComponentModel.DataAnnotations.Schema;
34
using Dtos.UserDtos;
45
using Microsoft.AspNetCore.Identity;
56

@@ -10,7 +11,6 @@ public class AppUser : IdentityUser<Guid>
1011
public IEnumerable<Booking> Bookings { get; set; } = new List<Booking>();
1112
public Guid AppRoleId { get; set; }
1213
public AppRole AppRole { get; set; } = new();
13-
1414
public AppUserDto ToDto()
1515
{
1616
return new AppUserDto

TableBooking.Model/Seed/migration-deploy.sql

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33

44
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
55
"MigrationId" character varying(150) NOT NULL,
6-
"ProductVersion" character varying(32) NOT NULL,
7-
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
8-
);
6+
"ProductVersion" character varying(32) NOT NULL,
7+
CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
8+
);
99

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

146+
ALTER TABLE "Bookings" ADD "RestaurantId" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
147+
148+
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
149+
VALUES ('20250119150709_BookingChanges', '9.0.0');
150+
146151
COMMIT;

0 commit comments

Comments
 (0)