chore: rename SharpbinV3 dir to SharpbinV3.Server

This commit is contained in:
2025-12-30 12:39:26 -05:00
parent 31142e0cf9
commit 1ec4877aad
45 changed files with 7 additions and 94 deletions
@@ -0,0 +1,115 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.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<IActionResult> Register([FromBody] RegisterRequest request)
{
var existingUser = await _userService.GetByUsername(request.Username);
if (existingUser != null)
return Conflict(new { message = "Username already exists." });
if (!string.IsNullOrEmpty(request.Email))
{
var existingEmailUser = await _userService.GetByEmail(request.Email);
if (existingEmailUser != null)
return Conflict(new { message = "Email already in use." });
if (!IsValidEmail(request.Email))
return BadRequest(new { message = "Invalid email." });
}
if (!IsValidPassword(request.Password))
return BadRequest(new { message = "Password should have at least 8 characters, including uppercase, lowercase, and digits." });
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<IActionResult> 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);
await _authService.UpdateLoginTime(user);
return Ok(new { token.Result });
}
[HttpPost]
[Route("refresh")]
[EnableRateLimiting("Sliding")]
public async Task<IActionResult> 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 });
}
}
private static bool IsValidPassword(string password)
{
if (password.Length < 6)
return false;
if (!password.Any(char.IsUpper))
return false;
if (!password.Any(char.IsLower))
return false;
if (!password.Any(char.IsDigit))
return false;
return true;
}
private static bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
}
}
@@ -0,0 +1,212 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Settings;
using System.Security.Claims;
namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(IPasteService pasteService, IUserService userService, IOptions<PasteSettings> options) : ControllerBase
{
private readonly IPasteService _pasteService = pasteService;
private readonly IUserService _userService = userService;
private readonly PasteSettings _pasteSettings = options.Value;
[HttpPost]
[Route("create")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
{
if (!await _pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(visibility))
return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(syntax))
return BadRequest(new { message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(title))
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
var httpUser = HttpContext.User;
var userUUID = httpUser?.FindFirst("UUID")?.Value;
User? user = userUUID is not null ? await _userService.GetByUUID(Guid.Parse(userUUID)) : null;
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
return Ok(new
{
paste.ID,
paste.UUID,
paste.IsCompressed,
paste.Size,
paste.TrueSize,
paste.ExpiresAt
});
}
[HttpGet]
[Route("{id}")]
public async Task<IActionResult> GetPasteByID(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
return Ok(new
{
paste.ID,
paste.UUID,
paste.Title,
paste.Size,
paste.TrueSize,
paste.IsCompressed,
paste.Views,
paste.Syntax,
paste.Visibility,
paste.ExpiresAt,
paste.EditedAt,
Author = paste.User != null && paste.User.Visibility == 0 ? new
{
paste.User.UID,
paste.User.UUID,
paste.User.Username,
paste.User.DisplayName,
paste.User.Visibility
} : null
});
}
[HttpGet]
[Route("raw/{id}")]
public async Task<IActionResult> GetRawPasteByID(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
if (paste.IsCompressed)
{
Response.Headers.Append("Content-Encoding", "gzip");
return File(paste.Content, "application/octet-stream");
}
else
{
return File(paste.Content, "text/plain; charset=utf-8");
}
}
[HttpPut]
[Route("{id}/edit")]
[Authorize]
public async Task<IActionResult> EditPaste(string id)
{
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content == null || id == null) return NotFound();
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.User;
var uuidClaim = user?.FindFirst("UUID")?.Value;
if (uuidClaim == null || user == null) return Forbid();
var hasPrivilegedRole = user.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) || !hasPrivilegedRole)
return Forbid();
bool result = await _pasteService.EditText(paste, content);
if (!result) return NotFound();
return Ok(new { message = "Paste edited successfully." });
}
[HttpPatch]
[Route("{id}/modify")]
[Authorize]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] PasteMetadataUpdateRequest request)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.User;
var uuidClaim = user?.FindFirst("UUID")?.Value;
if (uuidClaim == null || user == null) return Forbid();
var hasPrivilegedRole = user.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) || !hasPrivilegedRole)
return Forbid();
if (request.Title != null)
paste.Title = request.Title;
if (request.Syntax != null)
paste.Syntax = request.Syntax;
if (request.Visibility.HasValue)
paste.Visibility = request.Visibility.Value;
if (request.ExpiresAt.HasValue)
paste.ExpiresAt = request.ExpiresAt.Value;
if (!await _pasteService.ValidateExpiresAt(paste.ExpiresAt))
return BadRequest(new { message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(paste.Visibility))
return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(paste.Syntax ?? "plaintext"))
return BadRequest(new { message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(paste.Title ?? ""))
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
var newPaste = await _pasteService.Edit(paste);
return Ok(new
{
message = "Paste metadata updated successfully.",
paste = new
{
newPaste.ID,
newPaste.UUID,
newPaste.Title,
newPaste.Size,
newPaste.TrueSize,
newPaste.IsCompressed,
newPaste.Views,
newPaste.Syntax,
newPaste.Visibility,
newPaste.ExpiresAt
}
});
}
[HttpDelete]
[Route("{id}")]
[Authorize]
public async Task<IActionResult> DeletePaste(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.User;
var uuidClaim = user?.FindFirst("UUID")?.Value;
if (uuidClaim == null || user == null) return Forbid();
var hasPrivilegedRole = user.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) || !hasPrivilegedRole)
return Forbid();
bool result = await _pasteService.Delete(paste);
if (!result) return NotFound();
return Ok(new { message = "Paste deleted successfully." });
}
[HttpGet]
[Route("create/options")]
public IActionResult GetCreatePasteOptions()
{
var options = new
{
syntaxes = _pasteSettings.ValidSyntaxLanguages,
visibilities = new[]
{
new { value = 0, displayName = "Public" },
new { value = 1, displayName = "Unlisted" },
new { value = 2, displayName = "Private" }
},
maxTitleLength = _pasteSettings.MaxTitleLength,
maxPasteSize = _pasteSettings.MaxPasteSizeInBytes
};
return Ok(options);
}
}
}
@@ -0,0 +1,120 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(IUserService userService, AppDbContext db) : ControllerBase
{
private readonly IUserService _userService = userService;
private readonly AppDbContext _db = db;
[HttpGet("{username}")]
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
{
var user = await _userService.GetByUsername(username, withPastes: true);
return user == null ? NotFound() : Ok(await BuildUserResponse(user, page));
}
[HttpGet("uuid/{uuid}")]
public async Task<IActionResult> GetByUUID(Guid uuid, [FromQuery] int page = 1)
{
var user = await _userService.GetByUUID(uuid, withPastes: true);
return user == null ? NotFound() : Ok(await BuildUserResponse(user, page));
}
[HttpGet("me")]
[Authorize]
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
{
var userUUID = HttpContext.User?.FindFirst("UUID")?.Value;
if (userUUID is null)
return Unauthorized(new { message = "Invalid token." });
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
return user == null ? NotFound() : Ok(await BuildUserResponse(user, page));
}
private async Task<object> BuildUserResponse(User user, int page = 1)
{
var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString();
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser)
{
if (user.Visibility == 1 || user.Visibility == 2)
return NotFound();
else
pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
}
if (page < 1)
page = 1;
const int pageSize = 50;
var totalCount = await pasteQuery.CountAsync();
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var skip = (page - 1) * pageSize;
var pastes = await pasteQuery
.OrderByDescending(p => p.UUID)
.ThenByDescending(p => p.ID)
.Skip(skip)
.Take(pageSize)
.Select(p => new
{
p.ID,
p.UUID,
p.Title,
p.Syntax,
p.Size,
p.TrueSize,
p.Views,
p.Visibility,
p.EditedAt,
p.ExpiresAt
})
.ToListAsync();
var pagination = new
{
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
};
if (isAuthenticatedUser)
{
return new
{
user.UID,
user.Username,
user.UUID,
user.DisplayName,
user.Email,
user.LastLogin,
user.Roles,
user.Visibility,
Pastes = pastes,
Pagination = pagination
};
}
return new
{
user.UID,
user.Username,
user.UUID,
user.DisplayName,
user.Roles,
Pastes = pastes,
Pagination = pagination
};
}
}
}