checkpoint

This commit is contained in:
2026-10-28 13:23:35 +02:00
parent cce5e348b3
commit 33dad8ca5a
26 changed files with 1949 additions and 49 deletions
+23 -7
View File
@@ -1,26 +1,30 @@
using StatiKosev.Services;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Localization;
using StatiKosev.Data;
using StatiKosev.Logging;
using StatiKosev.Services;
namespace StatiKosev.Controllers;
[Route("messages")]
public class PrivateMessageController(MessageService messagesService, ILogger<PrivateMessageController> logger) : Controller
public class PrivateMessageController(
MessageService messagesService,
IStringLocalizer<StringValues> strings,
ILogger<PrivateMessageController> logger) : Controller
{
//form post from _MessageMe, redirects back to the page it came from
[HttpPost("send")]
[EnableRateLimiting("contact")]
public async Task<IActionResult> Send([FromForm] SendPrivateMessageRequest req, string? returnUrl)
[ValidateAntiForgeryToken]
public async Task<IActionResult> Send([FromForm] SendPrivateMessageRequest req, [FromForm] string? returnUrl)
{
var back = Url.IsLocalUrl(returnUrl) ? returnUrl : "/";
if (!ModelState.IsValid)
{
TempData["Status"] = "The message must be between 1 and 2000 characters.";
TempData["Status"] = strings["MessageInvalid"].Value;
TempData["StatusType"] = "error";
return LocalRedirect(back);
}
@@ -36,8 +40,20 @@ public class PrivateMessageController(MessageService messagesService, ILogger<Pr
else
await messagesService.SendAsUserAsync(req.Body, userId, senderUsername, userAgent);
TempData["Status"] = "Sent, thank you!";
TempData["Status"] = strings["MessageSent"].Value;
TempData["StatusType"] = "success";
return LocalRedirect(back);
}
//JSON for the Inbox page (AJAX)
[HttpGet("")]
[Authorize(Policy = "AdminOnly")]
public async Task<IActionResult> Inbox(bool unreadOnly = false) =>
Ok(await messagesService.GetInboxAsync(unreadOnly));
[HttpPost("{id:int}/read")]
[Authorize(Policy = "AdminOnly")]
[ValidateAntiForgeryToken] // token comes in the RequestVerificationToken header
public async Task<IActionResult> MarkRead(int id) =>
await messagesService.MarkReadAsync(id) == 0 ? NotFound() : NoContent();
}
+32
View File
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace StatiKosev.Data;
public static class DbSeeder
{
public const string UserRole = "User";
public const string AdminRole = "Admin";
//applies pending migrations, creates the roles and makes the configured AdminEmail account an admin
public static async Task SeedAsync(IServiceProvider services, string? adminEmail)
{
using var scope = services.CreateScope();
var sp = scope.ServiceProvider;
await sp.GetRequiredService<AppDbContext>().Database.MigrateAsync();
var roles = sp.GetRequiredService<RoleManager<IdentityRole>>();
foreach (var role in new[] { UserRole, AdminRole })
if (!await roles.RoleExistsAsync(role))
await roles.CreateAsync(new IdentityRole(role));
if (string.IsNullOrWhiteSpace(adminEmail)) return;
var users = sp.GetRequiredService<UserManager<IdentityUser>>();
var admin = await users.FindByEmailAsync(adminEmail);
if (admin is not null && !await users.IsInRoleAsync(admin, AdminRole))
await users.AddToRoleAsync(admin, AdminRole);
}
public static bool IsAdminEmail(string? email, string? adminEmail) =>
!string.IsNullOrWhiteSpace(adminEmail) && string.Equals(email, adminEmail, StringComparison.OrdinalIgnoreCase);
}
+3 -3
View File
@@ -7,8 +7,8 @@ public class PrivateMessage
{
public int Id { get; set; }
public bool Anonymous { get; set; }
public string? SenderId { get; set; }
public string SenderUsername { get; set; } = "";
[MaxLength(450)] public string? SenderId { get; set; }
[MaxLength(512)] public string SenderUsername { get; set; } = "";
[MaxLength(3000)] public string Body { get; set; } = "";
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public bool IsRead { get; set; }
@@ -18,7 +18,7 @@ public class PrivateMessage
public PrivateMessage(string body, string userAgent)
{
CreatedAt = DateTime.UtcNow;
SenderUsername = userAgent + "___" + CreatedAt.ToString("dd-MM-yyyy___HH:mm:ss");
SenderUsername = userAgent[..Math.Min(userAgent.Length, 480)] + "___" + CreatedAt.ToString("dd-MM-yyyy___HH:mm:ss");
Anonymous = true;
SenderId = null;
Body = body;
+118 -1
View File
@@ -13,7 +13,7 @@
<value>Login</value>
</data>
<data name="Hello" xml:space="preserve">
<value>Greetings!</value>
<value>Hello, {0}!</value>
</data>
<data name="Title" xml:space="preserve">
<value>Stati Kosev</value>
@@ -21,4 +21,121 @@
<data name="SendMeAMessage" xml:space="preserve">
<value>Send me a DM.</value>
</data>
<data name="Home" xml:space="preserve">
<value>Home</value>
</data>
<data name="Navigation" xml:space="preserve">
<value>Navigation</value>
</data>
<data name="Description" xml:space="preserve">
<value>Here you'll find my projects, an art gallery and a way to get in touch.</value>
</data>
<data name="PhotoAlt" xml:space="preserve">
<value>Photo of Stati Kosev</value>
</data>
<data name="Guest" xml:space="preserve">
<value>guest</value>
</data>
<data name="Gallery" xml:space="preserve">
<value>Gallery</value>
</data>
<data name="GalleryEmpty" xml:space="preserve">
<value>The gallery is empty.</value>
</data>
<data name="Previous" xml:space="preserve">
<value>Previous</value>
</data>
<data name="Next" xml:space="preserve">
<value>Next</value>
</data>
<data name="Pause" xml:space="preserve">
<value>Pause</value>
</data>
<data name="Play" xml:space="preserve">
<value>Play</value>
</data>
<data name="GoToSlide" xml:space="preserve">
<value>Image {0}</value>
</data>
<data name="SlideOf" xml:space="preserve">
<value>{0} of {1}</value>
</data>
<data name="MessageForm" xml:space="preserve">
<value>Message form</value>
</data>
<data name="SendingAs" xml:space="preserve">
<value>Sending as </value>
</data>
<data name="SendingAnon" xml:space="preserve">
<value>Send anonymously</value>
</data>
<data name="YouAreNotLoggedIn" xml:space="preserve">
<value>You are not logged in</value>
</data>
<data name="CancelMessaging" xml:space="preserve">
<value>Cancel the message</value>
</data>
<data name="SendMessage" xml:space="preserve">
<value>Send</value>
</data>
<data name="CancelSend" xml:space="preserve">
<value>Cancel</value>
</data>
<data name="YourMessage" xml:space="preserve">
<value>Your message</value>
</data>
<data name="MessageSent" xml:space="preserve">
<value>Sent, thank you!</value>
</data>
<data name="MessageInvalid" xml:space="preserve">
<value>The message must be between 1 and 2000 characters.</value>
</data>
<data name="TooManyMessages" xml:space="preserve">
<value>Please wait a moment before sending another message.</value>
</data>
<data name="Messages" xml:space="preserve">
<value>Messages</value>
</data>
<data name="UnreadOnly" xml:space="preserve">
<value>Unread only</value>
</data>
<data name="MarkRead" xml:space="preserve">
<value>Mark as read</value>
</data>
<data name="Read" xml:space="preserve">
<value>Read</value>
</data>
<data name="NoMessages" xml:space="preserve">
<value>No messages.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Could not load the messages.</value>
</data>
<data name="Loading" xml:space="preserve">
<value>Loading…</value>
</data>
<data name="Anonymous" xml:space="preserve">
<value>Anonymous</value>
</data>
<data name="Register" xml:space="preserve">
<value>Register</value>
</data>
<data name="Email" xml:space="preserve">
<value>Email</value>
</data>
<data name="Password" xml:space="preserve">
<value>Password</value>
</data>
<data name="Logout" xml:space="preserve">
<value>Log out</value>
</data>
<data name="PasswordHint" xml:space="preserve">
<value>At least 8 characters, with an uppercase letter, a lowercase letter and a digit.</value>
</data>
<data name="LoginFailed" xml:space="preserve">
<value>Wrong email or password.</value>
</data>
<data name="RegisterFailed" xml:space="preserve">
<value>Registration failed. The email may already be taken, or the password is too weak.</value>
</data>
</root>
+91 -1
View File
@@ -13,7 +13,7 @@
<value>Вход</value>
</data>
<data name="Hello" xml:space="preserve">
<value>Здравейте!</value>
<value>Здравейте, {0}!</value>
</data>
<data name="Title" xml:space="preserve">
<value>Стати Косев</value>
@@ -48,4 +48,94 @@
<data name="YourMessage" xml:space="preserve">
<value>Вашето съобщение</value>
</data>
<data name="Home" xml:space="preserve">
<value>Начало</value>
</data>
<data name="Navigation" xml:space="preserve">
<value>Навигация</value>
</data>
<data name="Description" xml:space="preserve">
<value>Тук ще намерите моите проекти, галерия с творби и начин да се свържете с мен.</value>
</data>
<data name="PhotoAlt" xml:space="preserve">
<value>Снимка на Стати Косев</value>
</data>
<data name="Guest" xml:space="preserve">
<value>гост</value>
</data>
<data name="GalleryEmpty" xml:space="preserve">
<value>Галерията е празна.</value>
</data>
<data name="Previous" xml:space="preserve">
<value>Предишна</value>
</data>
<data name="Next" xml:space="preserve">
<value>Следваща</value>
</data>
<data name="Pause" xml:space="preserve">
<value>Пауза</value>
</data>
<data name="Play" xml:space="preserve">
<value>Пусни</value>
</data>
<data name="GoToSlide" xml:space="preserve">
<value>Снимка {0}</value>
</data>
<data name="SlideOf" xml:space="preserve">
<value>{0} от {1}</value>
</data>
<data name="MessageSent" xml:space="preserve">
<value>Изпратено, благодаря!</value>
</data>
<data name="MessageInvalid" xml:space="preserve">
<value>Съобщението трябва да е между 1 и 2000 символа.</value>
</data>
<data name="TooManyMessages" xml:space="preserve">
<value>Изчакайте малко, преди да изпратите следващо съобщение.</value>
</data>
<data name="Messages" xml:space="preserve">
<value>Съобщения</value>
</data>
<data name="UnreadOnly" xml:space="preserve">
<value>Само непрочетени</value>
</data>
<data name="MarkRead" xml:space="preserve">
<value>Отбележи като прочетено</value>
</data>
<data name="Read" xml:space="preserve">
<value>Прочетено</value>
</data>
<data name="NoMessages" xml:space="preserve">
<value>Няма съобщения.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Съобщенията не можаха да се заредят.</value>
</data>
<data name="Loading" xml:space="preserve">
<value>Зареждане…</value>
</data>
<data name="Anonymous" xml:space="preserve">
<value>Анонимно</value>
</data>
<data name="Register" xml:space="preserve">
<value>Регистрация</value>
</data>
<data name="Email" xml:space="preserve">
<value>Имейл</value>
</data>
<data name="Password" xml:space="preserve">
<value>Парола</value>
</data>
<data name="Logout" xml:space="preserve">
<value>Изход</value>
</data>
<data name="PasswordHint" xml:space="preserve">
<value>Поне 8 символа, с главна буква, малка буква и цифра.</value>
</data>
<data name="LoginFailed" xml:space="preserve">
<value>Грешен имейл или парола.</value>
</data>
<data name="RegisterFailed" xml:space="preserve">
<value>Регистрацията не бе успешна. Имейлът може вече да е зает или паролата е твърде слаба.</value>
</data>
</root>
+317
View File
@@ -0,0 +1,317 @@
// <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 StatiKosev.Data;
#nullable disable
namespace StatiKosev.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20261028091601_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.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.IdentityUser", 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.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")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
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")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("StatiKosev.Data.PrivateMessage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<bool>("Anonymous")
.HasColumnType("boolean");
b.Property<string>("Body")
.IsRequired()
.HasMaxLength(3000)
.HasColumnType("character varying(3000)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("SenderId")
.HasMaxLength(450)
.HasColumnType("character varying(450)");
b.Property<string>("SenderUsername")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.HasKey("Id");
b.ToTable("PrivateMessages");
});
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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", 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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
+244
View File
@@ -0,0 +1,244 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace StatiKosev.Migrations
{
/// <inheritdoc />
public partial class Initial : 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: "PrivateMessages",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Anonymous = table.Column<bool>(type: "boolean", nullable: false),
SenderId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: true),
SenderUsername = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
Body = table.Column<string>(type: "character varying(3000)", maxLength: 3000, nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
IsRead = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PrivateMessages", 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: "character varying(128)", maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(type: "character varying(128)", maxLength: 128, 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: "character varying(128)", maxLength: 128, nullable: false),
Name = table.Column<string>(type: "character varying(128)", maxLength: 128, 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: "PrivateMessages");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
+314
View File
@@ -0,0 +1,314 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using StatiKosev.Data;
#nullable disable
namespace StatiKosev.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.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.IdentityUser", 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.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")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
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")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("StatiKosev.Data.PrivateMessage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<bool>("Anonymous")
.HasColumnType("boolean");
b.Property<string>("Body")
.IsRequired()
.HasMaxLength(3000)
.HasColumnType("character varying(3000)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("SenderId")
.HasMaxLength(450)
.HasColumnType("character varying(450)");
b.Property<string>("SenderUsername")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.HasKey("Id");
b.ToTable("PrivateMessages");
});
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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", 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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
+41 -14
View File
@@ -1,21 +1,48 @@
@page
@model StatiKosev.Pages.Gallery
@{
Layout = null;
ViewData["Title"] = StringValues["Gallery"];
}
@section Head {
<link rel="stylesheet" href="~/styles/gallery.css" asp-append-version="true"/>
}
<!DOCTYPE html>
<html>
<head>
<title>
@StringValues["Gallery"]
</title>
</head>
<body>
<div>
<section class="slideshow" aria-roledescription="carousel" aria-label="@StringValues["Gallery"]">
<h1>@StringValues["Gallery"]</h1>
@if (Model.Images.Count == 0)
{
<p>@StringValues["GalleryEmpty"]</p>
}
else
{
@* without JavaScript this is a swipeable scroll-snap strip; slideshow.js adds the buttons and autoplay *@
<div class="slides" tabindex="0">
@for (var i = 0; i < Model.Images.Count; i++)
{
<figure class="slide" role="group" aria-roledescription="slide"
aria-label="@StringValues["SlideOf", i + 1, Model.Images.Count]">
<img src="@Model.Images[i]" alt="@StringValues["GoToSlide", i + 1]" asp-append-version="true"
loading="@(i == 0 ? "eager" : "lazy")"/>
</figure>
}
</div>
</body>
</html>
<div class="slideshow-controls" hidden>
<button type="button" class="slide-prev" aria-label="@StringValues["Previous"]">&#8249;</button>
<div class="slide-dots">
@for (var i = 0; i < Model.Images.Count; i++)
{
<button type="button" data-index="@i" aria-label="@StringValues["GoToSlide", i + 1]"></button>
}
</div>
<button type="button" class="slide-toggle" data-pause="@StringValues["Pause"]" data-play="@StringValues["Play"]"
aria-label="@StringValues["Pause"]">&#10074;&#10074;</button>
<button type="button" class="slide-next" aria-label="@StringValues["Next"]">&#8250;</button>
</div>
}
</section>
@section Scripts {
<script src="~/scripts/slideshow.js" asp-append-version="true"></script>
}
+15 -1
View File
@@ -2,10 +2,24 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
namespace StatiKosev.Pages;
public class Gallery : PageModel
public class Gallery(IWebHostEnvironment env) : PageModel
{
static readonly string[] ImageExtensions = [".png", ".jpg", ".jpeg", ".webp", ".gif"];
public IReadOnlyList<string> Images { get; private set; } = [];
//every image in wwwroot/images except the profile photo used on the home page
public void OnGet()
{
var dir = Path.Combine(env.WebRootPath, "images");
if (!Directory.Exists(dir)) return;
Images = Directory.EnumerateFiles(dir)
.Where(f => ImageExtensions.Contains(Path.GetExtension(f).ToLowerInvariant()))
.Select(Path.GetFileName)
.Where(n => !n!.StartsWith("profile.", StringComparison.OrdinalIgnoreCase))
.Order()
.Select(n => "/images/" + n)
.ToList();
}
}
+30
View File
@@ -0,0 +1,30 @@
@page
@model StatiKosev.Pages.InboxModel
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
@{
ViewData["Title"] = StringValues["Messages"];
}
@section Head {
<link rel="stylesheet" href="~/styles/inbox.css" asp-append-version="true"/>
}
@* messages are loaded as JSON from PrivateMessageController by inbox.js *@
<section class="inbox"
data-api="/messages"
data-token="@Antiforgery.GetAndStoreTokens(HttpContext).RequestToken"
data-anonymous="@StringValues["Anonymous"]"
data-mark-read="@StringValues["MarkRead"]"
data-read="@StringValues["Read"]"
data-empty="@StringValues["NoMessages"]"
data-failed="@StringValues["LoadFailed"]">
<header class="inbox-header">
<h1>@StringValues["Messages"]</h1>
<label><input type="checkbox" class="inbox-unread-only"/> @StringValues["UnreadOnly"]</label>
</header>
<p class="inbox-status" role="status" aria-live="polite">@StringValues["Loading"]</p>
<ol class="inbox-list"></ol>
</section>
@section Scripts {
<script src="~/scripts/inbox.js" asp-append-version="true"></script>
}
+12
View File
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace StatiKosev.Pages;
[Authorize(Policy = "AdminOnly")]
public class InboxModel : PageModel
{
public void OnGet()
{
}
}
+36
View File
@@ -0,0 +1,36 @@
@page
@model StatiKosev.Pages.LoginModel
@{
ViewData["Title"] = StringValues["Login"];
}
@section Head {
<link rel="stylesheet" href="~/styles/account.css" asp-append-version="true"/>
}
<div class="auth-forms">
<form method="post" action="/account/login" asp-antiforgery="true" class="auth-card" data-once>
<h1>@StringValues["Login"]</h1>
<input type="hidden" name="returnUrl" value="@Model.ReturnUrl"/>
<label>@StringValues["Email"]
<input type="email" name="email" required autocomplete="username"/>
</label>
<label>@StringValues["Password"]
<input type="password" name="password" required autocomplete="current-password"/>
</label>
<button type="submit">@StringValues["Login"]</button>
</form>
<form method="post" action="/account/register" asp-antiforgery="true" class="auth-card" data-once>
<h1>@StringValues["Register"]</h1>
<input type="hidden" name="returnUrl" value="@Model.ReturnUrl"/>
<label>@StringValues["Email"]
<input type="email" name="email" required autocomplete="email"/>
</label>
<label>@StringValues["Password"]
<input type="password" name="password" required minlength="8" autocomplete="new-password"
aria-describedby="password-hint"/>
</label>
<p id="password-hint" class="hint">@StringValues["PasswordHint"]</p>
<button type="submit">@StringValues["Register"]</button>
</form>
</div>
+15
View File
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace StatiKosev.Pages;
public class LoginModel : PageModel
{
[BindProperty(SupportsGet = true)]
public string? ReturnUrl { get; set; }
public void OnGet()
{
if (!Url.IsLocalUrl(ReturnUrl)) ReturnUrl = "/";
}
}
+38 -2
View File
@@ -1,8 +1,19 @@
@{
var path = Context.Request.Path.Value ?? "/";
var lang = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
var loggedIn = User.Identity?.IsAuthenticated == true;
string Active(string p) => path.Equals(p, StringComparison.OrdinalIgnoreCase) ? "active" : "";
string? Current(string p) => Active(p) == "" ? null : "page";
//one-line notice: message status from the controller (TempData), rate limit (?wait=1), login/register errors (?auth=)
var status = TempData["Status"] as string;
var statusType = TempData["StatusType"] as string ?? "info";
if (Context.Request.Query["wait"] == "1")
(status, statusType) = (StringValues["TooManyMessages"].Value, "error");
else if (Context.Request.Query["auth"] == "login-failed")
(status, statusType) = (StringValues["LoginFailed"].Value, "error");
else if (Context.Request.Query["auth"] == "register-failed")
(status, statusType) = (StringValues["RegisterFailed"].Value, "error");
}
<!DOCTYPE html>
@@ -11,23 +22,48 @@
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>@StringValues["Title"]</title>
<title>@(ViewData["Title"] ?? StringValues["Title"])</title>
<link rel="stylesheet" href="~/styles/site.css" asp-append-version="true"/>
<link rel="stylesheet" href="~/styles/message-form.css" asp-append-version="true"/>
@await RenderSectionAsync("Head", required: false)
</head>
<body>
<header class="site-header">
<nav class="main-nav" aria-label="@StringValues["Navigation"]">
<a asp-page="/Index" class="@Active("/")" aria-current="@Current("/")">@StringValues["Home"]</a>
<a asp-page="/Gallery" class="@Active("/Gallery")" aria-current="@Current("/Gallery")">@StringValues["Gallery"]</a>
<a asp-page="/Contact" class="@Active("/Contact")" aria-current="@Current("/Contact")">@StringValues["Contact"]</a>
@if (User.IsInRole("Admin"))
{
<a asp-page="/Inbox" class="@Active("/Inbox")" aria-current="@Current("/Inbox")">@StringValues["Messages"]</a>
}
</nav>
<div class="header-end">
@if (loggedIn)
{
<form method="post" action="/account/logout" asp-antiforgery="true" class="logout-form">
<span class="user-name">@User.Identity!.Name</span>
<button type="submit">@StringValues["Logout"]</button>
</form>
}
else
{
<a asp-page="/Login" asp-route-returnUrl="@(Active("/Login") == "" ? path : null)" class="@Active("/Login")" aria-current="@Current("/Login")">@StringValues["Login"]</a>
}
<div class="lang-switch">
<a href="/set-language?culture=bg&returnUrl=@Context.Request.Path" class="@(lang == "bg" ? "active" : "")" lang="bg">Български</a>
<a href="/set-language?culture=en&returnUrl=@Context.Request.Path" class="@(lang == "en" ? "active" : "")" lang="en">English</a>
</div>
</div>
</header>
@if (status is not null)
{
<p class="flash flash-@statusType" role="status">@status</p>
}
<main>@RenderBody()</main>
<script src="~/scripts/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
+17 -5
View File
@@ -15,11 +15,12 @@ namespace StatiKosev;
public class Program
{
public static void Main(string[] arguments)
public static async Task Main(string[] arguments)
{
var builder = WebApplication.CreateBuilder(arguments);
var databaseConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var messageRateLimitSeconds = builder.Configuration.GetValue("MessageRateLimitSeconds", 10);
var adminEmail = builder.Configuration["AdminEmail"]; // this account sees the Inbox
builder.Services.AddLocalization(o => o.ResourcesPath = "LanguagesValues");
builder.Services.AddRazorPages();
@@ -38,6 +39,11 @@ public class Program
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
builder.Services.ConfigureApplicationCookie(o =>
{
o.LoginPath = "/Login";
o.AccessDeniedPath = "/";
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
@@ -81,6 +87,7 @@ public class Program
Console.WriteLine($"Database connection string: {databaseConnectionString}");
var app = builder.Build();
await DbSeeder.SeedAsync(app.Services, adminEmail);
app.UseAntiforgery();
app.UseRateLimiter();
@@ -90,7 +97,10 @@ public class Program
static string ForceLocalizeUrl(string? u) =>
!string.IsNullOrEmpty(u) && u.StartsWith('/') && !u.StartsWith("//") && !u.StartsWith("/\\") ? u : "/";
Console.WriteLine("Local==" + ForceLocalizeUrl(app.Environment.ApplicationName));
//failed login/register go back to the login page with the reason and the original returnUrl
static string LoginPage(string auth, string back) =>
QueryHelpers.AddQueryString("/Login", new Dictionary<string, string?> { ["auth"] = auth, ["returnUrl"] = back });
var account = app.MapGroup("/account");
account.MapPost("/login", async ([FromForm] string email, [FromForm] string password,
@@ -98,7 +108,7 @@ public class Program
{
var r = await signIn.PasswordSignInAsync(email, password, isPersistent: true, lockoutOnFailure: true);
var back = ForceLocalizeUrl(returnUrl);
return Results.LocalRedirect(r.Succeeded ? back : QueryHelpers.AddQueryString(back, "auth", "login-failed"));
return Results.LocalRedirect(r.Succeeded ? back : LoginPage("login-failed", back));
});
account.MapPost("/register", async ([FromForm] string email, [FromForm] string password,
@@ -108,8 +118,10 @@ public class Program
var user = new IdentityUser { UserName = email, Email = email };
var res = await users.CreateAsync(user, password);
if (!res.Succeeded)
return Results.LocalRedirect(QueryHelpers.AddQueryString(back, "auth", "register-failed"));
await users.AddToRoleAsync(user, "User");
return Results.LocalRedirect(LoginPage("register-failed", back));
await users.AddToRoleAsync(user, DbSeeder.UserRole);
if (DbSeeder.IsAdminEmail(email, adminEmail))
await users.AddToRoleAsync(user, DbSeeder.AdminRole);
await signIn.SignInAsync(user, isPersistent: true);
return Results.LocalRedirect(back);
});
-1
View File
@@ -8,7 +8,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.3.13" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9" />
+2 -1
View File
@@ -3,5 +3,6 @@
"DefaultConnection": "Host=192.168.1.1;Database=dotnet_portfolio;Username=dotnet_portfolio_usr;Password=z50QhAN3v8P7Eqmj0ptPppr3jtC4WkwA"
},
"Logging": { "LogLevel": { "Default": "Information" } },
"MessageRateLimitSeconds": 30
"MessageRateLimitSeconds": 30,
"AdminEmail": ""
}
+13
View File
@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "10.0.9",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}
+81
View File
@@ -0,0 +1,81 @@
// Inbox: loads messages as JSON (GET /messages) and marks them read (POST /messages/{id}/read).
const inbox = document.querySelector('.inbox');
const list = inbox.querySelector('.inbox-list');
const status = inbox.querySelector('.inbox-status');
const unreadOnly = inbox.querySelector('.inbox-unread-only');
const t = inbox.dataset;
const dateFormat = new Intl.DateTimeFormat(document.documentElement.lang, { dateStyle: 'medium', timeStyle: 'short' });
async function load() {
try {
const res = await fetch(`${t.api}?unreadOnly=${unreadOnly.checked}`, { headers: { Accept: 'application/json' } });
if (!res.ok || res.redirected) throw new Error(res.status);
render(await res.json());
} catch {
list.replaceChildren();
status.textContent = t.failed;
}
}
// built with textContent only: message bodies are user input
function render(messages) {
status.textContent = messages.length ? '' : t.empty;
list.replaceChildren(...messages.map(m => {
const li = document.createElement('li');
li.className = 'inbox-item' + (m.isRead ? ' is-read' : '');
const meta = document.createElement('div');
meta.className = 'inbox-meta';
const from = document.createElement('strong');
from.textContent = m.anonymous ? t.anonymous : m.senderUsername;
const time = document.createElement('time');
time.dateTime = m.createdAt;
time.textContent = dateFormat.format(new Date(m.createdAt));
meta.append(from, time);
const body = document.createElement('p');
body.className = 'inbox-body';
body.textContent = m.body;
li.append(meta, body);
if (m.anonymous) {
const agent = document.createElement('p');
agent.className = 'inbox-agent';
agent.textContent = m.senderUsername;
li.append(agent);
}
li.append(m.isRead ? readLabel() : markReadButton(m.id, li));
return li;
}));
}
function readLabel() {
const span = document.createElement('span');
span.className = 'inbox-read';
span.textContent = t.read;
return span;
}
function markReadButton(id, li) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'inbox-mark-read';
button.textContent = t.markRead;
button.addEventListener('click', async () => {
button.disabled = true;
const res = await fetch(`${t.api}/${id}/read`, {
method: 'POST',
headers: { RequestVerificationToken: t.token }
});
if (!res.ok) { button.disabled = false; return; }
if (unreadOnly.checked) { li.remove(); if (!list.children.length) status.textContent = t.empty; return; }
li.classList.add('is-read');
button.replaceWith(readLabel());
});
return button;
}
unreadOnly.addEventListener('change', load);
load();
+12
View File
@@ -0,0 +1,12 @@
// forms marked data-once can only be submitted once (no double messages / double registrations)
document.addEventListener('submit', e => {
const form = e.target;
if (!form.matches('form[data-once]')) return;
if (form.dataset.submitted) {
e.preventDefault();
return;
}
form.dataset.submitted = 'true';
// disable after the browser has collected the form data
setTimeout(() => form.querySelectorAll('[type="submit"]').forEach(b => b.disabled = true));
});
+68
View File
@@ -0,0 +1,68 @@
// Gallery slideshow: prev/next, dots, arrow keys, autoplay that pauses on hover/focus.
// The slides are a scroll-snap strip, so swiping on touch screens works natively.
document.querySelectorAll('.slideshow').forEach(show => {
const strip = show.querySelector('.slides');
const slides = [...show.querySelectorAll('.slide')];
const controls = show.querySelector('.slideshow-controls');
if (!strip || slides.length < 2) return;
const dots = [...controls.querySelectorAll('.slide-dots button')];
const toggle = controls.querySelector('.slide-toggle');
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const intervalMs = 5000;
let current = 0;
let playing = !reducedMotion;
let hovered = false;
let timer = null;
controls.hidden = false;
function goTo(index) {
current = (index + slides.length) % slides.length;
strip.scrollTo({ left: current * strip.clientWidth, behavior: reducedMotion ? 'auto' : 'smooth' });
update();
}
function update() {
dots.forEach((d, i) => d.setAttribute('aria-current', i === current ? 'true' : 'false'));
toggle.textContent = playing ? '❚❚' : '▶';
toggle.setAttribute('aria-label', playing ? toggle.dataset.pause : toggle.dataset.play);
strip.setAttribute('aria-live', playing ? 'off' : 'polite');
}
function schedule() {
clearInterval(timer);
if (playing && !hovered) timer = setInterval(() => goTo(current + 1), intervalMs);
}
controls.querySelector('.slide-prev').addEventListener('click', () => { goTo(current - 1); schedule(); });
controls.querySelector('.slide-next').addEventListener('click', () => { goTo(current + 1); schedule(); });
dots.forEach((d, i) => d.addEventListener('click', () => { goTo(i); schedule(); }));
toggle.addEventListener('click', () => { playing = !playing; update(); schedule(); });
show.addEventListener('keydown', e => {
if (e.key === 'ArrowLeft') { goTo(current - 1); schedule(); }
if (e.key === 'ArrowRight') { goTo(current + 1); schedule(); }
});
// pause while the pointer or keyboard focus is inside
show.addEventListener('pointerenter', () => { hovered = true; schedule(); });
show.addEventListener('pointerleave', () => { hovered = false; schedule(); });
show.addEventListener('focusin', () => { hovered = true; schedule(); });
show.addEventListener('focusout', e => { if (!show.contains(e.relatedTarget)) { hovered = false; schedule(); } });
// keep the dots in sync when the user swipes or scrolls the strip
let scrollEnd;
strip.addEventListener('scroll', () => {
clearTimeout(scrollEnd);
scrollEnd = setTimeout(() => {
current = Math.round(strip.scrollLeft / strip.clientWidth);
update();
}, 100);
});
addEventListener('resize', () => strip.scrollTo({ left: current * strip.clientWidth }));
update();
schedule();
});
+88
View File
@@ -0,0 +1,88 @@
.auth-forms {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 1.5rem;
}
.auth-card {
--surface: #fff;
--text: #0f172a;
--muted: #64748b;
--border: #cbd5e1;
--accent: #2563eb;
display: flex;
flex-direction: column;
gap: 0.9rem;
box-sizing: border-box;
width: min(22rem, calc(100vw - 2rem));
padding: 1.75rem;
border-radius: 1rem;
background: var(--surface);
color: var(--text);
box-shadow: 0 20px 50px rgb(0 0 0 / 0.2);
font-family: system-ui, sans-serif;
}
.auth-card h1 {
margin: 0;
font-size: 1.35rem;
}
.auth-card label {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-weight: 600;
font-size: 0.95rem;
}
.auth-card input {
padding: 0.65rem 0.8rem;
border: 1px solid var(--border);
border-radius: 0.6rem;
background: var(--surface);
color: var(--text);
font: inherit;
font-weight: 400;
}
.auth-card input:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px rgb(37 99 235 / 0.2);
}
.auth-card .hint {
margin: -0.4rem 0 0;
color: var(--muted);
font-size: 0.85rem;
}
.auth-card button {
padding: 0.7rem 1.2rem;
border: none;
border-radius: 999px;
background: var(--accent);
color: #fff;
font: 600 1rem/1.2 system-ui, sans-serif;
cursor: pointer;
}
.auth-card button:disabled { opacity: 0.6; cursor: wait; }
.auth-card button:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 2px;
}
@media (prefers-color-scheme: dark) {
.auth-card {
--surface: #0f172a;
--text: #e2e8f0;
--muted: #94a3b8;
--border: #334155;
--accent: #3b82f6;
}
}
+136
View File
@@ -0,0 +1,136 @@
.slideshow {
--frame: #0f172a;
--control-bg: #fff;
--control-text: #0f172a;
--dot: rgb(15 23 42 / 0.3);
--dot-active: #2563eb;
box-sizing: border-box;
width: min(60rem, calc(100vw - 2rem));
font-family: system-ui, sans-serif;
}
.slideshow h1 {
margin: 0 0 1rem;
text-align: center;
}
/* scroll-snap strip: works without JS and gives native swipe */
.slides {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scrollbar-width: none;
border-radius: 1rem;
background: var(--frame);
box-shadow: 0 20px 50px rgb(0 0 0 / 0.3);
}
.slides::-webkit-scrollbar { display: none; }
.slides:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 3px;
}
.slide {
flex: 0 0 100%;
margin: 0;
scroll-snap-align: center;
display: grid;
place-items: center;
}
.slide img {
display: block;
width: 100%;
height: min(70vh, 40rem);
object-fit: contain;
}
.slideshow-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
margin-top: 1rem;
}
.slideshow-controls[hidden] { display: none; }
.slide-prev,
.slide-next,
.slide-toggle {
display: grid;
place-items: center;
width: 2.75rem;
height: 2.75rem;
border: none;
border-radius: 50%;
background: var(--control-bg);
color: var(--control-text);
font: 700 1.4rem/1 system-ui, sans-serif;
cursor: pointer;
box-shadow: 0 2px 8px rgb(0 0 0 / 0.15);
transition: transform 0.15s ease;
}
.slide-toggle { font-size: 0.9rem; }
.slide-prev:hover,
.slide-next:hover,
.slide-toggle:hover { transform: scale(1.08); }
.slide-dots {
display: flex;
gap: 0.25rem;
}
/* 1.5rem hit area around a small visible dot */
.slide-dots button {
width: 1.5rem;
height: 1.5rem;
padding: 0;
border: none;
background: transparent;
cursor: pointer;
}
.slide-dots button::before {
content: "";
display: block;
width: 0.65rem;
height: 0.65rem;
margin: auto;
border-radius: 50%;
background: var(--dot);
transition: background-color 0.2s ease, transform 0.2s ease;
}
.slide-dots button[aria-current="true"]::before {
background: var(--dot-active);
transform: scale(1.3);
}
.slideshow-controls button:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 2px;
}
@media (prefers-color-scheme: dark) {
.slideshow {
--control-bg: #1e293b;
--control-text: #e2e8f0;
--dot: rgb(226 232 240 / 0.35);
--dot-active: #60a5fa;
}
}
@media (prefers-reduced-motion: reduce) {
.slide-prev, .slide-next, .slide-toggle,
.slide-dots button::before { transition: none; }
}
@media (max-width: 480px) {
.slide img { height: 55vh; }
}
+123
View File
@@ -0,0 +1,123 @@
.inbox {
--surface: #fff;
--text: #0f172a;
--muted: #64748b;
--border: #e2e8f0;
--accent: #2563eb;
--unread: #2563eb;
box-sizing: border-box;
width: min(44rem, calc(100vw - 2rem));
font-family: system-ui, sans-serif;
color: var(--text);
}
.inbox-header {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.5rem 1rem;
}
.inbox-header h1 { margin: 0; }
.inbox-header label {
display: inline-flex;
align-items: center;
gap: 0.4rem;
cursor: pointer;
}
.inbox-header input { accent-color: var(--accent); }
.inbox-status:empty { display: none; }
.inbox-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin: 1rem 0 0;
padding: 0;
list-style: none;
}
.inbox-item {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 1rem 1.25rem;
border-left: 4px solid var(--unread);
border-radius: 0.75rem;
background: var(--surface);
box-shadow: 0 2px 10px rgb(0 0 0 / 0.08);
}
.inbox-item.is-read {
border-left-color: var(--border);
opacity: 0.8;
}
.inbox-meta {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 0.25rem 1rem;
}
.inbox-meta strong { overflow-wrap: anywhere; }
.inbox-meta time {
color: var(--muted);
font-size: 0.9rem;
font-variant-numeric: tabular-nums;
}
.inbox-body {
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: 1.5;
}
.inbox-agent {
margin: 0;
color: var(--muted);
font-size: 0.8rem;
overflow-wrap: anywhere;
}
.inbox-mark-read {
align-self: flex-end;
padding: 0.5rem 1rem;
border: none;
border-radius: 999px;
background: var(--accent);
color: #fff;
font: 600 0.9rem/1.2 system-ui, sans-serif;
cursor: pointer;
}
.inbox-mark-read:disabled { opacity: 0.6; cursor: wait; }
.inbox-mark-read:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 2px;
}
.inbox-read {
align-self: flex-end;
color: var(--muted);
font-size: 0.9rem;
}
@media (prefers-color-scheme: dark) {
.inbox {
--surface: #0f172a;
--text: #e2e8f0;
--muted: #94a3b8;
--border: #334155;
--accent: #3b82f6;
--unread: #60a5fa;
}
}
+73 -6
View File
@@ -1,12 +1,12 @@
html, body{
html {
background-color: lightgreen;
}
body {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
}
body {
margin: 0;
font-family: system-ui, sans-serif;
}
@@ -16,9 +16,17 @@ main {
display: flex;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
max-width: 100%;
padding: 2rem 1rem;
}
/* photos never wider than the screen (the profile photo has width="600") */
img {
max-width: 100%;
height: auto;
}
/* Navbar */
.site-header {
--nav-bg: rgb(255 255 255 / 0.75);
@@ -43,6 +51,13 @@ main {
box-shadow: 0 1px 0 rgb(15 23 42 / 0.1), 0 4px 16px rgb(15 23 42 / 0.06);
}
.header-end {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.25rem 0.75rem;
}
.main-nav,
.lang-switch {
display: flex;
@@ -75,11 +90,62 @@ main {
color: var(--nav-active-text);
}
.site-header a:focus-visible {
.site-header a:focus-visible,
.logout-form button:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 2px;
}
.logout-form {
display: flex;
align-items: center;
gap: 0.25rem;
margin: 0;
}
.user-name {
max-width: 14rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--nav-muted);
font-size: 0.9rem;
}
.logout-form button {
padding: 0.45rem 0.9rem;
border: none;
border-radius: 999px;
background: transparent;
color: var(--nav-text);
font: 600 1rem/1.2 system-ui, sans-serif;
cursor: pointer;
transition: background-color 0.15s ease;
}
.logout-form button:hover {
background: var(--nav-hover);
}
/* one-line notice under the header (message sent, login failed, ...) */
.flash {
--flash-bg: #e0f2fe;
--flash-text: #075985;
box-sizing: border-box;
width: min(40rem, calc(100% - 2rem));
margin: 1rem 0 0;
padding: 0.75rem 1rem;
border-radius: 0.75rem;
background: var(--flash-bg);
color: var(--flash-text);
font-weight: 600;
text-align: center;
}
.flash-success { --flash-bg: #dcfce7; --flash-text: #166534; }
.flash-error { --flash-bg: #fee2e2; --flash-text: #991b1b; }
#message-me-btn {
--btn-bg: #2563eb;
--btn-bg-hover: #1d4ed8;
@@ -140,5 +206,6 @@ main {
@media (prefers-reduced-motion: reduce) {
#message-me-btn,
.site-header a { transition: none; }
.site-header a,
.logout-form button { transition: none; }
}