Changed Auth to use Identity, with easy to set passsword requirenments via appsettings.json

This commit is contained in:
Matěj Kubíček
2026-05-01 18:07:27 +02:00
parent 3581fce0df
commit ea11e6969b
25 changed files with 1107 additions and 561 deletions
@@ -1,28 +1,37 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Data;
using TemplateWeb.Entities;
using TemplateWeb.Models;
namespace TemplateWeb.Areas.Admin.Controllers;
public class UsersController : AdminBaseController
{
private readonly AppDbContext _context;
private readonly UserManager<UserEntity> _userManager;
public UsersController(AppDbContext context)
public UsersController(UserManager<UserEntity> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task<IActionResult> Index()
{
var users = await _context.Users.ToListAsync();
return View(users);
var users = _userManager.Users.ToList();
var viewModels = new List<UserWithRolesViewModel>();
foreach (var user in users)
{
var roles = await _userManager.GetRolesAsync(user);
viewModels.Add(new UserWithRolesViewModel { UserEntity = user, Roles = roles });
}
return View(viewModels);
}
public async Task<IActionResult> Details(int id)
public async Task<IActionResult> Details(string id)
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == id);
var user = await _userManager.FindByIdAsync(id);
if (user == null) return NotFound();
return View(user);
var roles = await _userManager.GetRolesAsync(user);
return View(new UserWithRolesViewModel { UserEntity = user, Roles = roles });
}
}
@@ -1,4 +1,4 @@
@model UserModel
@model UserWithRolesViewModel
@{
ViewData["Title"] = "User Details";
}
@@ -9,22 +9,25 @@
<div class="card">
<div class="card-header bg-primary text-white">
<h3 class="card-title mb-0">User Information: @Model.UserName</h3>
<h3 class="card-title mb-0">User Information: @Model.UserEntity.UserName</h3>
</div>
<div class="card-body">
<dl class="row">
<dt class="col-sm-3">ID</dt>
<dd class="col-sm-9">@Model.Id</dd>
<dd class="col-sm-9">@Model.UserEntity.Id</dd>
<dt class="col-sm-3">Username</dt>
<dd class="col-sm-9">@Model.UserName</dd>
<dd class="col-sm-9">@Model.UserEntity.UserName</dd>
<dt class="col-sm-3">Email</dt>
<dd class="col-sm-9">@Model.Email</dd>
<dd class="col-sm-9">@Model.UserEntity.Email</dd>
<dt class="col-sm-3">Role</dt>
<dt class="col-sm-3">Roles</dt>
<dd class="col-sm-9">
<span class="badge @(Model.Role == UserRole.Admin ? "bg-danger" : "bg-info")">@Model.Role</span>
@foreach (var role in Model.Roles)
{
<span class="badge @(role == "Admin" ? "bg-danger" : "bg-info")">@role</span>
}
</dd>
</dl>
</div>
@@ -1,4 +1,4 @@
@model IEnumerable<UserModel>
@model IEnumerable<UserWithRolesViewModel>
@{
ViewData["Title"] = "User Management";
}
@@ -13,20 +13,25 @@
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Roles</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
@foreach (var vm in Model)
{
<tr>
<td>@user.Id</td>
<td>@user.UserName</td>
<td>@user.Email</td>
<td><span class="badge @(user.Role == UserRole.Admin ? "bg-danger" : "bg-info")">@user.Role</span></td>
<td>@vm.UserEntity.Id</td>
<td>@vm.UserEntity.UserName</td>
<td>@vm.UserEntity.Email</td>
<td>
<a asp-action="Details" asp-route-id="@user.Id" class="btn btn-sm btn-outline-primary">Details</a>
@foreach (var role in vm.Roles)
{
<span class="badge @(role == "Admin" ? "bg-danger" : "bg-info")">@role</span>
}
</td>
<td>
<a asp-action="Details" asp-route-id="@vm.UserEntity.Id" class="btn btn-sm btn-outline-primary">Details</a>
</td>
</tr>
}
@@ -1,4 +1,3 @@
@using TemplateWeb
@using TemplateWeb.Models
@using TemplateWeb.Models.DbModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@@ -1,6 +1,9 @@
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TemplateWeb.Interfaces;
using TemplateWeb.Entities;
using TemplateWeb.Models;
namespace TemplateWeb.Controllers;
@@ -8,23 +11,28 @@ namespace TemplateWeb.Controllers;
public class AuthController : Controller
{
private readonly ILogger<AuthController> _logger;
private readonly IAuthService _authService;
private readonly UserManager<UserEntity> _userManager;
private readonly SignInManager<UserEntity> _signInManager;
public AuthController(ILogger<AuthController> logger, IAuthService authService)
public AuthController(
ILogger<AuthController> logger,
UserManager<UserEntity> userManager,
SignInManager<UserEntity> signInManager)
{
_logger = logger;
_authService = authService;
_userManager = userManager;
_signInManager = signInManager;
}
#region HttpGet
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string? returnUrl)
{
if (User.Identity?.IsAuthenticated == true)
{
return RedirectToAction("Index", "Home");
}
return View(new AuthLoginViewModel { ReturnUrl = returnUrl });
}
@@ -33,119 +41,159 @@ public class AuthController : Controller
public IActionResult Register(string? returnUrl)
{
if (User.Identity?.IsAuthenticated == true)
{
return RedirectToAction("Index", "Home");
}
return View(new AuthRegisterViewModel { ReturnUrl = returnUrl });
}
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
public IActionResult AccessDenied() => View();
[HttpGet]
[Authorize]
public async Task<IActionResult> Profile()
{
var userResult = await _authService.FindUserByEmailOrUsernameAsync(User.Identity?.Name ?? "");
if (!userResult.Success || userResult.Data == null) return RedirectToAction("Login");
var user = await _userManager.GetUserAsync(User);
if (user == null) return RedirectToAction("Login");
var model = new ProfileViewModel
return View(new ProfileViewModel
{
UserName = userResult.Data.UserName,
Email = userResult.Data.Email
};
return View(model);
UserName = user.UserName!,
Email = user.Email!,
});
}
#endregion
#region httpPost
[HttpPost] [Authorize] [ValidateAntiForgeryToken]
public async Task<IActionResult> Profile(ProfileViewModel model)
#region HttpPost
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(AuthLoginViewModel model)
{
if (!ModelState.IsValid) return View(model);
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId)) return RedirectToAction("Login");
// Support login by email or username
var user = model.EmailOrUsername.Contains('@')
? await _userManager.FindByEmailAsync(model.EmailOrUsername)
: await _userManager.FindByNameAsync(model.EmailOrUsername);
var result = await _authService.UpdateProfileAsync(userId, model);
if (!result.Success)
{
ModelState.AddModelError(string.Empty, result.Message);
return View(model);
}
TempData["SuccessMessage"] = "Profile updated successfully. Please log in again if you changed your username.";
return RedirectToAction("Profile");
}
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken]
public async Task<IActionResult> Login(AuthLoginViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var userResult = await _authService.FindUserByEmailOrUsernameAsync(model.EmailOrUsername);
if (!userResult.Success || userResult.Data == null)
{
ModelState.AddModelError(string.Empty, userResult.Message);
return View(model);
}
var user = userResult.Data;
if (!BCrypt.Net.BCrypt.Verify(model.Password, user.Password))
if (user == null)
{
ModelState.AddModelError(string.Empty, "Invalid credentials.");
return View(model);
}
var authResult = await _authService.AuthenticateAsync(user, model.RememberMe);
if (!authResult.Success)
var result = await _signInManager.PasswordSignInAsync(
user, model.Password, model.RememberMe, lockoutOnFailure: false);
if (!result.Succeeded)
{
ModelState.AddModelError(string.Empty, authResult.Message);
ModelState.AddModelError(string.Empty, "Invalid credentials.");
return View(model);
}
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken]
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(AuthRegisterViewModel model)
{
if (!ModelState.IsValid)
if (!ModelState.IsValid) return View(model);
var user = new UserEntity
{
UserName = model.UserName.Trim(),
Email = model.Email.Trim().ToLower(),
};
var result = await _userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
ModelState.AddModelError(string.Empty, error.Description);
return View(model);
}
var result = await _authService.RegisterAsync(model);
if (!result.Success)
{
ModelState.AddModelError(string.Empty, result.Message);
return View(model);
}
await _userManager.AddToRoleAsync(user, "User");
_logger.LogInformation("User {UserName} registered.", user.UserName);
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Login");
}
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Profile(ProfileViewModel model)
{
if (!ModelState.IsValid) return View(model);
var user = await _userManager.GetUserAsync(User);
if (user == null) return RedirectToAction("Login");
// Update username
if (user.UserName != model.UserName.Trim())
{
var setName = await _userManager.SetUserNameAsync(user, model.UserName.Trim());
if (!setName.Succeeded)
{
foreach (var e in setName.Errors)
ModelState.AddModelError(string.Empty, e.Description);
return View(model);
}
}
// Update email
if (user.Email != model.Email.Trim().ToLower())
{
var setEmail = await _userManager.SetEmailAsync(user, model.Email.Trim().ToLower());
if (!setEmail.Succeeded)
{
foreach (var e in setEmail.Errors)
ModelState.AddModelError(string.Empty, e.Description);
return View(model);
}
}
// Change password (requires current password)
if (!string.IsNullOrWhiteSpace(model.NewPassword))
{
if (string.IsNullOrWhiteSpace(model.CurrentPassword))
{
ModelState.AddModelError(nameof(model.CurrentPassword), "Current password is required to set a new password.");
return View(model);
}
var changePassword = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
if (!changePassword.Succeeded)
{
foreach (var e in changePassword.Errors)
ModelState.AddModelError(string.Empty, e.Description);
return View(model);
}
}
// Refresh cookie so the user stays logged in after security-stamp changes
await _signInManager.RefreshSignInAsync(user);
TempData["SuccessMessage"] = "Profile updated successfully.";
return RedirectToAction("Profile");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _authService.LogoutAsync();
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
@@ -154,19 +202,12 @@ public class AuthController : Controller
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteAccount()
{
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
if (userIdClaim == null) return RedirectToAction("Login");
var user = await _userManager.GetUserAsync(User);
if (user == null) return RedirectToAction("Login");
if (!int.TryParse(userIdClaim.Value, out var userId))
{
return RedirectToAction("Index", "Home");
}
var userResult = await _authService.FindUserByEmailOrUsernameAsync(User.Identity?.Name ?? "");
if (userResult is not { Success: true, Data: not null }) return RedirectToAction("Register");
await _authService.DeleteUserAsync(userResult.Data);
await _authService.LogoutAsync();
await _signInManager.SignOutAsync();
await _userManager.DeleteAsync(user);
_logger.LogInformation("User {UserId} deleted their account.", user.Id);
return RedirectToAction("Register");
}
@@ -175,16 +216,25 @@ public class AuthController : Controller
[Authorize]
public async Task<IActionResult> DownloadData()
{
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId)) return RedirectToAction("Login");
var user = await _userManager.GetUserAsync(User);
if (user == null) return RedirectToAction("Login");
var result = await _authService.GetUserDataAsync(userId);
if (!result.Success || result.Data == null) return BadRequest(result.Message);
var roles = await _userManager.GetRolesAsync(user);
var json = System.Text.Json.JsonSerializer.Serialize(result.Data, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
var data = new
{
user.Id,
user.UserName,
user.Email,
Roles = roles,
ExportDate = DateTime.UtcNow,
};
return File(bytes, "application/json", $"user_data_{User.Identity?.Name}.json");
var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true });
var bytes = Encoding.UTF8.GetBytes(json);
return File(bytes, "application/json", $"user_data_{user.UserName}.json");
}
#endregion
}
+4 -5
View File
@@ -1,14 +1,13 @@
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Models.DbModels;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Entities;
namespace TemplateWeb.Data;
public class AppDbContext : DbContext
public class AppDbContext : IdentityDbContext<UserEntity>
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<UserModel> Users { get; set; }
}
+20 -14
View File
@@ -1,27 +1,33 @@
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Models.DbModels;
using Microsoft.AspNetCore.Identity;
using TemplateWeb.Entities;
namespace TemplateWeb.Data;
public static class DataSeeder
{
public static async Task SeedAdminUser(AppDbContext context)
public static async Task SeedAsync(UserManager<UserEntity> userManager, RoleManager<IdentityRole> roleManager)
{
// Only run if no users exist
if (await context.Users.AnyAsync())
// Ensure roles exist
foreach (var role in new[] { "Admin", "User" })
{
return;
if (!await roleManager.RoleExistsAsync(role))
await roleManager.CreateAsync(new IdentityRole(role));
}
var admin = new UserModel
// Seed initial admin user if none exists
if (!userManager.Users.Any())
{
UserName = "admin",
Email = "admin@template.com",
Password = BCrypt.Net.BCrypt.HashPassword("Admin123!"), // You should change this on first login
Role = UserRole.Admin
};
var admin = new UserEntity
{
UserName = "admin",
Email = "admin@template.com",
EmailConfirmed = true,
};
await context.Users.AddAsync(admin);
await context.SaveChangesAsync();
// You should change this password on first login
var result = await userManager.CreateAsync(admin, "Admin123!");
if (result.Succeeded)
await userManager.AddToRoleAsync(admin, "Admin");
}
}
}
@@ -0,0 +1,7 @@
using Microsoft.AspNetCore.Identity;
namespace TemplateWeb.Entities;
public class UserEntity : IdentityUser
{
}
@@ -1,28 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace TemplateWeb.Models.DbModels;
public class UserModel
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(50)]
[MinLength(3)]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[MinLength(5)]
[DataType(DataType.Password)]
public string Password { get; set; }
public UserRole Role { get; set; } = UserRole.User;
}
public enum UserRole
{
User,
Admin
}
@@ -1,15 +0,0 @@
using TemplateWeb.Models;
using TemplateWeb.Models.DbModels;
namespace TemplateWeb.Interfaces;
public interface IAuthService
{
Task<ServiceResult<UserModel>> FindUserByEmailOrUsernameAsync(string emailOrUsername);
Task<ServiceResult> AuthenticateAsync(UserModel user, bool rememberMe);
Task<ServiceResult<UserModel>> RegisterAsync(AuthRegisterViewModel model);
Task LogoutAsync();
Task<ServiceResult> DeleteUserAsync(UserModel user);
Task<ServiceResult> UpdateProfileAsync(int userId, ProfileViewModel model);
Task<ServiceResult<object>> GetUserDataAsync(int userId);
}
@@ -1,58 +0,0 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TemplateWeb.Data;
#nullable disable
namespace TemplateWeb.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260418160408_InitMigrations")]
partial class InitMigrations
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.0-preview.1.25081.1")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TemplateWeb.Models.DbModels.UserModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Role")
.HasColumnType("integer");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
@@ -1,38 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace TemplateWeb.Migrations
{
/// <inheritdoc />
public partial class InitMigrations : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserName = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Role = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}
@@ -0,0 +1,277 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TemplateWeb.Data;
#nullable disable
namespace TemplateWeb.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260501160159_SwitchToIdentity")]
partial class SwitchToIdentity
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("TemplateWeb.Entities.UserEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,223 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace TemplateWeb.Migrations
{
/// <inheritdoc />
public partial class SwitchToIdentity : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
PasswordHash = table.Column<string>(type: "text", nullable: true),
SecurityStamp = table.Column<string>(type: "text", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
PhoneNumber = table.Column<string>(type: "text", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RoleId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "text", nullable: false),
ProviderKey = table.Column<string>(type: "text", nullable: false),
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
UserId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
LoginProvider = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
@@ -1,4 +1,5 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
@@ -16,12 +17,38 @@ namespace TemplateWeb.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.0-preview.1.25081.1")
.HasAnnotation("ProductVersion", "10.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TemplateWeb.Models.DbModels.UserModel", b =>
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -29,25 +56,217 @@ namespace TemplateWeb.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<int>("Role")
.HasColumnType("integer");
b.Property<string>("UserName")
b.Property<string>("RoleId")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("TemplateWeb.Entities.UserEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("TemplateWeb.Entities.UserEntity", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
@@ -0,0 +1,9 @@
using TemplateWeb.Entities;
namespace TemplateWeb.Models;
public class UserWithRolesViewModel
{
public UserEntity UserEntity { get; set; } = null!;
public IList<string> Roles { get; set; } = [];
}
+24 -15
View File
@@ -1,9 +1,8 @@
using dotenv.net;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Data;
using TemplateWeb.Interfaces;
using TemplateWeb.Services;
using TemplateWeb.Entities;
namespace TemplateWeb;
@@ -23,21 +22,30 @@ public class Program
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
// Configure Identity — password requirements are read from appsettings.json "Identity:Password"
var pwSection = builder.Configuration.GetSection("Identity:Password");
builder.Services.AddIdentity<UserEntity, IdentityRole>(options =>
{
options.LoginPath = "/Auth/Login";
options.AccessDeniedPath = "/Auth/AccessDenied";
options.ExpireTimeSpan = TimeSpan.FromHours(2);
});
builder.Services.AddAuthorization();
options.Password.RequiredLength = pwSection.GetValue<int>("RequiredLength", 6);
options.Password.RequireDigit = pwSection.GetValue<bool>("RequireDigit", true);
options.Password.RequireLowercase = pwSection.GetValue<bool>("RequireLowercase", true);
options.Password.RequireUppercase = pwSection.GetValue<bool>("RequireUppercase", true);
options.Password.RequireNonAlphanumeric = pwSection.GetValue<bool>("RequireNonAlphanumeric", false);
options.Password.RequiredUniqueChars = pwSection.GetValue<int>("RequiredUniqueChars", 1);
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddHttpContextAccessor();
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Auth/Login";
options.AccessDeniedPath = "/Auth/AccessDenied";
options.ExpireTimeSpan = TimeSpan.FromHours(2);
});
var app = builder.Build();
// Apply migrations on startup
// Apply migrations and seed on startup
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
@@ -46,8 +54,9 @@ public class Program
db.Database.Migrate();
}
// Seed the initial admin user
DataSeeder.SeedAdminUser(db).GetAwaiter().GetResult();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<UserEntity>>();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
DataSeeder.SeedAsync(userManager, roleManager).GetAwaiter().GetResult();
}
// Configure the HTTP request pipeline.
@@ -1,183 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Data;
using TemplateWeb.Interfaces;
using TemplateWeb.Models;
using TemplateWeb.Models.DbModels;
namespace TemplateWeb.Services;
public class AuthService : IAuthService
{
private readonly AppDbContext _context;
private readonly ILogger<AuthService> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
public AuthService(
AppDbContext context, ILogger<AuthService> logger, IHttpContextAccessor httpContextAccessor)
{
_context = context;
_logger = logger;
_httpContextAccessor = httpContextAccessor;
}
public async Task<ServiceResult<UserModel>> FindUserByEmailOrUsernameAsync(string emailOrUsername)
{
if (string.IsNullOrWhiteSpace(emailOrUsername))
return ServiceResult<UserModel>.Failure("Email or username is required.");
var trimmed = emailOrUsername.Trim().ToLower();
var user = await _context.Users.SingleOrDefaultAsync(u =>
string.Equals(u.Email, trimmed) ||
string.Equals(u.UserName, trimmed));
return user == null ? ServiceResult<UserModel>.Failure("User not found.") : ServiceResult<UserModel>.Ok(user);
}
public async Task<ServiceResult> AuthenticateAsync(UserModel user, bool rememberMe)
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
new(ClaimTypes.Name, user.UserName),
new(ClaimTypes.Email, user.Email),
new(ClaimTypes.Role, user.Role.ToString()),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext == null)
{
_logger.LogError("HttpContext is null during authentication.");
return ServiceResult.Failure("An internal error occurred.");
}
await httpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties
{
IsPersistent = rememberMe,
ExpiresUtc = rememberMe
? DateTimeOffset.UtcNow.AddDays(30)
: DateTimeOffset.UtcNow.AddHours(8)
});
return ServiceResult.Ok();
}
public async Task<ServiceResult<UserModel>> RegisterAsync(AuthRegisterViewModel viewModel)
{
var userNameTrimmed = viewModel.UserName.Trim();
var emailTrimmed = viewModel.Email.Trim().ToLower();
var existingUser = await _context.Users.AnyAsync(u =>
string.Equals(u.UserName, userNameTrimmed) ||
string.Equals(u.Email, emailTrimmed));
if (existingUser)
{
return ServiceResult<UserModel>.Failure("Username or Email already exists.");
}
var user = new UserModel
{
UserName = userNameTrimmed,
Email = emailTrimmed,
Password = BCrypt.Net.BCrypt.HashPassword(viewModel.Password),
Role = UserRole.User
};
try
{
await _context.Users.AddAsync(user);
await _context.SaveChangesAsync();
_logger.LogInformation("User {UserName} registered.", user.UserName);
return ServiceResult<UserModel>.Ok(user);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error registering user {UserName}", user.UserName);
return ServiceResult<UserModel>.Failure("An error occurred while saving the user.");
}
}
public async Task LogoutAsync()
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext != null)
{
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
_logger.LogInformation("User logged out.");
}
}
public async Task<ServiceResult> DeleteUserAsync(UserModel user)
{
try
{
_context.Users.Remove(user);
await _context.SaveChangesAsync();
_logger.LogInformation("User {UserId} deleted.", user.Id);
return ServiceResult.Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting user {UserId}", user.Id);
return ServiceResult.Failure("An error occurred while deleting the user.");
}
}
public async Task<ServiceResult> UpdateProfileAsync(int userId, ProfileViewModel model)
{
var user = await _context.Users.FindAsync(userId);
if (user == null) return ServiceResult.Failure("User not found.");
var isTaken = await _context.Users.AnyAsync(u => u.Id != userId &&
(u.UserName.ToLower() == model.UserName.Trim().ToLower() ||
u.Email.ToLower() == model.Email.Trim().ToLower()));
if (isTaken) return ServiceResult.Failure("Username or Email already exists.");
user.UserName = model.UserName.Trim();
user.Email = model.Email.Trim().ToLower();
if (!string.IsNullOrWhiteSpace(model.NewPassword))
{
user.Password = BCrypt.Net.BCrypt.HashPassword(model.NewPassword);
}
try
{
await _context.SaveChangesAsync();
return ServiceResult.Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating profile for user {UserId}", userId);
return ServiceResult.Failure("An error occurred while saving changes.");
}
}
public async Task<ServiceResult<object>> GetUserDataAsync(int userId)
{
var user = await _context.Users.FindAsync(userId);
if (user == null) return ServiceResult<object>.Failure("User not found.");
var data = new
{
user.Id,
user.UserName,
user.Email,
Role = user.Role.ToString(),
ExportDate = DateTime.UtcNow
};
return ServiceResult<object>.Ok(data);
}
}
+1 -1
View File
@@ -8,8 +8,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.1.0" />
<PackageReference Include="dotenv.net" Version="4.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -14,9 +14,12 @@ public class ProfileViewModel
[Display(Name = "Email")]
public string Email { get; set; } = string.Empty;
[DataType(DataType.Password)]
[Display(Name = "Current Password")]
public string? CurrentPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "New Password (leave blank to keep current)")]
[MinLength(5)]
public string? NewPassword { get; set; }
[DataType(DataType.Password)]
@@ -32,6 +32,12 @@
<hr />
<p class="text-muted small">Change Password (optional)</p>
<div class="mb-3">
<label asp-for="CurrentPassword" class="form-label"></label>
<input asp-for="CurrentPassword" class="form-control" />
<span asp-validation-for="CurrentPassword" class="text-danger small"></span>
</div>
<div class="mb-3">
<label asp-for="NewPassword" class="form-label"></label>
<input asp-for="NewPassword" class="form-control" />
+10
View File
@@ -8,5 +8,15 @@
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=templatedb;Username=user;Password=password"
},
"Identity": {
"Password": {
"RequiredLength": 6,
"RequireDigit": true,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireNonAlphanumeric": false,
"RequiredUniqueChars": 1
}
}
}
+42 -60
View File
@@ -1,115 +1,97 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using Microsoft.Extensions.DependencyInjection;
using TemplateWeb.Data;
using TemplateWeb.Models;
using TemplateWeb.Models.DbModels;
using TemplateWeb.Services;
using TemplateWeb.Entities;
namespace WebTests;
[TestClass]
public class AuthServiceTests
{
private AppDbContext _context = null!;
private Mock<ILogger<AuthService>> _loggerMock = null!;
private Mock<IHttpContextAccessor> _httpContextAccessorMock = null!;
private AuthService _authService = null!;
private ServiceProvider _serviceProvider = null!;
private UserManager<UserEntity> _userManager = null!;
[TestInitialize]
public void Initialize()
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
_context = new AppDbContext(options);
_loggerMock = new Mock<ILogger<AuthService>>();
_httpContextAccessorMock = new Mock<IHttpContextAccessor>();
_authService = new AuthService(_context, _loggerMock.Object, _httpContextAccessorMock.Object);
var services = new ServiceCollection();
services.AddLogging();
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase(Guid.NewGuid().ToString()));
services.AddIdentity<UserEntity, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
_serviceProvider = services.BuildServiceProvider();
_userManager = _serviceProvider.GetRequiredService<UserManager<UserEntity>>();
}
[TestCleanup]
public void Cleanup()
{
_context.Database.EnsureDeleted();
_context.Dispose();
_serviceProvider.Dispose();
}
[TestMethod]
public async Task RegisterAsync_ShouldReturnSuccess_WhenUserIsNew()
public async Task CreateAsync_ShouldReturnSuccess_WhenUserIsNew()
{
// Arrange
var model = new AuthRegisterViewModel
{
UserName = "testuser",
Email = "test@example.com",
Password = "password123",
ConfirmPassword = "password123"
};
var user = new UserEntity { UserName = "testuser", Email = "test@example.com" };
// Act
var result = await _authService.RegisterAsync(model);
var result = await _userManager.CreateAsync(user, "Password123!");
// Assert
Assert.IsTrue(result.Success);
Assert.IsNotNull(result.Data);
Assert.AreEqual("testuser", result.Data.UserName);
Assert.AreEqual("test@example.com", result.Data.Email);
Assert.IsTrue(result.Succeeded);
var userInDb = await _context.Users.FirstOrDefaultAsync(u => u.UserName == "testuser");
var userInDb = await _userManager.FindByNameAsync("testuser");
Assert.IsNotNull(userInDb);
Assert.AreEqual("test@example.com", userInDb.Email);
}
[TestMethod]
public async Task RegisterAsync_ShouldReturnFailure_WhenUserAlreadyExists()
public async Task CreateAsync_ShouldReturnFailure_WhenUsernameAlreadyExists()
{
// Arrange
var existingUser = new UserModel { UserName = "existing", Email = "existing@example.com", Password = "hashedpassword" };
_context.Users.Add(existingUser);
await _context.SaveChangesAsync();
var existing = new UserEntity { UserName = "existing", Email = "existing@example.com" };
await _userManager.CreateAsync(existing, "Password123!");
var model = new AuthRegisterViewModel
{
UserName = "existing",
Email = "new@example.com",
Password = "password123",
ConfirmPassword = "password123"
};
var duplicate = new UserEntity { UserName = "existing", Email = "other@example.com" };
// Act
var result = await _authService.RegisterAsync(model);
var result = await _userManager.CreateAsync(duplicate, "Password123!");
// Assert
Assert.IsFalse(result.Success);
Assert.AreEqual("Username or Email already exists.", result.Message);
Assert.IsFalse(result.Succeeded);
Assert.IsTrue(result.Errors.Any(e => e.Code == "DuplicateUserName"));
}
[TestMethod]
public async Task FindUserByEmailOrUsernameAsync_ShouldReturnUser_WhenUsernameMatches()
public async Task FindByNameAsync_ShouldReturnUser_CaseInsensitive()
{
// Arrange
var user = new UserModel { UserName = "testuser", Email = "test@example.com", Password = "password" };
_context.Users.Add(user);
await _context.SaveChangesAsync();
var user = new UserEntity { UserName = "testuser", Email = "test@example.com" };
await _userManager.CreateAsync(user, "Password123!");
// Act
var result = await _authService.FindUserByEmailOrUsernameAsync("TESTUSER");
// Act — Identity normalizes usernames, so lookup is always case-insensitive
var found = await _userManager.FindByNameAsync("TESTUSER");
// Assert
Assert.IsTrue(result.Success);
Assert.IsNotNull(result.Data);
Assert.AreEqual("testuser", result.Data.UserName);
Assert.IsNotNull(found);
Assert.AreEqual("testuser", found.UserName);
}
[TestMethod]
public async Task FindUserByEmailOrUsernameAsync_ShouldReturnFailure_WhenUserNotFound()
public async Task FindByNameAsync_ShouldReturnNull_WhenUserNotFound()
{
// Act
var result = await _authService.FindUserByEmailOrUsernameAsync("nonexistent");
var result = await _userManager.FindByNameAsync("nonexistent");
// Assert
Assert.IsFalse(result.Success);
Assert.AreEqual("User not found.", result.Message);
Assert.IsNull(result);
}
}
+2
View File
@@ -9,7 +9,9 @@
<ItemGroup>
<PackageReference Include="dotenv.net" Version="4.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.6" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="MSTest" Version="4.0.1"/>
</ItemGroup>
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 1 ]]; then
echo "Usage: $0 <NewProjectName>"
exit 1
fi
NEW_NAME="$1"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$SCRIPT_DIR/Template"
if [[ ! -d "$ROOT" ]]; then
echo "Error: Template directory not found at $ROOT"
exit 1
fi
echo "Renaming 'Template' -> '$NEW_NAME' in: $ROOT"
# Rename files first (deepest first to avoid path issues)
while IFS= read -r -d '' path; do
dir="$(dirname "$path")"
base="$(basename "$path")"
new_base="${base//Template/$NEW_NAME}"
if [[ "$base" != "$new_base" ]]; then
echo " FILE: $base -> $new_base"
mv "$path" "$dir/$new_base"
fi
done < <(find "$ROOT" \
-not -path "*/bin/*" \
-not -path "*/obj/*" \
-not -path "*/.idea/*" \
-type f -name "*Template*" -print0 | sort -rz)
# Rename directories (deepest first)
while IFS= read -r -d '' path; do
parent="$(dirname "$path")"
base="$(basename "$path")"
new_base="${base//Template/$NEW_NAME}"
if [[ "$base" != "$new_base" ]]; then
echo " DIR: $base -> $new_base"
mv "$path" "$parent/$new_base"
fi
done < <(find "$ROOT" \
-not -path "*/bin/*" \
-not -path "*/obj/*" \
-not -path "*/.idea/*" \
-type d -name "*Template*" -print0 | sort -rz)
echo "Done."