diff --git a/Controllers/PrivateMessageController.cs b/Controllers/PrivateMessageController.cs index 9adad0c..c1f77ec 100644 --- a/Controllers/PrivateMessageController.cs +++ b/Controllers/PrivateMessageController.cs @@ -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 logger) : Controller +public class PrivateMessageController( + MessageService messagesService, + IStringLocalizer strings, + ILogger logger) : Controller { + //form post from _MessageMe, redirects back to the page it came from [HttpPost("send")] [EnableRateLimiting("contact")] - - public async Task Send([FromForm] SendPrivateMessageRequest req, string? returnUrl) + [ValidateAntiForgeryToken] + public async Task 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 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 MarkRead(int id) => + await messagesService.MarkReadAsync(id) == 0 ? NotFound() : NoContent(); +} diff --git a/Data/DbSeeder.cs b/Data/DbSeeder.cs new file mode 100644 index 0000000..a16bb86 --- /dev/null +++ b/Data/DbSeeder.cs @@ -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().Database.MigrateAsync(); + + var roles = sp.GetRequiredService>(); + 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>(); + 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); +} diff --git a/Data/PrivateMessage.cs b/Data/PrivateMessage.cs index 60f0fbe..3a32457 100644 --- a/Data/PrivateMessage.cs +++ b/Data/PrivateMessage.cs @@ -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; diff --git a/LanguagesValues/StringValues.en.resx b/LanguagesValues/StringValues.en.resx index 5b2c00c..a7263b7 100644 --- a/LanguagesValues/StringValues.en.resx +++ b/LanguagesValues/StringValues.en.resx @@ -13,7 +13,7 @@ Login - Greetings! + Hello, {0}! Stati Kosev @@ -21,4 +21,121 @@ Send me a DM. + + Home + + + Navigation + + + Here you'll find my projects, an art gallery and a way to get in touch. + + + Photo of Stati Kosev + + + guest + + + Gallery + + + The gallery is empty. + + + Previous + + + Next + + + Pause + + + Play + + + Image {0} + + + {0} of {1} + + + Message form + + + Sending as + + + Send anonymously + + + You are not logged in + + + Cancel the message + + + Send + + + Cancel + + + Your message + + + Sent, thank you! + + + The message must be between 1 and 2000 characters. + + + Please wait a moment before sending another message. + + + Messages + + + Unread only + + + Mark as read + + + Read + + + No messages. + + + Could not load the messages. + + + Loading… + + + Anonymous + + + Register + + + Email + + + Password + + + Log out + + + At least 8 characters, with an uppercase letter, a lowercase letter and a digit. + + + Wrong email or password. + + + Registration failed. The email may already be taken, or the password is too weak. + \ No newline at end of file diff --git a/LanguagesValues/StringValues.resx b/LanguagesValues/StringValues.resx index e373c08..a0b6b49 100644 --- a/LanguagesValues/StringValues.resx +++ b/LanguagesValues/StringValues.resx @@ -13,7 +13,7 @@ Вход - Здравейте! + Здравейте, {0}! Стати Косев @@ -48,4 +48,94 @@ Вашето съобщение + + Начало + + + Навигация + + + Тук ще намерите моите проекти, галерия с творби и начин да се свържете с мен. + + + Снимка на Стати Косев + + + гост + + + Галерията е празна. + + + Предишна + + + Следваща + + + Пауза + + + Пусни + + + Снимка {0} + + + {0} от {1} + + + Изпратено, благодаря! + + + Съобщението трябва да е между 1 и 2000 символа. + + + Изчакайте малко, преди да изпратите следващо съобщение. + + + Съобщения + + + Само непрочетени + + + Отбележи като прочетено + + + Прочетено + + + Няма съобщения. + + + Съобщенията не можаха да се заредят. + + + Зареждане… + + + Анонимно + + + Регистрация + + + Имейл + + + Парола + + + Изход + + + Поне 8 символа, с главна буква, малка буква и цифра. + + + Грешен имейл или парола. + + + Регистрацията не бе успешна. Имейлът може вече да е зает или паролата е твърде слаба. + \ No newline at end of file diff --git a/Migrations/20261028091601_Initial.Designer.cs b/Migrations/20261028091601_Initial.Designer.cs new file mode 100644 index 0000000..616153f --- /dev/null +++ b/Migrations/20261028091601_Initial.Designer.cs @@ -0,0 +1,317 @@ +// +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 + { + /// + 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("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("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", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("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", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("StatiKosev.Data.PrivateMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Anonymous") + .HasColumnType("boolean"); + + b.Property("Body") + .IsRequired() + .HasMaxLength(3000) + .HasColumnType("character varying(3000)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("SenderId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("SenderUsername") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.ToTable("PrivateMessages"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", 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", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20261028091601_Initial.cs b/Migrations/20261028091601_Initial.cs new file mode 100644 index 0000000..cadd019 --- /dev/null +++ b/Migrations/20261028091601_Initial.cs @@ -0,0 +1,244 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace StatiKosev.Migrations +{ + /// + public partial class Initial : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "text", nullable: false), + Name = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "text", nullable: false), + UserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Email = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "boolean", nullable: false), + PasswordHash = table.Column(type: "text", nullable: true), + SecurityStamp = table.Column(type: "text", nullable: true), + ConcurrencyStamp = table.Column(type: "text", nullable: true), + PhoneNumber = table.Column(type: "text", nullable: true), + PhoneNumberConfirmed = table.Column(type: "boolean", nullable: false), + TwoFactorEnabled = table.Column(type: "boolean", nullable: false), + LockoutEnd = table.Column(type: "timestamp with time zone", nullable: true), + LockoutEnabled = table.Column(type: "boolean", nullable: false), + AccessFailedCount = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "PrivateMessages", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Anonymous = table.Column(type: "boolean", nullable: false), + SenderId = table.Column(type: "character varying(450)", maxLength: 450, nullable: true), + SenderUsername = table.Column(type: "character varying(512)", maxLength: 512, nullable: false), + Body = table.Column(type: "character varying(3000)", maxLength: 3000, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + IsRead = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PrivateMessages", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RoleId = table.Column(type: "text", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(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(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + UserId = table.Column(type: "text", nullable: false), + ClaimType = table.Column(type: "text", nullable: true), + ClaimValue = table.Column(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(type: "character varying(128)", maxLength: 128, nullable: false), + ProviderKey = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + ProviderDisplayName = table.Column(type: "text", nullable: true), + UserId = table.Column(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(type: "text", nullable: false), + RoleId = table.Column(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(type: "text", nullable: false), + LoginProvider = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Name = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Value = table.Column(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); + } + + /// + 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"); + } + } +} diff --git a/Migrations/AppDbContextModelSnapshot.cs b/Migrations/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000..d499470 --- /dev/null +++ b/Migrations/AppDbContextModelSnapshot.cs @@ -0,0 +1,314 @@ +// +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("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("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", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("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", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("StatiKosev.Data.PrivateMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Anonymous") + .HasColumnType("boolean"); + + b.Property("Body") + .IsRequired() + .HasMaxLength(3000) + .HasColumnType("character varying(3000)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("SenderId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("SenderUsername") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.ToTable("PrivateMessages"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", 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", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Pages/Gallery.cshtml b/Pages/Gallery.cshtml index 99c6891..4bba386 100644 --- a/Pages/Gallery.cshtml +++ b/Pages/Gallery.cshtml @@ -1,21 +1,48 @@ @page @model StatiKosev.Pages.Gallery - @{ - Layout = null; + ViewData["Title"] = StringValues["Gallery"]; +} +@section Head { + } - +
+

@StringValues["Gallery"]

- - - - @StringValues["Gallery"] - - - -
- -
- - \ No newline at end of file + @if (Model.Images.Count == 0) + { +

@StringValues["GalleryEmpty"]

+ } + else + { + @* without JavaScript this is a swipeable scroll-snap strip; slideshow.js adds the buttons and autoplay *@ +
+ @for (var i = 0; i < Model.Images.Count; i++) + { +
+ @StringValues[ +
+ } +
+ + + } +
+ +@section Scripts { + +} diff --git a/Pages/Gallery.cshtml.cs b/Pages/Gallery.cshtml.cs index ce7cb89..2edc554 100644 --- a/Pages/Gallery.cshtml.cs +++ b/Pages/Gallery.cshtml.cs @@ -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 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(); } -} \ No newline at end of file +} diff --git a/Pages/Inbox.cshtml b/Pages/Inbox.cshtml new file mode 100644 index 0000000..67b8b9b --- /dev/null +++ b/Pages/Inbox.cshtml @@ -0,0 +1,30 @@ +@page +@model StatiKosev.Pages.InboxModel +@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery +@{ + ViewData["Title"] = StringValues["Messages"]; +} +@section Head { + +} + +@* messages are loaded as JSON from PrivateMessageController by inbox.js *@ +
+
+

