using System.Transactions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using UnivateProperties_API.Containers.Users; using UnivateProperties_API.Model.Users; using UnivateProperties_API.Repository; using UnivateProperties_API.Repository.Users; namespace User_API.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] public class UserController : ControllerBase { private readonly IRepository _Repo; public UserController(IRepository repo) { _Repo = repo; } [Authorize(Roles = Role.SuperAdmin)] [HttpGet] public IActionResult Get() { return new OkObjectResult(_Repo.GetAll()); } [HttpGet("{id}")] public IActionResult Get(int id) { var currentUserId = int.Parse(User.Identity.Name); if (id != currentUserId && !User.IsInRole(Role.SuperAdmin)) { return Forbid(); } return new OkObjectResult(_Repo.Get(x => x.Id == id)); } [HttpPost()] public IActionResult Post([FromBody] User user) { using (var scope = new TransactionScope()) { _Repo.Insert(user); scope.Complete(); return CreatedAtAction(nameof(Get), new { id = user.Id }, user); } } [HttpPut()] public IActionResult Put([FromBody] User user) { if (user != null) { using (var scope = new TransactionScope()) { _Repo.Update(user); scope.Complete(); return new OkResult(); } } return new NoContentResult(); } [HttpDelete("{id}")] public IActionResult Delete(int id) { _Repo.RemoveAtId(id); return new OkResult(); } } }