diff --git a/SharpbinV3.Client/src/routes/verify-email/+page.server.ts b/SharpbinV3.Client/src/routes/verify-email/+page.server.ts new file mode 100644 index 0000000..00df9d3 --- /dev/null +++ b/SharpbinV3.Client/src/routes/verify-email/+page.server.ts @@ -0,0 +1,15 @@ +import { apiUrl } from '$lib/server/api'; +import { extractError } from '$lib/utils/misc'; +import { error } from '@sveltejs/kit'; + +export const load = async ({ url }) => { + const token = url.searchParams.get('token'); + if (token) { + const res = await fetch(`${apiUrl}/api/auth/verify-email?token=${token}`); + if (!res.ok) { + const json = await res.json().catch(); + const message = extractError(json); + throw error(res.status, message ?? 'Request failed'); + } + } +}; diff --git a/SharpbinV3.Client/src/routes/verify-email/+page.svelte b/SharpbinV3.Client/src/routes/verify-email/+page.svelte new file mode 100644 index 0000000..51d3f75 --- /dev/null +++ b/SharpbinV3.Client/src/routes/verify-email/+page.svelte @@ -0,0 +1,11 @@ +
+
+

Email verified.

+

You may close this page.

+
+
diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index 4babbf9..7623c69 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -27,6 +27,7 @@ namespace SharpbinV3.Server.Controllers IOptions options, VerificationService verification, TotpVerificationProvider totp, + EmailService email, AppDbContext db ) : ControllerBase { @@ -35,6 +36,7 @@ namespace SharpbinV3.Server.Controllers private readonly ApiKeyService _apiKeyService = apiKeyService; private readonly VerificationService _verification = verification; private readonly TotpVerificationProvider _totp = totp; + private readonly EmailService _email = email; private readonly AppDbContext _db = db; [HttpPost] @@ -62,6 +64,9 @@ namespace SharpbinV3.Server.Controllers return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." }); var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName); + if (!string.IsNullOrWhiteSpace(user.Email)) + await _authService.SendEmailVerification(user); + return Ok( new { @@ -322,5 +327,16 @@ namespace SharpbinV3.Server.Controllers return Ok(new { success = true, message = "API key deleted." }); } + + [HttpGet] + [Route("verify-email")] + public async Task VerifyEmail(string token) + { + (bool verifiedEmail, string message) = await _authService.VerifyEmailVerificationToken(token); + if (verifiedEmail) + return Ok(new { success = true, message }); + else + return BadRequest(new { success = false, message }); + } } } diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index cda8ab4..0ce276b 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -63,7 +63,6 @@ namespace SharpbinV3.Server.Controllers [EnableRateLimiting("Strict")] public async Task UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser) { - Console.WriteLine($"{ModelState.IsValid}"); if (!ModelState.IsValid) return BadRequest(ModelState); @@ -389,6 +388,7 @@ namespace SharpbinV3.Server.Controllers CreatedAt = user.CreatedAt, DisplayName = user.DisplayName, Email = user.Email, + EmailVerified = user.EmailVerified, LastLogin = user.LastLogin, Roles = user.Roles, Visibility = user.Visibility, diff --git a/SharpbinV3.Server/DTOs/User/UserResponseDto.cs b/SharpbinV3.Server/DTOs/User/UserResponseDto.cs index 459ab64..4fa50cb 100644 --- a/SharpbinV3.Server/DTOs/User/UserResponseDto.cs +++ b/SharpbinV3.Server/DTOs/User/UserResponseDto.cs @@ -14,6 +14,7 @@ namespace SharpbinV3.Server.DTOs.User public class UserResponseDto : UserSimpleDto { public string? Email { get; set; } + public bool EmailVerified { get; set; } = false; public long? LastLogin { get; set; } } } diff --git a/SharpbinV3.Server/Data/AppDbContext.cs b/SharpbinV3.Server/Data/AppDbContext.cs index 5288106..fa4837a 100644 --- a/SharpbinV3.Server/Data/AppDbContext.cs +++ b/SharpbinV3.Server/Data/AppDbContext.cs @@ -12,6 +12,7 @@ namespace SharpbinV3.Server.Data public DbSet UserTotps => Set(); public DbSet Reports => Set(); public DbSet ApiKeys => Set(); + public DbSet EmailVerificationTokens => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -63,6 +64,12 @@ namespace SharpbinV3.Server.Data .WithMany(u => u.ApiKeys) .HasForeignKey(a => a.UserUUID) .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasOne(a => a.User) + .WithMany(u => u.EmailVerificationTokens) + .HasForeignKey(a => a.UserUUID) + .OnDelete(DeleteBehavior.Cascade); } } } diff --git a/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs b/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs new file mode 100644 index 0000000..d6d9422 --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs @@ -0,0 +1,25 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Data.Entities +{ + public enum EmailTokenType + { + VerifyEmail, + ResetPassword, + ChangeEmail, + DeleteAccount, + } + + public sealed class EmailVerificationToken + { + [Key] + public Guid UUID { get; set; } = Guid.CreateVersion7(); + public required Guid UserUUID { get; set; } + public User User { get; set; } = null!; + public required string TokenHash { get; set; } + public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + public long ExpiresAt { get; set; } + public required EmailTokenType Type { get; set; } + public bool Used { get; set; } = false; + } +} diff --git a/SharpbinV3.Server/Data/Entities/User.cs b/SharpbinV3.Server/Data/Entities/User.cs index 0bae13b..e0b108c 100644 --- a/SharpbinV3.Server/Data/Entities/User.cs +++ b/SharpbinV3.Server/Data/Entities/User.cs @@ -15,6 +15,8 @@ namespace SharpbinV3.Server.Data.Entities public required string PasswordHash { get; set; } public string? Email { get; set; } + public bool EmailVerified { get; set; } = false; + public string? DisplayName { get; set; } public long? LastLogin { get; set; } @@ -24,6 +26,7 @@ namespace SharpbinV3.Server.Data.Entities public List RefreshTokens { get; set; } = []; public List Reports { get; set; } = []; public List ApiKeys { get; set; } = []; + public List EmailVerificationTokens { get; set; } = []; public UserTotp? Totp { get; set; } } } diff --git a/SharpbinV3.Server/Migrations/20260221080317_EmailVerificationToken.Designer.cs b/SharpbinV3.Server/Migrations/20260221080317_EmailVerificationToken.Designer.cs new file mode 100644 index 0000000..48b14be --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260221080317_EmailVerificationToken.Designer.cs @@ -0,0 +1,453 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SharpbinV3.Server.Data; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260221080317_EmailVerificationToken")] + partial class EmailVerificationToken + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("TrueSize") + .HasColumnType("INTEGER"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("PID"); + + b.HasIndex("AuthorUUID"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("ID") + .IsUnique(); + + b.HasIndex("PID") + .IsUnique(); + + b.HasIndex("Size"); + + b.HasIndex("Syntax"); + + b.HasIndex("UUID") + .IsUnique(); + + b.HasIndex("Views"); + + b.HasIndex("Visibility"); + + b.ToTable("Pastes"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserUUID"); + + b.ToTable("RefreshTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Roles") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("UUID"); + + b.HasIndex("UID"); + + b.HasIndex("UUID") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EncryptedSecret") + .IsRequired() + .HasColumnType("BLOB"); + + b.HasKey("UserUUID"); + + b.ToTable("UserTotps"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("ApiKeys") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("EmailVerificationTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Pastes") + .HasForeignKey("AuthorUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithOne("Totp") + .HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("PasteViews"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("ApiKeys"); + + b.Navigation("EmailVerificationTokens"); + + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Reports"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260221080317_EmailVerificationToken.cs b/SharpbinV3.Server/Migrations/20260221080317_EmailVerificationToken.cs new file mode 100644 index 0000000..378ca2f --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260221080317_EmailVerificationToken.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class EmailVerificationToken : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "EmailVerified", + table: "Users", + type: "INTEGER", + nullable: false, + defaultValue: false); + + migrationBuilder.CreateTable( + name: "EmailVerificationTokens", + columns: table => new + { + UUID = table.Column(type: "TEXT", nullable: false), + UserUUID = table.Column(type: "TEXT", nullable: false), + TokenHash = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + ExpiresAt = table.Column(type: "INTEGER", nullable: false), + Type = table.Column(type: "INTEGER", nullable: false), + Used = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_EmailVerificationTokens", x => x.UUID); + table.ForeignKey( + name: "FK_EmailVerificationTokens_Users_UserUUID", + column: x => x.UserUUID, + principalTable: "Users", + principalColumn: "UUID", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_EmailVerificationTokens_UserUUID", + table: "EmailVerificationTokens", + column: "UserUUID"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "EmailVerificationTokens"); + + migrationBuilder.DropColumn( + name: "EmailVerified", + table: "Users"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs index eb27212..f0796c9 100644 --- a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs @@ -47,6 +47,38 @@ namespace SharpbinV3.Server.Migrations b.ToTable("ApiKeys"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { b.Property("PID") @@ -258,6 +290,9 @@ namespace SharpbinV3.Server.Migrations b.Property("Email") .HasColumnType("TEXT"); + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + b.Property("LastLogin") .HasColumnType("INTEGER"); @@ -317,6 +352,17 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("EmailVerificationTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") @@ -388,6 +434,8 @@ namespace SharpbinV3.Server.Migrations { b.Navigation("ApiKeys"); + b.Navigation("EmailVerificationTokens"); + b.Navigation("Pastes"); b.Navigation("RefreshTokens"); diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index 8ec6ec9..8bd6bf7 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -70,6 +70,7 @@ namespace SharpbinV3.Server builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -92,7 +93,9 @@ namespace SharpbinV3.Server .Bind(builder.Configuration.GetSection("JwtSettings")) .ValidateDataAnnotations() .ValidateOnStart(); - builder.Services.Configure(builder.Configuration.GetSection("AuthSettings")); + builder.Services.AddOptions().Bind(builder.Configuration).ValidateDataAnnotations().ValidateOnStart(); + builder.Services.AddOptions().Bind(builder.Configuration.GetSection("AuthSettings")).ValidateDataAnnotations(); + builder.Services.AddOptions().Bind(builder.Configuration.GetSection("EmailSettings")).ValidateDataAnnotations(); builder .Services.AddAuthentication(options => diff --git a/SharpbinV3.Server/Services/AuthService.cs b/SharpbinV3.Server/Services/AuthService.cs index 4a43255..7ddff65 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -1,4 +1,5 @@ -using System.IdentityModel.Tokens.Jwt; +using System.Data; +using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.EntityFrameworkCore; @@ -25,15 +26,20 @@ namespace SharpbinV3.Server.Services public sealed class AuthService( AppDbContext db, + EmailService email, IOptions jwtOptions, IOptions authOptions, + IOptions appSettings, ILogger logger ) { private readonly AppDbContext _db = db; + private readonly EmailService _email = email; private readonly JWTSettings _jwtSettings = jwtOptions.Value; private readonly AuthSettings _authSettings = authOptions.Value; + private readonly AppSettings _appSettings = appSettings.Value; private readonly ILogger _logger = logger; + private const int EmailVerificationTokenLength = 64; public async Task CreateUser(string username, string password, string? email, string? displayName) { @@ -214,5 +220,57 @@ namespace SharpbinV3.Server.Services var userUUID = Guid.Parse(uuidClaim); return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID); } + + public async Task SendEmailVerification(User user) + { + if (string.IsNullOrWhiteSpace(user.Email)) + return; + + string token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength); + string tokenHash = Utilities.ComputeSha256(token); + + await _email.SendAsync( + user.Email, + "Verify Your Email", + $"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}" + ); + var verificationToken = new EmailVerificationToken + { + TokenHash = tokenHash, + UserUUID = user.UUID, + User = user, + ExpiresAt = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(), + Type = EmailTokenType.VerifyEmail, + }; + await _db.EmailVerificationTokens.AddAsync(verificationToken); + await _db.SaveChangesAsync(); + } + + public async Task<(bool success, string message)> VerifyEmailVerificationToken(string token) + { + if (token.Length != EmailVerificationTokenLength) + return (false, "Invalid token."); + + string tokenHash = Utilities.ComputeSha256(token); + var verificationToken = await _db.EmailVerificationTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.TokenHash == tokenHash); + + if ( + verificationToken == null + || verificationToken.User == null + || verificationToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + || verificationToken.Used + ) + return (false, "Token is expired or already used."); + + if (verificationToken != null && !verificationToken.Used) + { + verificationToken.Used = true; + verificationToken.User.EmailVerified = true; + await _db.SaveChangesAsync(); + } + + await _db.SaveChangesAsync(); + return (true, "Email successfully verified."); + } } } diff --git a/SharpbinV3.Server/Services/EmailService.cs b/SharpbinV3.Server/Services/EmailService.cs new file mode 100644 index 0000000..3c18ee0 --- /dev/null +++ b/SharpbinV3.Server/Services/EmailService.cs @@ -0,0 +1,31 @@ +using MailKit.Net.Smtp; +using MailKit.Security; +using Microsoft.Extensions.Options; +using MimeKit; +using SharpbinV3.Server.Settings; + +namespace SharpbinV3.Server.Services +{ + public class EmailService(IOptions emailSettings) + { + private readonly EmailSettings settings = emailSettings.Value; + + public async Task SendAsync(string to, string subject, string body) + { + var message = new MimeMessage(); + message.From.Add(new MailboxAddress("Sharpbin", settings.From)); + message.To.Add(MailboxAddress.Parse(to)); + message.Subject = subject; + + message.Body = new TextPart("html") { Text = body }; + + using var smtp = new SmtpClient(); + await smtp.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.StartTls); + + await smtp.AuthenticateAsync(settings.User, settings.Password); + + await smtp.SendAsync(message); + await smtp.DisconnectAsync(true); + } + } +} diff --git a/SharpbinV3.Server/Settings/AppSettings.cs b/SharpbinV3.Server/Settings/AppSettings.cs new file mode 100644 index 0000000..176be9b --- /dev/null +++ b/SharpbinV3.Server/Settings/AppSettings.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Settings +{ + public class AppSettings + { + [Required, MaxLength(256)] + public string Domain { get; set; } = string.Empty; + public bool Https { get; set; } = true; + } +} diff --git a/SharpbinV3.Server/Settings/AuthSettings.cs b/SharpbinV3.Server/Settings/AuthSettings.cs index 9246e74..ec57937 100644 --- a/SharpbinV3.Server/Settings/AuthSettings.cs +++ b/SharpbinV3.Server/Settings/AuthSettings.cs @@ -8,5 +8,6 @@ public bool First_User_Admin { get; set; } = true; public bool Admins_Require_2FA { get; set; } = true; public string API_Key_HMAC_Secret { get; set; } = string.Empty; + public string Email_Verification_HMAC_Secret { get; set; } = string.Empty; } } diff --git a/SharpbinV3.Server/Settings/EmailSettings.cs b/SharpbinV3.Server/Settings/EmailSettings.cs new file mode 100644 index 0000000..6945377 --- /dev/null +++ b/SharpbinV3.Server/Settings/EmailSettings.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Settings +{ + public class EmailSettings + { + [MaxLength(256)] + public string Host { get; set; } = string.Empty; + + [Range(1, 65535)] + public int Port { get; set; } = 587; + + [MaxLength(256)] + public string User { get; set; } = string.Empty; + + [MaxLength(256)] + public string Password { get; set; } = string.Empty; + + [EmailAddress] + public string From { get; set; } = string.Empty; + public string Verification_HMAC_Secret { get; set; } = string.Empty; + } +} diff --git a/SharpbinV3.Server/SharpbinV3.Server.csproj b/SharpbinV3.Server/SharpbinV3.Server.csproj index 2a0eada..7996611 100644 --- a/SharpbinV3.Server/SharpbinV3.Server.csproj +++ b/SharpbinV3.Server/SharpbinV3.Server.csproj @@ -14,6 +14,7 @@ + diff --git a/SharpbinV3.Server/appsettings.Development.json b/SharpbinV3.Server/appsettings.Development.json index 86e8d8a..827ef8a 100644 --- a/SharpbinV3.Server/appsettings.Development.json +++ b/SharpbinV3.Server/appsettings.Development.json @@ -1,4 +1,6 @@ { + "Domain": "localhost:5173", + "Https": false, "Logging": { "LogLevel": { "Default": "Information",