Compare commits

...

3 Commits

Author SHA1 Message Date
Francesco Lorenzo D'Amico 7fb60d6f55 Create EF-Migration for AdminUser and ContactMessage 2026-08-18 14:58:08 +02:00
Francesco Lorenzo D'Amico 04877691b9 Add protected admin scope with login 2026-08-18 14:56:41 +02:00
Francesco Lorenzo D'Amico dfe5044c69 Connect contactMessage and adminUser on DB plus added contactMessage model 2026-08-18 14:52:29 +02:00
12 changed files with 424 additions and 11 deletions
@@ -5,4 +5,6 @@ namespace RazorPagesMovie.Data;
public class RazorPagesMovieContext(DbContextOptions<RazorPagesMovieContext> options) : DbContext(options) public class RazorPagesMovieContext(DbContextOptions<RazorPagesMovieContext> options) : DbContext(options)
{ {
public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; } = default!; public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; } = default!;
public DbSet<RazorPagesMovie.Models.AdminUser> AdminUser { get; set; } = default!;
public DbSet<RazorPagesMovie.Models.ContactMessage> ContactMessage { get; set; } = default!;
} }
@@ -0,0 +1,125 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using RazorPagesMovie.Data;
#nullable disable
namespace RazorPagesMovie.Migrations
{
[DbContext(typeof(RazorPagesMovieContext))]
[Migration("20260818121135_AddAdminUserAndContactMessage")]
partial class AddAdminUserAndContactMessage
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.28")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("RazorPagesMovie.Models.AdminUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Id");
b.ToTable("AdminUser");
});
modelBuilder.Entity("RazorPagesMovie.Models.ContactMessage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(4000)
.HasColumnType("nvarchar(4000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Phone")
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<DateTime>("SentAt")
.HasColumnType("datetime2");
b.Property<string>("Subject")
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.HasKey("Id");
b.ToTable("ContactMessage");
});
modelBuilder.Entity("RazorPagesMovie.Models.Movie", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Genre")
.IsRequired()
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<decimal>("Price")
.HasColumnType("decimal(18, 2)");
b.Property<string>("Rating")
.IsRequired()
.HasMaxLength(5)
.HasColumnType("nvarchar(5)");
b.Property<DateTime>("ReleaseDate")
.HasColumnType("datetime2");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("nvarchar(60)");
b.HasKey("Id");
b.ToTable("Movie");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,57 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace RazorPagesMovie.Migrations
{
/// <inheritdoc />
public partial class AddAdminUserAndContactMessage : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AdminUser",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Username = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AdminUser", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ContactMessage",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Email = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false),
Phone = table.Column<string>(type: "nvarchar(30)", maxLength: 30, nullable: true),
Subject = table.Column<string>(type: "nvarchar(150)", maxLength: 150, nullable: true),
Message = table.Column<string>(type: "nvarchar(4000)", maxLength: 4000, nullable: false),
SentAt = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactMessage", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AdminUser");
migrationBuilder.DropTable(
name: "ContactMessage");
}
}
}
@@ -22,6 +22,67 @@ namespace RazorPagesMovie.Migrations
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("RazorPagesMovie.Models.AdminUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Id");
b.ToTable("AdminUser");
});
modelBuilder.Entity("RazorPagesMovie.Models.ContactMessage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(4000)
.HasColumnType("nvarchar(4000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Phone")
.HasMaxLength(30)
.HasColumnType("nvarchar(30)");
b.Property<DateTime>("SentAt")
.HasColumnType("datetime2");
b.Property<string>("Subject")
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.HasKey("Id");
b.ToTable("ContactMessage");
});
modelBuilder.Entity("RazorPagesMovie.Models.Movie", b => modelBuilder.Entity("RazorPagesMovie.Models.Movie", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
+15
View File
@@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;
namespace RazorPagesMovie.Models;
public class AdminUser
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Username { get; set; } = string.Empty;
[Required]
public string PasswordHash { get; set; } = string.Empty;
}
+1 -2
View File
@@ -6,7 +6,6 @@ public class ContactMessage
{ {
public int Id { get; set; } public int Id { get; set; }
[Display(Name = "Name")]
[Required] [Required]
[StringLength(100)] [StringLength(100)]
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
@@ -28,7 +27,7 @@ public class ContactMessage
[Display(Name = "Nachricht")] [Display(Name = "Nachricht")]
[Required] [Required]
[StringLength(4000)] [StringLength(5000)]
public string Message { get; set; } = string.Empty; public string Message { get; set; } = string.Empty;
[Display(Name = "Gesendet am")] [Display(Name = "Gesendet am")]
+11
View File
@@ -0,0 +1,11 @@
@page
@model RazorPagesMovie.Pages.Admin.IndexModel
@{
ViewData["Title"] = "Admin";
}
<h1>Welcome, @User.Identity?.Name</h1>
<form method="post" asp-page-handler="Logout">
<button type="submit" class="btn btn-secondary">Logout</button>
</form>
@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPagesMovie.Pages.Admin;
public class IndexModel : PageModel
{
public void OnGet()
{
}
public async Task<IActionResult> OnPostLogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToPage("/Login");
}
}
+28
View File
@@ -0,0 +1,28 @@
@page
@model RazorPagesMovie.Pages.LoginModel
@{
ViewData["Title"] = "Login";
}
<div class="row justify-content-center">
<div class="col-md-4">
<h1>Admin Login</h1>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">@Model.ErrorMessage</div>
}
<form method="post">
<div class="mb-3">
<label asp-for="Username" class="form-label"></label>
<input asp-for="Username" class="form-control" autofocus />
</div>
<div class="mb-3">
<label asp-for="Password" class="form-label"></label>
<input asp-for="Password" type="password" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
+53
View File
@@ -0,0 +1,53 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;
using RazorPagesMovie.Models;
namespace RazorPagesMovie.Pages;
public class LoginModel : PageModel
{
private readonly RazorPagesMovieContext _context;
public LoginModel(RazorPagesMovieContext context)
{
_context = context;
}
[BindProperty]
public string Username { get; set; } = string.Empty;
[BindProperty]
public string Password { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync(string? returnUrl)
{
var user = await _context.AdminUser.SingleOrDefaultAsync(u => u.Username == Username);
var hasher = new PasswordHasher<AdminUser>();
if (user is null || hasher.VerifyHashedPassword(user, user.PasswordHash, Password) == PasswordVerificationResult.Failed)
{
ErrorMessage = "Benutzername oder Passwort ist falsch.";
return Page();
}
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, user.Username) },
CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
return LocalRedirect(returnUrl ?? "/Admin");
}
}
+15 -1
View File
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data; using RazorPagesMovie.Data;
using RazorPagesMovie.Models; using RazorPagesMovie.Models;
@@ -6,7 +7,19 @@ var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true); builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true);
builder.Services.AddDbContext<RazorPagesMovieContext>(options => builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found."))); options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));
builder.Services.AddRazorPages();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Login";
options.AccessDeniedPath = "/Login";
});
builder.Services.AddAuthorization();
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin");
});
var app = builder.Build(); var app = builder.Build();
@@ -27,6 +40,7 @@ if (!app.Environment.IsDevelopment())
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapRazorPages(); app.MapRazorPages();
app.Run(); app.Run();
+37 -8
View File
@@ -1,4 +1,6 @@
using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using RazorPagesMovie.Data; using RazorPagesMovie.Data;
namespace RazorPagesMovie.Models; namespace RazorPagesMovie.Models;
@@ -15,18 +17,45 @@ public static class SeedData
throw new ArgumentNullException("Null RazorPagesMovieContext"); throw new ArgumentNullException("Null RazorPagesMovieContext");
} }
if (context.Movie.Any()) if (!context.Movie.Any())
{ {
return; context.Movie.AddRange(
}
context.Movie.AddRange(
new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M, Rating = "R" }, new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M, Rating = "R" },
new Movie { Title = "Ghostbusters", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M, Rating = "G" }, new Movie { Title = "Ghostbusters", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M, Rating = "G" },
new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M, Rating = "G" }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M, Rating = "G" },
new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M, Rating = "NR" } new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M, Rating = "NR" }
); );
context.SaveChanges(); context.SaveChanges();
}
if (!context.AdminUser.Any())
{
var accounts = serviceProvider.GetRequiredService<IConfiguration>()
.GetSection("AdminAccounts")
.Get<List<AdminAccountSeed>>() ?? new List<AdminAccountSeed>();
var hasher = new PasswordHasher<AdminUser>();
foreach (var account in accounts)
{
if (string.IsNullOrWhiteSpace(account.Username) || string.IsNullOrWhiteSpace(account.Password))
{
continue;
}
var user = new AdminUser { Username = account.Username };
user.PasswordHash = hasher.HashPassword(user, account.Password);
context.AdminUser.Add(user);
}
context.SaveChanges();
}
} }
} }
private class AdminAccountSeed
{
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
} }