@StringValues["Messages"]

+ +
+

@StringValues["Loading"]

+
    +
    + +@section Scripts { + +} diff --git a/Pages/Inbox.cshtml.cs b/Pages/Inbox.cshtml.cs new file mode 100644 index 0000000..26969ce --- /dev/null +++ b/Pages/Inbox.cshtml.cs @@ -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() + { + } +} diff --git a/Pages/Login.cshtml b/Pages/Login.cshtml new file mode 100644 index 0000000..4626753 --- /dev/null +++ b/Pages/Login.cshtml @@ -0,0 +1,36 @@ +@page +@model StatiKosev.Pages.LoginModel +@{ + ViewData["Title"] = StringValues["Login"]; +} +@section Head { + +} + +
    +
    +

    @StringValues["Login"]

    + + + + +
    + +
    +

    @StringValues["Register"]

    + + + +

    @StringValues["PasswordHint"]

    + +
    +
    diff --git a/Pages/Login.cshtml.cs b/Pages/Login.cshtml.cs new file mode 100644 index 0000000..48a8b35 --- /dev/null +++ b/Pages/Login.cshtml.cs @@ -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 = "/"; + } +} diff --git a/Pages/Shared/_Layout.cshtml b/Pages/Shared/_Layout.cshtml index db59427..ab85ff6 100644 --- a/Pages/Shared/_Layout.cshtml +++ b/Pages/Shared/_Layout.cshtml @@ -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"); } @@ -11,23 +22,48 @@ - @StringValues["Title"] + @(ViewData["Title"] ?? StringValues["Title"]) + @await RenderSectionAsync("Head", required: false) +@if (status is not null) +{ +

    @status

    +} +
    @RenderBody()
    + + +@await RenderSectionAsync("Scripts", required: false) diff --git a/Program.cs b/Program.cs index 1c792bf..c62d2f5 100644 --- a/Program.cs +++ b/Program.cs @@ -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() .AddEntityFrameworkStores(); + 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 { ["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); }); diff --git a/StatiKosev.csproj b/StatiKosev.csproj index 8e6b145..2366ecf 100644 --- a/StatiKosev.csproj +++ b/StatiKosev.csproj @@ -8,7 +8,6 @@ - diff --git a/appsettings.json b/appsettings.json index 5e23edd..a41ab34 100644 --- a/appsettings.json +++ b/appsettings.json @@ -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": "" } \ No newline at end of file diff --git a/dotnet-tools.json b/dotnet-tools.json new file mode 100644 index 0000000..807729e --- /dev/null +++ b/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "10.0.9", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/wwwroot/scripts/inbox.js b/wwwroot/scripts/inbox.js new file mode 100644 index 0000000..8f3ac5e --- /dev/null +++ b/wwwroot/scripts/inbox.js @@ -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(); diff --git a/wwwroot/scripts/site.js b/wwwroot/scripts/site.js new file mode 100644 index 0000000..174dc36 --- /dev/null +++ b/wwwroot/scripts/site.js @@ -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)); +}); diff --git a/wwwroot/scripts/slideshow.js b/wwwroot/scripts/slideshow.js new file mode 100644 index 0000000..60869af --- /dev/null +++ b/wwwroot/scripts/slideshow.js @@ -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(); +}); diff --git a/wwwroot/styles/account.css b/wwwroot/styles/account.css new file mode 100644 index 0000000..127982a --- /dev/null +++ b/wwwroot/styles/account.css @@ -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; + } +} diff --git a/wwwroot/styles/gallery.css b/wwwroot/styles/gallery.css new file mode 100644 index 0000000..2257391 --- /dev/null +++ b/wwwroot/styles/gallery.css @@ -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; } +} diff --git a/wwwroot/styles/inbox.css b/wwwroot/styles/inbox.css new file mode 100644 index 0000000..af79bf1 --- /dev/null +++ b/wwwroot/styles/inbox.css @@ -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; + } +} diff --git a/wwwroot/styles/site.css b/wwwroot/styles/site.css index 8fa41a5..806a1a0 100644 --- a/wwwroot/styles/site.css +++ b/wwwroot/styles/site.css @@ -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; } } \ No newline at end of file