Fixed up the database connection, added admin account and admin area

This commit is contained in:
Matěj Kubíček
2026-04-18 18:47:58 +02:00
parent f50bec167f
commit 982093ff7a
20 changed files with 425 additions and 14 deletions
@@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace TemplateWeb.Areas.Admin.Controllers;
[Area("Admin")]
[Authorize(Roles = "Admin")]
public abstract class AdminBaseController : Controller
{
}
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc;
namespace TemplateWeb.Areas.Admin.Controllers;
public class DashboardController : AdminBaseController
{
public IActionResult Index()
{
return View();
}
}
@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Data;
namespace TemplateWeb.Areas.Admin.Controllers;
public class UsersController : AdminBaseController
{
private readonly AppDbContext _context;
public UsersController(AppDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var users = await _context.Users.ToListAsync();
return View(users);
}
public async Task<IActionResult> Details(int id)
{
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == id);
if (user == null) return NotFound();
return View(user);
}
}
@@ -0,0 +1,19 @@
@{
ViewData["Title"] = "Dashboard";
}
<h1>Admin Dashboard</h1>
<p>Welcome to the administration area.</p>
<div class="row mt-4">
<div class="col-md-4">
<div class="card text-white bg-primary mb-3">
<div class="card-header">Users</div>
<div class="card-body">
<h5 class="card-title">Manage system users</h5>
<p class="card-text">View and edit user details.</p>
<a asp-controller="Users" asp-action="Index" class="btn btn-light">Go to Users</a>
</div>
</div>
</div>
</div>
@@ -0,0 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>@ViewData["Title"] - Admin Panel</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"/>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true"/>
<style>
body { display: flex; min-height: 100vh; flex-direction: column; }
.wrapper { display: flex; flex: 1; }
#sidebar { min-width: 250px; max-width: 250px; background: #343a40; color: #fff; transition: all 0.3s; }
#sidebar .sidebar-header { padding: 20px; background: #3c444b; }
#sidebar ul.components { padding: 20px 0; border-bottom: 1px solid #47748b; }
#sidebar ul p { color: #fff; padding: 10px; }
#sidebar ul li a { padding: 10px; font-size: 1.1em; display: block; color: #fff; text-decoration: none; }
#sidebar ul li a:hover { color: #343a40; background: #fff; }
#content { width: 100%; padding: 20px; }
</style>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-dark bg-dark border-bottom box-shadow">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">TemplateWeb <small class="text-muted">Admin</small></a>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Index">Back to Site</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="wrapper">
<!-- Sidebar -->
<nav id="sidebar">
<div class="sidebar-header">
<h3>Admin Panel</h3>
</div>
<ul class="list-unstyled components">
<li class="@(ViewContext.RouteData.Values["controller"]?.ToString() == "Dashboard" ? "active" : "")">
<a asp-area="Admin" asp-controller="Dashboard" asp-action="Index">Dashboard</a>
</li>
<li class="@(ViewContext.RouteData.Values["controller"]?.ToString() == "Users" ? "active" : "")">
<a asp-area="Admin" asp-controller="Users" asp-action="Index">Users</a>
</li>
<!-- Add more models here easily -->
</ul>
</nav>
<!-- Page Content -->
<div id="content">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
@@ -0,0 +1,31 @@
@model UserModel
@{
ViewData["Title"] = "User Details";
}
<div class="mb-4">
<a asp-action="Index" class="btn btn-secondary">&larr; Back to List</a>
</div>
<div class="card">
<div class="card-header bg-primary text-white">
<h3 class="card-title mb-0">User Information: @Model.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>
<dt class="col-sm-3">Username</dt>
<dd class="col-sm-9">@Model.UserName</dd>
<dt class="col-sm-3">Email</dt>
<dd class="col-sm-9">@Model.Email</dd>
<dt class="col-sm-3">Role</dt>
<dd class="col-sm-9">
<span class="badge @(Model.Role == UserRole.Admin ? "bg-danger" : "bg-info")">@Model.Role</span>
</dd>
</dl>
</div>
</div>
@@ -0,0 +1,34 @@
@model IEnumerable<UserModel>
@{
ViewData["Title"] = "User Management";
}
<div class="d-flex justify-content-between align-items-center mb-4">
<h1>Users</h1>
</div>
<table class="table table-striped table-hover">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var user 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>
<a asp-action="Details" asp-route-id="@user.Id" class="btn btn-sm btn-outline-primary">Details</a>
</td>
</tr>
}
</tbody>
</table>
@@ -0,0 +1,4 @@
@using TemplateWeb
@using TemplateWeb.Models
@using TemplateWeb.Models.DbModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@@ -0,0 +1,3 @@
@{
Layout = "_AdminLayout";
}
+27
View File
@@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore;
using TemplateWeb.Models.DbModels;
namespace TemplateWeb.Data;
public static class DataSeeder
{
public static async Task SeedAdminUser(AppDbContext context)
{
// Only run if no users exist
if (await context.Users.AnyAsync())
{
return;
}
var admin = new UserModel
{
UserName = "admin",
Email = "admin@template.com",
Password = BCrypt.Net.BCrypt.HashPassword("Admin123!"), // You should change this on first login
Role = UserRole.Admin
};
await context.Users.AddAsync(admin);
await context.SaveChangesAsync();
}
}
@@ -0,0 +1,58 @@
// <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
}
}
}
@@ -0,0 +1,38 @@
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,55 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TemplateWeb.Data;
#nullable disable
namespace TemplateWeb.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(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
}
}
}
+4 -4
View File
@@ -5,14 +5,14 @@ public class ServiceResult
public bool Success { get; protected set; } public bool Success { get; protected set; }
public string Message { get; protected set; } = string.Empty; public string Message { get; protected set; } = string.Empty;
public static ServiceResult Ok() => new ServiceResult { Success = true }; public static ServiceResult Ok() => new() { Success = true };
public static ServiceResult Failure(string message) => new ServiceResult { Success = false, Message = message }; public static ServiceResult Failure(string message) => new() { Success = false, Message = message };
} }
public class ServiceResult<T> : ServiceResult public class ServiceResult<T> : ServiceResult
{ {
public T? Data { get; private set; } public T? Data { get; private set; }
public static ServiceResult<T> Ok(T data) => new ServiceResult<T> { Success = true, Data = data }; public static ServiceResult<T> Ok(T data) => new() { Success = true, Data = data };
public new static ServiceResult<T> Failure(string message) => new ServiceResult<T> { Success = false, Message = message }; public new static ServiceResult<T> Failure(string message) => new() { Success = false, Message = message };
} }
+20 -2
View File
@@ -14,8 +14,9 @@ public class Program
DotEnv.Load(); DotEnv.Load();
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// gets the connection string from .env // gets the connection string from configuration
var connectionString = builder.Configuration["DEFAULT_CONNECTION"] ?? throw new InvalidOperationException("Connection string 'DEFAULT_CONNECTION' not found."); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<AppDbContext>(options => builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(connectionString)); options.UseNpgsql(connectionString));
@@ -36,6 +37,19 @@ public class Program
var app = builder.Build(); var app = builder.Build();
// Apply migrations on startup
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
if (db.Database.GetPendingMigrations().Any())
{
db.Database.Migrate();
}
// Seed the initial admin user
DataSeeder.SeedAdminUser(db).GetAwaiter().GetResult();
}
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {
@@ -48,6 +62,10 @@ public class Program
app.UseAuthorization(); app.UseAuthorization();
app.MapStaticAssets(); app.MapStaticAssets();
app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute( app.MapControllerRoute(
name: "default", name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}") pattern: "{controller=Home}/{action=Index}/{id?}")
+4 -4
View File
@@ -31,8 +31,8 @@ public class AuthService : IAuthService
var trimmed = emailOrUsername.Trim().ToLower(); var trimmed = emailOrUsername.Trim().ToLower();
var user = await _context.Users.SingleOrDefaultAsync(u => var user = await _context.Users.SingleOrDefaultAsync(u =>
u.Email.Equals(trimmed, StringComparison.CurrentCultureIgnoreCase) || string.Equals(u.Email, trimmed) ||
u.UserName.Equals(trimmed, StringComparison.CurrentCultureIgnoreCase)); string.Equals(u.UserName, trimmed));
return user == null ? ServiceResult<UserModel>.Failure("User not found.") : ServiceResult<UserModel>.Ok(user); return user == null ? ServiceResult<UserModel>.Failure("User not found.") : ServiceResult<UserModel>.Ok(user);
} }
@@ -77,8 +77,8 @@ public class AuthService : IAuthService
var emailTrimmed = viewModel.Email.Trim().ToLower(); var emailTrimmed = viewModel.Email.Trim().ToLower();
var existingUser = await _context.Users.AnyAsync(u => var existingUser = await _context.Users.AnyAsync(u =>
u.UserName.Equals(userNameTrimmed, StringComparison.CurrentCultureIgnoreCase) || string.Equals(u.UserName, userNameTrimmed) ||
u.Email.Equals(emailTrimmed, StringComparison.CurrentCultureIgnoreCase)); string.Equals(u.Email, emailTrimmed));
if (existingUser) if (existingUser)
{ {
+2 -2
View File
@@ -10,11 +10,11 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.1.0" /> <PackageReference Include="BCrypt.Net-Next" Version="4.1.0" />
<PackageReference Include="dotenv.net" Version="4.0.2" /> <PackageReference Include="dotenv.net" Version="4.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0-preview.1.25081.1"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.6">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0-preview.1" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -10,7 +10,7 @@ public class AuthLoginViewModel
[Display(Name = "Password")] [Display(Name = "Password")]
[DataType(DataType.Password)] [DataType(DataType.Password)]
[Required] [MinLength(5)] [Required] [MinLength(4)]
public string Password { get; set; } public string Password { get; set; }
[Display(Name = "Remember me?")] [Display(Name = "Remember me?")]
@@ -30,6 +30,12 @@
<ul class="navbar-nav"> <ul class="navbar-nav">
@if (User.Identity?.IsAuthenticated == true) @if (User.Identity?.IsAuthenticated == true)
{ {
@if (User.IsInRole("Admin"))
{
<li class="nav-item">
<a class="nav-link text-primary fw-bold" asp-area="Admin" asp-controller="Dashboard" asp-action="Index">Admin Panel</a>
</li>
}
<li class="nav-item"> <li class="nav-item">
<span class="nav-link text-dark">Hello, @User.Identity.Name!</span> <span class="nav-link text-dark">Hello, @User.Identity.Name!</span>
</li> </li>
+1 -1
View File
@@ -9,7 +9,7 @@
ports: ports:
- "5432:5432" - "5432:5432"
volumes: volumes:
- postgres_data:/var/lib/postgresql/data - postgres_data:/var/lib/postgresql
templateweb: templateweb:
image: templateweb image: templateweb