diff --git a/SharpbinV3/Controllers/AuthController.cs b/SharpbinV3/Controllers/AuthController.cs new file mode 100644 index 0000000..17e4742 --- /dev/null +++ b/SharpbinV3/Controllers/AuthController.cs @@ -0,0 +1,78 @@ +using Microsoft.AspNetCore.Mvc; +using SharpbinV3.Services; +using SharpbinV3.DTOs; +using Bcrypt = BCrypt.Net.BCrypt; +using SharpbinV3.Data.Entities; +using Microsoft.AspNetCore.RateLimiting; + +namespace SharpbinV3.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class AuthController(IUserService userService, IAuthService authService) : ControllerBase + { + private readonly IAuthService _authService = authService; + private readonly IUserService _userService = userService; + + [HttpPost] + [EnableRateLimiting("Sliding")] + [Route("register")] + public async Task Register([FromBody] RegisterRequest request) + { + var existingUser = await _userService.GetByUsername(request.Username); + if (existingUser != null) + return Conflict(new { message = "Username already exists." }); + + var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName); + return Ok(new + { + message = "User registered successfully.", + user = new + { + user.UID, + user.UUID, + user.Username, + user.Email, + user.DisplayName, + user.Roles + } + } + ); + } + [HttpPost] + [Route("login")] + [EnableRateLimiting("Sliding")] + public async Task Login([FromBody] LoginRequest request) + { + if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) + return BadRequest(new { message = "Username or email is required." }); + + User? user = null; + if (!string.IsNullOrEmpty(request.Username)) + user = await _userService.GetByUsername(request.Username); + if (user == null && !string.IsNullOrEmpty(request.Email)) + user = await _userService.GetByEmail(request.Email); + + if (user == null) return BadRequest(new { message = "Invalid username/email or password." }); + if (!Bcrypt.Verify(request.Password, user.PasswordHash)) + return BadRequest(new { message = "Invalid username/email or password." }); + var token = _authService.GenerateJWTToken(user); + return Ok(new { token }); + } + [HttpPost] + [Route("refresh")] + [EnableRateLimiting("Sliding")] + public async Task RefreshToken([FromBody] RefreshTokenRequest request) + { + try + { + var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken); + return Ok(new { token = jwtResult }); + } + catch (Exception ex) + { + return BadRequest(new { message = ex.Message }); + } + } + } +} diff --git a/SharpbinV3/Controllers/UserController.cs b/SharpbinV3/Controllers/UserController.cs index 508f903..f958eaf 100644 --- a/SharpbinV3/Controllers/UserController.cs +++ b/SharpbinV3/Controllers/UserController.cs @@ -1,5 +1,5 @@ +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using SharpbinV3.DTOs; using SharpbinV3.Services; namespace SharpbinV3.Controllers @@ -10,21 +10,7 @@ namespace SharpbinV3.Controllers { private readonly IUserService _userService = userService; - [HttpPost] - public async Task Create([FromBody] CreateUserDto dto) - { - if (await _userService.GetByUsername(dto.Username) != null) - return Conflict("Username already exists."); - - if (!string.IsNullOrEmpty(dto.Email) && await _userService.GetByEmail(dto.Email) != null) - return Conflict("Email already exists."); - - var user = await _userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.DisplayName); - - return CreatedAtAction(nameof(GetByUid), new { uid = user.UID }, new { user.UID, user.Username, user.UUID }); - } - - [HttpGet("{uid:int}")] + [HttpGet("{uid}")] public async Task GetByUid(int uid) { var user = await _userService.GetByUID(uid); @@ -32,15 +18,16 @@ namespace SharpbinV3.Controllers return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName }); } - [HttpGet("username/{username:string}")] + [HttpGet("username/{username}")] public async Task GetByUsername(string username) { var user = await _userService.GetByUsername(username); if (user == null) return NotFound(); return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName }); } - [HttpGet("uuid/{uuid:guid}")] - public async Task GetByUuid(Guid uuid) + [HttpGet("uuid/{uuid}")] + [Authorize] + public async Task GetByUUID(Guid uuid) { var user = await _userService.GetByUUID(uuid); if (user == null) return NotFound(); diff --git a/SharpbinV3/DTOs/JWTResult.cs b/SharpbinV3/DTOs/JWTResult.cs new file mode 100644 index 0000000..6ca69f5 --- /dev/null +++ b/SharpbinV3/DTOs/JWTResult.cs @@ -0,0 +1,10 @@ +namespace SharpbinV3.DTOs +{ + public class JWTResult + { + public string? Token { get; set; } + public string? RefreshToken { get; set; } + public bool Success { get; set; } + public List? Errors { get; set; } + } +} diff --git a/SharpbinV3/DTOs/LoginRequest.cs b/SharpbinV3/DTOs/LoginRequest.cs new file mode 100644 index 0000000..eb65a66 --- /dev/null +++ b/SharpbinV3/DTOs/LoginRequest.cs @@ -0,0 +1,14 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.DTOs +{ + public class LoginRequest + { + [StringLength(50, MinimumLength = 3)] + public string? Username { get; set; } + [EmailAddress] + public string? Email { get; set; } + [StringLength(128, MinimumLength = 6)] + public string? Password { get; set; } + } +} diff --git a/SharpbinV3/DTOs/RefreshTokenRequest.cs b/SharpbinV3/DTOs/RefreshTokenRequest.cs new file mode 100644 index 0000000..02d5564 --- /dev/null +++ b/SharpbinV3/DTOs/RefreshTokenRequest.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.DTOs +{ + public class RefreshTokenRequest + { + [Required] + public required string Token { get; set; } + [Required] + public required string RefreshToken { get; set; } + } +} diff --git a/SharpbinV3/DTOs/CreateUserDto.cs b/SharpbinV3/DTOs/RegisterRequest.cs similarity index 93% rename from SharpbinV3/DTOs/CreateUserDto.cs rename to SharpbinV3/DTOs/RegisterRequest.cs index 1865ad6..50f611c 100644 --- a/SharpbinV3/DTOs/CreateUserDto.cs +++ b/SharpbinV3/DTOs/RegisterRequest.cs @@ -2,7 +2,7 @@ using System.ComponentModel.DataAnnotations; namespace SharpbinV3.DTOs { - public class CreateUserDto + public class RegisterRequest { [Required] [StringLength(50, MinimumLength = 3)] diff --git a/SharpbinV3/Data/AppDbContext.cs b/SharpbinV3/Data/AppDbContext.cs index a6d14c4..7803fef 100644 --- a/SharpbinV3/Data/AppDbContext.cs +++ b/SharpbinV3/Data/AppDbContext.cs @@ -7,5 +7,6 @@ namespace SharpbinV3.Data { public DbSet Users => Set(); public DbSet Pastes => Set(); + public DbSet RefreshTokens => Set(); } } diff --git a/SharpbinV3/Data/Entities/RefreshToken.cs b/SharpbinV3/Data/Entities/RefreshToken.cs new file mode 100644 index 0000000..805a164 --- /dev/null +++ b/SharpbinV3/Data/Entities/RefreshToken.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Data.Entities +{ + public sealed class RefreshToken + { + [Key] + public Guid UserUUID { get; set; } + public required string Token { get; set; } + public required string JwtId { get; set; } + public required long CreatedAt { get; set; } + public required long ExpiresAt { get; set; } + public bool Used { get; set; } = false; + public User? User { get; set; } + } +} diff --git a/SharpbinV3/Data/Entities/User.cs b/SharpbinV3/Data/Entities/User.cs index 3383b15..b7ca2f5 100644 --- a/SharpbinV3/Data/Entities/User.cs +++ b/SharpbinV3/Data/Entities/User.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ValueGeneration.Internal; using System.ComponentModel.DataAnnotations; namespace SharpbinV3.Data.Entities @@ -16,7 +15,7 @@ namespace SharpbinV3.Data.Entities public string? Email { get; set; } public string? DisplayName { get; set; } public long? LastLogin { get; set; } - public int Type { get; set; } = 0; // 0 = regular user, 1 = moderator, 255 = admin + public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin public int Visiblity { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private public List Pastes { get; set; } = []; } diff --git a/SharpbinV3/Migrations/20251124021817_InitialCreate.Designer.cs b/SharpbinV3/Migrations/20251124021817_InitialCreate.Designer.cs deleted file mode 100644 index ce0df12..0000000 --- a/SharpbinV3/Migrations/20251124021817_InitialCreate.Designer.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using SharpbinV3.Data; - -#nullable disable - -namespace SharpbinV3.Migrations -{ - [DbContext(typeof(AppDbContext))] - [Migration("20251124021817_InitialCreate")] - partial class InitialCreate - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); - - modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b => - { - b.Property("PID") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("AuthorUUID") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("EditedAt") - .HasColumnType("INTEGER"); - - b.Property("ExpiresAt") - .HasColumnType("INTEGER"); - - b.Property("FilePath") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ID") - .HasColumnType("TEXT"); - - b.Property("Size") - .HasColumnType("INTEGER"); - - b.Property("Syntax") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.Property("TrueSize") - .HasColumnType("INTEGER"); - - b.Property("UUID") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("UserUID") - .HasColumnType("INTEGER"); - - b.Property("Views") - .HasColumnType("INTEGER"); - - b.HasKey("PID"); - - b.HasIndex("UserUID"); - - b.ToTable("Pastes"); - }); - - modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => - { - b.Property("UID") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("DisplayName") - .HasColumnType("TEXT"); - - b.Property("Email") - .HasColumnType("TEXT"); - - b.Property("LastLogin") - .HasColumnType("INTEGER"); - - b.Property("PasswordHash") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("UUID") - .HasColumnType("TEXT"); - - b.Property("Username") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("UID"); - - b.ToTable("Users"); - }); - - modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b => - { - b.HasOne("SharpbinV3.Data.Entities.User", "User") - .WithMany("Pastes") - .HasForeignKey("UserUID"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => - { - b.Navigation("Pastes"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/SharpbinV3/Migrations/20251124181150_AddPasteIndexes.Designer.cs b/SharpbinV3/Migrations/20251124181150_AddPasteIndexes.Designer.cs deleted file mode 100644 index 69c22da..0000000 --- a/SharpbinV3/Migrations/20251124181150_AddPasteIndexes.Designer.cs +++ /dev/null @@ -1,143 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using SharpbinV3.Data; - -#nullable disable - -namespace SharpbinV3.Migrations -{ - [DbContext(typeof(AppDbContext))] - [Migration("20251124181150_AddPasteIndexes")] - partial class AddPasteIndexes - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); - - modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b => - { - b.Property("PID") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("AuthorUUID") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("EditedAt") - .HasColumnType("INTEGER"); - - b.Property("ExpiresAt") - .HasColumnType("INTEGER"); - - b.Property("FilePath") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ID") - .HasColumnType("TEXT"); - - b.Property("Size") - .HasColumnType("INTEGER"); - - b.Property("Syntax") - .HasColumnType("TEXT"); - - b.Property("Title") - .HasColumnType("TEXT"); - - b.Property("TrueSize") - .HasColumnType("INTEGER"); - - b.Property("UUID") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("UserUID") - .HasColumnType("INTEGER"); - - b.Property("Views") - .HasColumnType("INTEGER"); - - b.HasKey("PID"); - - b.HasIndex("AuthorUUID"); - - b.HasIndex("ExpiresAt"); - - b.HasIndex("ID") - .IsUnique(); - - b.HasIndex("PID") - .IsUnique(); - - b.HasIndex("UUID") - .IsUnique(); - - b.HasIndex("UserUID"); - - b.HasIndex("Views"); - - b.ToTable("Pastes"); - }); - - modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => - { - b.Property("UID") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER"); - - b.Property("DisplayName") - .HasColumnType("TEXT"); - - b.Property("Email") - .HasColumnType("TEXT"); - - b.Property("LastLogin") - .HasColumnType("INTEGER"); - - b.Property("PasswordHash") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("UUID") - .HasColumnType("TEXT"); - - b.Property("Username") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("UID"); - - b.HasIndex("UID") - .IsUnique(); - - b.HasIndex("UUID") - .IsUnique(); - - b.ToTable("Users"); - }); - - modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b => - { - b.HasOne("SharpbinV3.Data.Entities.User", "User") - .WithMany("Pastes") - .HasForeignKey("UserUID"); - - b.Navigation("User"); - }); - - modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => - { - b.Navigation("Pastes"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/SharpbinV3/Migrations/20251124181150_AddPasteIndexes.cs b/SharpbinV3/Migrations/20251124181150_AddPasteIndexes.cs deleted file mode 100644 index f820753..0000000 --- a/SharpbinV3/Migrations/20251124181150_AddPasteIndexes.cs +++ /dev/null @@ -1,95 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace SharpbinV3.Migrations -{ - /// - public partial class AddPasteIndexes : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateIndex( - name: "IX_Users_UID", - table: "Users", - column: "UID", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Users_UUID", - table: "Users", - column: "UUID", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_AuthorUUID", - table: "Pastes", - column: "AuthorUUID"); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_ExpiresAt", - table: "Pastes", - column: "ExpiresAt"); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_ID", - table: "Pastes", - column: "ID", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_PID", - table: "Pastes", - column: "PID", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_UUID", - table: "Pastes", - column: "UUID", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_Views", - table: "Pastes", - column: "Views"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropIndex( - name: "IX_Users_UID", - table: "Users"); - - migrationBuilder.DropIndex( - name: "IX_Users_UUID", - table: "Users"); - - migrationBuilder.DropIndex( - name: "IX_Pastes_AuthorUUID", - table: "Pastes"); - - migrationBuilder.DropIndex( - name: "IX_Pastes_ExpiresAt", - table: "Pastes"); - - migrationBuilder.DropIndex( - name: "IX_Pastes_ID", - table: "Pastes"); - - migrationBuilder.DropIndex( - name: "IX_Pastes_PID", - table: "Pastes"); - - migrationBuilder.DropIndex( - name: "IX_Pastes_UUID", - table: "Pastes"); - - migrationBuilder.DropIndex( - name: "IX_Pastes_Views", - table: "Pastes"); - } - } -} diff --git a/SharpbinV3/Migrations/20251124184531_AddVisibility.cs b/SharpbinV3/Migrations/20251124184531_AddVisibility.cs deleted file mode 100644 index 65d4fe3..0000000 --- a/SharpbinV3/Migrations/20251124184531_AddVisibility.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace SharpbinV3.Migrations -{ - /// - public partial class AddVisibility : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "Type", - table: "Users", - type: "INTEGER", - nullable: false, - defaultValue: 0); - - migrationBuilder.AddColumn( - name: "Visiblity", - table: "Users", - type: "INTEGER", - nullable: false, - defaultValue: 0); - - migrationBuilder.AddColumn( - name: "Visiblity", - table: "Pastes", - type: "INTEGER", - nullable: false, - defaultValue: 0); - - migrationBuilder.CreateIndex( - name: "IX_Pastes_Visiblity", - table: "Pastes", - column: "Visiblity"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropIndex( - name: "IX_Pastes_Visiblity", - table: "Pastes"); - - migrationBuilder.DropColumn( - name: "Type", - table: "Users"); - - migrationBuilder.DropColumn( - name: "Visiblity", - table: "Users"); - - migrationBuilder.DropColumn( - name: "Visiblity", - table: "Pastes"); - } - } -} diff --git a/SharpbinV3/Migrations/20251124184531_AddVisibility.Designer.cs b/SharpbinV3/Migrations/20251125015039_Init.Designer.cs similarity index 74% rename from SharpbinV3/Migrations/20251124184531_AddVisibility.Designer.cs rename to SharpbinV3/Migrations/20251125015039_Init.Designer.cs index 6484092..85b2370 100644 --- a/SharpbinV3/Migrations/20251124184531_AddVisibility.Designer.cs +++ b/SharpbinV3/Migrations/20251125015039_Init.Designer.cs @@ -11,8 +11,8 @@ using SharpbinV3.Data; namespace SharpbinV3.Migrations { [DbContext(typeof(AppDbContext))] - [Migration("20251124184531_AddVisibility")] - partial class AddVisibility + [Migration("20251125015039_Init")] + partial class Init { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -92,6 +92,39 @@ namespace SharpbinV3.Migrations b.ToTable("Pastes"); }); + modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b => + { + b.Property("UserUUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUID") + .HasColumnType("INTEGER"); + + b.HasKey("UserUUID"); + + b.HasIndex("UserUID"); + + b.ToTable("RefreshTokens"); + }); + modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => { b.Property("UID") @@ -111,8 +144,9 @@ namespace SharpbinV3.Migrations .IsRequired() .HasColumnType("TEXT"); - b.Property("Type") - .HasColumnType("INTEGER"); + b.PrimitiveCollection("Roles") + .IsRequired() + .HasColumnType("TEXT"); b.Property("UUID") .HasColumnType("TEXT"); @@ -144,6 +178,15 @@ namespace SharpbinV3.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Data.Entities.User", "User") + .WithMany() + .HasForeignKey("UserUID"); + + b.Navigation("User"); + }); + modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => { b.Navigation("Pastes"); diff --git a/SharpbinV3/Migrations/20251124021817_InitialCreate.cs b/SharpbinV3/Migrations/20251125015039_Init.cs similarity index 50% rename from SharpbinV3/Migrations/20251124021817_InitialCreate.cs rename to SharpbinV3/Migrations/20251125015039_Init.cs index f09aba0..55f4438 100644 --- a/SharpbinV3/Migrations/20251124021817_InitialCreate.cs +++ b/SharpbinV3/Migrations/20251125015039_Init.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace SharpbinV3.Migrations { /// - public partial class InitialCreate : Migration + public partial class Init : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -22,7 +22,9 @@ namespace SharpbinV3.Migrations PasswordHash = table.Column(type: "TEXT", nullable: false), Email = table.Column(type: "TEXT", nullable: true), DisplayName = table.Column(type: "TEXT", nullable: true), - LastLogin = table.Column(type: "INTEGER", nullable: true) + LastLogin = table.Column(type: "INTEGER", nullable: true), + Roles = table.Column(type: "TEXT", nullable: false), + Visiblity = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -46,6 +48,7 @@ namespace SharpbinV3.Migrations TrueSize = table.Column(type: "INTEGER", nullable: false), Views = table.Column(type: "INTEGER", nullable: false), Syntax = table.Column(type: "TEXT", nullable: true), + Visiblity = table.Column(type: "INTEGER", nullable: false), ExpiresAt = table.Column(type: "INTEGER", nullable: false) }, constraints: table => @@ -58,10 +61,87 @@ namespace SharpbinV3.Migrations principalColumn: "UID"); }); + migrationBuilder.CreateTable( + name: "RefreshTokens", + columns: table => new + { + UserUUID = table.Column(type: "TEXT", nullable: false), + Token = table.Column(type: "TEXT", nullable: false), + JwtId = table.Column(type: "TEXT", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + ExpiresAt = table.Column(type: "INTEGER", nullable: false), + Used = table.Column(type: "INTEGER", nullable: false), + UserUID = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_RefreshTokens", x => x.UserUUID); + table.ForeignKey( + name: "FK_RefreshTokens_Users_UserUID", + column: x => x.UserUID, + principalTable: "Users", + principalColumn: "UID"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_AuthorUUID", + table: "Pastes", + column: "AuthorUUID"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_ExpiresAt", + table: "Pastes", + column: "ExpiresAt"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_ID", + table: "Pastes", + column: "ID", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_PID", + table: "Pastes", + column: "PID", + unique: true); + migrationBuilder.CreateIndex( name: "IX_Pastes_UserUID", table: "Pastes", column: "UserUID"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_UUID", + table: "Pastes", + column: "UUID", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_Views", + table: "Pastes", + column: "Views"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_Visiblity", + table: "Pastes", + column: "Visiblity"); + + migrationBuilder.CreateIndex( + name: "IX_RefreshTokens_UserUID", + table: "RefreshTokens", + column: "UserUID"); + + migrationBuilder.CreateIndex( + name: "IX_Users_UID", + table: "Users", + column: "UID", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Users_UUID", + table: "Users", + column: "UUID", + unique: true); } /// @@ -70,6 +150,9 @@ namespace SharpbinV3.Migrations migrationBuilder.DropTable( name: "Pastes"); + migrationBuilder.DropTable( + name: "RefreshTokens"); + migrationBuilder.DropTable( name: "Users"); } diff --git a/SharpbinV3/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3/Migrations/AppDbContextModelSnapshot.cs index 961d283..e978c49 100644 --- a/SharpbinV3/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3/Migrations/AppDbContextModelSnapshot.cs @@ -89,6 +89,39 @@ namespace SharpbinV3.Migrations b.ToTable("Pastes"); }); + modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b => + { + b.Property("UserUUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUID") + .HasColumnType("INTEGER"); + + b.HasKey("UserUUID"); + + b.HasIndex("UserUID"); + + b.ToTable("RefreshTokens"); + }); + modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => { b.Property("UID") @@ -108,8 +141,9 @@ namespace SharpbinV3.Migrations .IsRequired() .HasColumnType("TEXT"); - b.Property("Type") - .HasColumnType("INTEGER"); + b.PrimitiveCollection("Roles") + .IsRequired() + .HasColumnType("TEXT"); b.Property("UUID") .HasColumnType("TEXT"); @@ -141,6 +175,15 @@ namespace SharpbinV3.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Data.Entities.User", "User") + .WithMany() + .HasForeignKey("UserUID"); + + b.Navigation("User"); + }); + modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => { b.Navigation("Pastes"); diff --git a/SharpbinV3/Program.cs b/SharpbinV3/Program.cs index e2c5df2..2e27276 100644 --- a/SharpbinV3/Program.cs +++ b/SharpbinV3/Program.cs @@ -1,6 +1,11 @@ +using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using SharpbinV3.Data; using SharpbinV3.Services; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using System.Text; namespace SharpbinV3 { @@ -19,9 +24,49 @@ namespace SharpbinV3 { opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")); }); + builder.Services.AddSingleton(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(jwt => + { + var key = Encoding.ASCII.GetBytes(builder.Configuration.GetSection("JwtConfig:Secret").Value ?? string.Empty); + jwt.SaveToken = true; + jwt.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = true, + ValidIssuer = builder.Configuration["JwtConfig:Issuer"], + ValidateAudience = true, + ValidAudience = builder.Configuration["JwtConfig:Audience"], + RequireExpirationTime = true, + ValidateLifetime = true + }; + }); + + builder.Services.AddRateLimiter(options => + { + options.AddSlidingWindowLimiter("Sliding", opt => + { + opt.Window = TimeSpan.FromSeconds(10); + opt.PermitLimit = 10; + opt.QueueLimit = 2; + opt.SegmentsPerWindow = 5; + opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; + }); + + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + }); var app = builder.Build(); + app.UseRateLimiter(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) @@ -31,6 +76,7 @@ namespace SharpbinV3 app.UseHttpsRedirection(); + app.UseAuthentication(); app.UseAuthorization(); diff --git a/SharpbinV3/Services/AuthService.cs b/SharpbinV3/Services/AuthService.cs new file mode 100644 index 0000000..e4e1889 --- /dev/null +++ b/SharpbinV3/Services/AuthService.cs @@ -0,0 +1,160 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using SharpbinV3.Data; +using SharpbinV3.Data.Entities; +using SharpbinV3.DTOs; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using Bcrypt = BCrypt.Net.BCrypt; + +namespace SharpbinV3.Services +{ + public sealed class AuthService(AppDbContext db, IConfiguration configuration) : IAuthService + { + private readonly AppDbContext _db = db; + private readonly IConfiguration _configuration = configuration; + + public async Task CreateUser(string username, string password, string? email, string? displayName) + { + var user = new User + { + Username = username, + PasswordHash = Bcrypt.HashPassword(password), + Email = email, + DisplayName = displayName, + UUID = Guid.CreateVersion7() + }; + + _db.Users.Add(user); + await _db.SaveChangesAsync(); + return user; + } + public async Task GenerateJWTToken(User user) + { + var jwtHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]!); + + var descriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity( + [ + new Claim("UUID", user.UUID.ToString()), + new Claim("Roles", user.Roles != null ? string.Join(",", user.Roles) : "0"), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) + ]), + Issuer = _configuration["JwtConfig:Issuer"], + Audience = _configuration["JwtConfig:Audience"], + Expires = DateTime.UtcNow.AddMinutes(15), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + + var token = jwtHandler.CreateToken(descriptor); + var jwtToken = jwtHandler.WriteToken(token); + + var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.UserUUID == user.UUID); + + if (existingToken != null) + { + existingToken.JwtId = token.Id; + existingToken.Used = false; + existingToken.CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + existingToken.ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(); + existingToken.Token = RandomString(36) + Guid.NewGuid(); + _db.RefreshTokens.Update(existingToken); + } + else + { + var refreshToken = new RefreshToken() + { + JwtId = token.Id, + Used = false, + User = user, + UserUUID = user.UUID, + CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(), + Token = RandomString(36) + Guid.NewGuid() + }; + await _db.RefreshTokens.AddAsync(refreshToken); + } + + await _db.SaveChangesAsync(); + + return new JWTResult() + { + Token = jwtToken, + Success = true, + RefreshToken = existingToken?.Token ?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token + }; + } + + public async Task ValidateJWTToken(string token) + { + var jwtHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]!); + try + { + jwtHandler.ValidateToken(token, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false, + ClockSkew = TimeSpan.Zero + }, out SecurityToken validatedToken); + return true; + } + catch + { + return false; + } + } + + public async Task RefreshJWTToken(string token, string refreshToken) + { + var jwtHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]!); + try + { + var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false, + ClockSkew = TimeSpan.Zero, + ValidateLifetime = false + }, out SecurityToken validatedToken); + var jwtId = validatedToken.Id; + var storedRefreshToken = await _db.RefreshTokens + .FirstOrDefaultAsync(rt => rt.Token == refreshToken); + if (storedRefreshToken == null + || storedRefreshToken.Used + || storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + || storedRefreshToken.JwtId != jwtId) + { + return new JWTResult() { Success = false }; + } + storedRefreshToken.Used = true; + await _db.SaveChangesAsync(); + var userUUID = principal.Claims.First(c => c.Type == "UUID").Value; + var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID.ToString() == userUUID); + if (user == null) + { + return new JWTResult() { Success = false }; + } + return await GenerateJWTToken(user); + } + catch + { + return new JWTResult() { Success = false }; + } + } + + private static string RandomString(int length) + { + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + return new string([.. Enumerable.Repeat(chars, length).Select(s => s[Random.Shared.Next(s.Length)])]); + } + } +} diff --git a/SharpbinV3/Services/CompressionService.cs b/SharpbinV3/Services/CompressionService.cs new file mode 100644 index 0000000..25869af --- /dev/null +++ b/SharpbinV3/Services/CompressionService.cs @@ -0,0 +1,44 @@ +using System.IO.Compression; + + +namespace SharpbinV3.Services +{ + public class CompressionService : ICompressionService + { + public byte[] Compress(byte[] data) + { + byte[] result = new byte[data.Length]; + using (MemoryStream ms = new()) + { + using (GZipStream gzip = new(ms, CompressionMode.Compress)) + { + gzip.Write(data, 0, data.Length); + } + result = ms.ToArray(); + } + if (result.Length > 0 && result.Length < data.Length) + return result; + + return data; + } + public byte[] Decompress(byte[] compressedData) + { + ArgumentNullException.ThrowIfNull(compressedData); + if (!IsCompressed(compressedData)) + throw new ArgumentException("Data is not in a valid compressed format.", nameof(compressedData)); + + using (MemoryStream ms = new()) + { + using MemoryStream compressedStream = new(compressedData); + using GZipStream gzip = new(compressedStream, CompressionMode.Decompress); + gzip.CopyTo(ms); + } + return compressedData; + } + + private static bool IsCompressed(byte[] data) + { + return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B; + } + } +} diff --git a/SharpbinV3/Services/IAuthService.cs b/SharpbinV3/Services/IAuthService.cs new file mode 100644 index 0000000..fc41061 --- /dev/null +++ b/SharpbinV3/Services/IAuthService.cs @@ -0,0 +1,13 @@ +using SharpbinV3.Data.Entities; +using SharpbinV3.DTOs; + +namespace SharpbinV3.Services +{ + public interface IAuthService + { + Task CreateUser(string username, string password, string? email, string? displayName); + Task GenerateJWTToken(User user); + Task ValidateJWTToken(string token); + Task RefreshJWTToken(string token, string refreshToken); + } +} diff --git a/SharpbinV3/Services/ICompressionService.cs b/SharpbinV3/Services/ICompressionService.cs new file mode 100644 index 0000000..f5df518 --- /dev/null +++ b/SharpbinV3/Services/ICompressionService.cs @@ -0,0 +1,8 @@ +namespace SharpbinV3.Services +{ + public interface ICompressionService + { + byte[] Compress(byte[] data); + byte[] Decompress(byte[] compressedData); + } +} diff --git a/SharpbinV3/Services/IPasteService.cs b/SharpbinV3/Services/IPasteService.cs new file mode 100644 index 0000000..fa212b8 --- /dev/null +++ b/SharpbinV3/Services/IPasteService.cs @@ -0,0 +1,15 @@ +using SharpbinV3.Data.Entities; + +namespace SharpbinV3.Services +{ + public interface IPasteService + { + Task Create(Paste paste); + Task Delete(Paste paste); + Task Edit(Paste paste); + Task Exists(string id); + Task EditText(Paste paste, string text); + Task Get(string id); + Task> GetList(int offset, int count); + } +} diff --git a/SharpbinV3/Services/IUserService.cs b/SharpbinV3/Services/IUserService.cs index 3cfd5d4..063f5c9 100644 --- a/SharpbinV3/Services/IUserService.cs +++ b/SharpbinV3/Services/IUserService.cs @@ -8,6 +8,5 @@ namespace SharpbinV3.Services Task GetByUsername(string username); Task GetByUUID(Guid uuid); Task GetByEmail(string email); - Task CreateUser(string username, string password, string? email, string? displayName); } } diff --git a/SharpbinV3/Services/UserService.cs b/SharpbinV3/Services/UserService.cs index 0c12dad..77e973e 100644 --- a/SharpbinV3/Services/UserService.cs +++ b/SharpbinV3/Services/UserService.cs @@ -1,7 +1,7 @@ using Microsoft.EntityFrameworkCore; using SharpbinV3.Data; using SharpbinV3.Data.Entities; -using Bcrypt = BCrypt.Net.BCrypt; + namespace SharpbinV3.Services { @@ -13,21 +13,5 @@ namespace SharpbinV3.Services public Task GetByUUID(Guid uuid) => _db.Users.FirstOrDefaultAsync(u => u.UUID == uuid); public Task GetByUsername(string username) => _db.Users.FirstOrDefaultAsync(u => u.Username == username); public Task GetByEmail(string email) => _db.Users.FirstOrDefaultAsync(u => u.Email == email); - - public async Task CreateUser(string username, string password, string? email, string? displayName) - { - var user = new User - { - Username = username, - PasswordHash = Bcrypt.HashPassword(password), - Email = email, - DisplayName = displayName, - UUID = Guid.CreateVersion7() - }; - - _db.Users.Add(user); - await _db.SaveChangesAsync(); - return user; - } } } diff --git a/SharpbinV3/SharpbinV3.csproj b/SharpbinV3/SharpbinV3.csproj index 2b04157..682ec46 100644 --- a/SharpbinV3/SharpbinV3.csproj +++ b/SharpbinV3/SharpbinV3.csproj @@ -14,6 +14,7 @@ + @@ -26,10 +27,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + diff --git a/SharpbinV3/appsettings.json b/SharpbinV3/appsettings.json index d51abd6..300bdb4 100644 --- a/SharpbinV3/appsettings.json +++ b/SharpbinV3/appsettings.json @@ -8,5 +8,10 @@ "ConnectionStrings": { "DefaultConnection": "Data Source=sharpbin.db" }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "JwtConfig": { + "Secret": "", + "Issuer": "SharpbinApi", + "Audience": "SharpbinClient" + } }