From 98cb301acdf30ce831deeaf88d4be1b230ddd1fd Mon Sep 17 00:00:00 2001 From: hz Date: Tue, 13 May 2025 21:42:17 -0500 Subject: [PATCH] Adding User Controller and Delete endpoint --- Controllers/UserController.cs | 40 +++++++++++++++++++++++++++++++++++ Services/UserService.cs | 6 ++++++ 2 files changed, 46 insertions(+) create mode 100644 Controllers/UserController.cs diff --git a/Controllers/UserController.cs b/Controllers/UserController.cs new file mode 100644 index 0000000..2a4ba05 --- /dev/null +++ b/Controllers/UserController.cs @@ -0,0 +1,40 @@ +using GameAuthApi.Models; +using GameAuthApi.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System.Threading.Tasks; + +namespace GameAuthApi.Controllers; + +[ApiController] +[Route("api/[controller]")] +public class UserController : ControllerBase +{ + private readonly UserService _userService; + + public UserController(UserService userService) + { + _userService = userService; + } + + // GET: /api/User + [HttpGet] + [Authorize(Roles = "SUPER")] + public async Task GetAllUsers() + { + var users = await _userService.GetAllAsync(); + return Ok(users); + } + + // DELETE: /api/User?username=foo + [HttpDelete] + [Authorize(Roles = "SUPER")] + public async Task DeleteUser([FromQuery] string username) + { + var deleted = await _userService.DeleteAsync(username); + if (!deleted) + return NotFound($"User '{username}' not found."); + + return Ok($"User '{username}' deleted successfully."); + } +} diff --git a/Services/UserService.cs b/Services/UserService.cs index 4adf734..43763b0 100644 --- a/Services/UserService.cs +++ b/Services/UserService.cs @@ -23,6 +23,12 @@ public class UserService public async Task> GetAllAsync() => await _users.Find(_ => true).ToListAsync(); + public async Task DeleteAsync(string username) + { + var result = await _users.DeleteOneAsync(u => u.Username == username); + return result.DeletedCount > 0; + } + public async Task CreateAsync(User user) => await _users.InsertOneAsync(user);