From 9149e64398e7b9f7b29bcf68db7eff2ce5f8169c Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Sun, 27 Nov 2022 14:10:25 -0600 Subject: Corregidos algunos bugs --- Controllers/AdministratorsController.cs | 2 +- Controllers/PrizesController.cs | 2 +- Controllers/RafflesController.cs | 34 +++++++++++++------------ Controllers/TicketsController.cs | 8 +++--- Controllers/UserAccountsController.cs | 2 +- Forms/PrizeForm.cs | 3 +++ Logics/CreateTicketLogic.cs | 11 +++++++- Migrations/ApplicationDbContextModelSnapshot.cs | 8 +++--- Models/Prize.cs | 4 +++ Models/RaffleWinner.cs | 5 ++++ Models/Ticket.cs | 4 ++- Policies/CorrectTokenHandler.cs | 13 ++++++---- Profiles/RaffleProfile.cs | 1 + Validations/IsNotClosed.cs | 28 ++++++++++++++++++++ wwwroot/Log.txt | 26 +++++++++++++++++++ 15 files changed, 117 insertions(+), 34 deletions(-) create mode 100644 Validations/IsNotClosed.cs diff --git a/Controllers/AdministratorsController.cs b/Controllers/AdministratorsController.cs index e76581f..f2271ed 100644 --- a/Controllers/AdministratorsController.cs +++ b/Controllers/AdministratorsController.cs @@ -25,7 +25,7 @@ namespace BackendPIA.Controllers { _manager = manager; } - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] [HttpPost("signup")] public async Task> Create(UserAccountForm form) { CreateUserAccountLogic logic = new CreateUserAccountLogic(_token_generator, _manager, form, _mapper, _user_account_service, "Administrator"); diff --git a/Controllers/PrizesController.cs b/Controllers/PrizesController.cs index 0707697..cd3f50f 100644 --- a/Controllers/PrizesController.cs +++ b/Controllers/PrizesController.cs @@ -39,7 +39,7 @@ namespace BackendPIA.Controllers { } [HttpPost] - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] public async Task> Create(PrizeForm form) { if(!_context.Raffles.Any(r => r.Id == form.RaffleId)) return BadRequest(new NotFoundError(404, $"The raffle with id {form.RaffleId} couldn't be found")); diff --git a/Controllers/RafflesController.cs b/Controllers/RafflesController.cs index aff4085..4b25519 100644 --- a/Controllers/RafflesController.cs +++ b/Controllers/RafflesController.cs @@ -22,48 +22,50 @@ namespace BackendPIA.Controllers { } [HttpGet] - public async Task> Index([FromQuery] string name = "") { - return await _service.GetRaffles(name); + public async Task>> Index([FromQuery] string name = "") { + var result = await _service.GetRaffles(name); + + return Ok(_mapper.Map>(result)); } [HttpGet("{id:int}")] - public async Task> Show(long id) { + public async Task> Show(long id) { var raffle = await _service.GetRaffle(id); if(raffle == null) - return NotFound("The resource couldn't be found"); + return NotFound(new NotFoundError(404, $"The raffle with id {id} doesn't exist or doesn't have any tickets.")); - return raffle; + return Ok(_mapper.Map(raffle)); } - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] [HttpPost] - public async Task> Create(RaffleForm form) { + public async Task> Create(RaffleForm form) { var raffle = await _service.CreateRaffle(_mapper.Map(form)); - return raffle; + return Ok(_mapper.Map(raffle)); } - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] [HttpPut("{id:int}")] - public async Task> Update(long id, RaffleForm form) { + public async Task> Update(long id, RaffleForm form) { var raffle = _mapper.Map(form); raffle.Id = id; var result = await _service.UpdateRaffle(raffle); if(result == null) - return NotFound("The resource couldn't be found."); + return NotFound(new NotFoundError(404, $"The raffle with id {id} doesn't exist or doesn't have any tickets.")); - return raffle; + return Ok(_mapper.Map(raffle)); } - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] [HttpDelete("{id:int}")] public async Task Delete(long id) { var result = await _service.DeleteRaffle(id); if(!result) - return NotFound("The resource couldn't be found."); + return NotFound(new NotFoundError(404, $"The raffle with id {id} doesn't exist or doesn't have any tickets.")); return StatusCode(303, new { Message = "The resource has been deleted"} ); } @@ -80,7 +82,7 @@ namespace BackendPIA.Controllers { return Ok(new { Numbers = available_tickets.Except(taken_tickets) }); } - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] [HttpPost("{id:int}/play")] public async Task>> Play(long id) { RafflePlayLogic logic = new RafflePlayLogic(_game_service, _service, id); @@ -92,7 +94,7 @@ namespace BackendPIA.Controllers { return Ok(_mapper.Map>(logic.Winners)); } - [Authorize] + [Authorize(Policy = "ValidToken")] [HttpGet("{id:int}/winners")] public async Task>> GetWinners(long id) { var raffle = await _service.GetRaffle(id); diff --git a/Controllers/TicketsController.cs b/Controllers/TicketsController.cs index 97a4a26..a8574d2 100644 --- a/Controllers/TicketsController.cs +++ b/Controllers/TicketsController.cs @@ -24,7 +24,7 @@ namespace BackendPIA.Controllers { _manager = manager; } - [Authorize] + [Authorize(Policy = "ValidToken")] [HttpGet] public async Task>> Index(long raffleId) { var result = await _ticket_service.GetTickets(raffleId); @@ -35,7 +35,7 @@ namespace BackendPIA.Controllers { return Ok(_mapper.Map>(result)); } - [Authorize] + [Authorize(Policy = "ValidToken")] [HttpGet("{id:int}")] public async Task> Show(long raffleId, long id) { var result = await _ticket_service.GetTicket(raffleId, id); @@ -46,7 +46,7 @@ namespace BackendPIA.Controllers { return Ok(_mapper.Map(result)); } - [Authorize] + [Authorize(Policy = "ValidToken")] [HttpPost] public async Task > Create(long raffleId, TicketForm form) { string email = HttpContext.User.Claims.Where(c => c.Type.Contains("email")).First().Value; @@ -60,7 +60,7 @@ namespace BackendPIA.Controllers { return Ok(_mapper.Map(logic.Created)); } - [Authorize(Roles = "Administrator")] + [Authorize(Roles = "Administrator", Policy = "ValidToken")] [HttpDelete("{id:int}")] public async Task Delete(long raffleId, long id) { bool result = await _ticket_service.DeleteTicket(raffleId, id); diff --git a/Controllers/UserAccountsController.cs b/Controllers/UserAccountsController.cs index 2a0a8dd..3b82590 100644 --- a/Controllers/UserAccountsController.cs +++ b/Controllers/UserAccountsController.cs @@ -27,7 +27,7 @@ namespace BackendPIA.Controllers { } [HttpGet("user")] - [Authorize(Roles = "Regular")] + [Authorize(Roles = "Regular", Policy = "ValidToken")] public async Task> Show() { string email = HttpContext.User.Claims.Where(c => c.Type.Contains("email")).First().Value; var user = await _user_account_service.GetUserAccount(email); diff --git a/Forms/PrizeForm.cs b/Forms/PrizeForm.cs index 00666f5..bc955f8 100644 --- a/Forms/PrizeForm.cs +++ b/Forms/PrizeForm.cs @@ -1,9 +1,12 @@ using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; using BackendPIA.Validations; namespace BackendPIA.Forms { public class PrizeForm { [Required] + [ForeignKey("RaffleId")] + [IsNotClosed] public long RaffleId { get; set; } [Required] public string? Name { get; set; } diff --git a/Logics/CreateTicketLogic.cs b/Logics/CreateTicketLogic.cs index df64a1a..be3c66c 100644 --- a/Logics/CreateTicketLogic.cs +++ b/Logics/CreateTicketLogic.cs @@ -24,17 +24,26 @@ namespace BackendPIA.Logics { } public async Task Call() { + var raffle = _context.Raffles.Find(_raffle_id); + // Check if the user exists. if(_user == null) return false; // Check if the given raffle exists- - if(!_context.Raffles.Any(r => r.Id == _raffle_id)) { + if(raffle == null) { ErrorMessage = "The raffle doesn't exist."; return false; } + // Check if the raffle has already closed. + if(raffle.IsClosed) { + ErrorMessage = "The raffle is already closed."; + + return false; + } + // Check if the user already has a ticket for the given raffle. if(_context.Tickets.Where(t => t.RaffleId == _raffle_id).Where(t => t.UserAccountId == _user.Id).Count() > 0) { ErrorMessage = $"There's already a ticket for {_user.UserName}."; diff --git a/Migrations/ApplicationDbContextModelSnapshot.cs b/Migrations/ApplicationDbContextModelSnapshot.cs index 37dac6d..2374b95 100644 --- a/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/Migrations/ApplicationDbContextModelSnapshot.cs @@ -48,7 +48,7 @@ namespace BackendPIA.Migrations b.HasIndex("RaffleId"); - b.ToTable("Prizes"); + b.ToTable("Prizes", (string)null); }); modelBuilder.Entity("BackendPIA.Models.Raffle", b => @@ -72,7 +72,7 @@ namespace BackendPIA.Migrations b.HasKey("Id"); - b.ToTable("Raffles"); + b.ToTable("Raffles", (string)null); }); modelBuilder.Entity("BackendPIA.Models.RaffleWinner", b => @@ -101,7 +101,7 @@ namespace BackendPIA.Migrations b.HasIndex("UserAccountId"); - b.ToTable("RaffleWinners"); + b.ToTable("RaffleWinners", (string)null); }); modelBuilder.Entity("BackendPIA.Models.Ticket", b => @@ -131,7 +131,7 @@ namespace BackendPIA.Migrations b.HasIndex("UserAccountId"); - b.ToTable("Tickets"); + b.ToTable("Tickets", (string)null); }); modelBuilder.Entity("BackendPIA.Models.UserAccount", b => diff --git a/Models/Prize.cs b/Models/Prize.cs index 496dcb7..d35b098 100644 --- a/Models/Prize.cs +++ b/Models/Prize.cs @@ -1,6 +1,10 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + namespace BackendPIA.Models { public class Prize { public long Id { get; set; } + [ForeignKey("RaffleId")] public long RaffleId { get; set; } public Raffle? Raffle { get; set; } public string Name { get; set; } diff --git a/Models/RaffleWinner.cs b/Models/RaffleWinner.cs index 59b91b2..355c747 100644 --- a/Models/RaffleWinner.cs +++ b/Models/RaffleWinner.cs @@ -1,8 +1,13 @@ +using System.ComponentModel.DataAnnotations.Schema; + namespace BackendPIA.Models { public class RaffleWinner { public long Id { get; set; } + [ForeignKey("UserAccountId")] public string UserAccountId { get; set; } + [ForeignKey("PrizeId")] public long PrizeId { get; set; } + [ForeignKey("RaffleId")] public long RaffleId { get; set; } public UserAccount? UserAccount { get; set; } public Prize? Prize { get; set; } diff --git a/Models/Ticket.cs b/Models/Ticket.cs index a876259..fe7bdbd 100644 --- a/Models/Ticket.cs +++ b/Models/Ticket.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace BackendPIA.Models { public class Ticket { @@ -8,9 +9,10 @@ namespace BackendPIA.Models { public int Number { get; set; } public bool IsWinner { get; set; } [Required] + [ForeignKey("UserAccountId")] public string? UserAccountId { get; set; } [Required] - + [ForeignKey("RaffleId")] public long RaffleId { get; set; } public UserAccount? Owner { get; set; } public Raffle? Raffle { get; set; } diff --git a/Policies/CorrectTokenHandler.cs b/Policies/CorrectTokenHandler.cs index 7663ec8..2356b56 100644 --- a/Policies/CorrectTokenHandler.cs +++ b/Policies/CorrectTokenHandler.cs @@ -13,13 +13,16 @@ namespace BackendPIA.Policies { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CorrectTokenRequirement requirement) { if(context.Resource is HttpContext httpContext) { - var user = _manager.FindByEmailAsync(context.User.Claims.Where(c => c.Type.Contains("email")).First().Value).Result; + var claims = context.User.Claims.Where(c => c.Type.Contains("email")); + if(claims != null) { + var user = _manager.FindByEmailAsync(claims.First().Value).Result; - if(user != null) { - string token = httpContext.Request.Headers["Authorization"].ToString().Split(' ')[1]; + if(user != null) { + string token = httpContext.Request.Headers["Authorization"].ToString().Split(' ')[1]; - if(user.CurrentToken != null && user.CurrentToken == token) - context.Succeed(requirement); + if(user.CurrentToken != null && user.CurrentToken == token) + context.Succeed(requirement); + } } } diff --git a/Profiles/RaffleProfile.cs b/Profiles/RaffleProfile.cs index 4b872b3..7f5a39b 100644 --- a/Profiles/RaffleProfile.cs +++ b/Profiles/RaffleProfile.cs @@ -6,6 +6,7 @@ namespace BackendPIA.Profiles { public class RaffleProfile : Profile { public RaffleProfile() { CreateMap().ReverseMap(); + CreateMap(); } } } diff --git a/Validations/IsNotClosed.cs b/Validations/IsNotClosed.cs new file mode 100644 index 0000000..3277356 --- /dev/null +++ b/Validations/IsNotClosed.cs @@ -0,0 +1,28 @@ +using System.ComponentModel.DataAnnotations; +using BackendPIA.Models; +using BackendPIA.Forms; + +namespace BackendPIA.Validations { + public class IsNotClosed : ValidationAttribute { + public string GetIsClosedErrorMessage(object? value) { + return $"The given raffle is already closed."; + } + + public string GetNullRaffleErrorMessage(object? value) { + return $"The raffle with id {value} doesn't exist"; + } + + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { + var db_context = (ApplicationDbContext) validationContext.GetService(typeof(ApplicationDbContext)); + var raffle = db_context.Raffles.Find((long) value); + + if(raffle == null) + return new ValidationResult(GetNullRaffleErrorMessage(value)); + + if(raffle.IsClosed) + return new ValidationResult(GetIsClosedErrorMessage(value)); + + return ValidationResult.Success; + } + } +} \ No newline at end of file diff --git a/wwwroot/Log.txt b/wwwroot/Log.txt index edf5f19..2b68e82 100644 --- a/wwwroot/Log.txt +++ b/wwwroot/Log.txt @@ -10,3 +10,29 @@ Executing task 27/11/2022 01:35:41 Stopping task... +Executing task +27/11/2022 01:46:23 +Executing task +27/11/2022 01:51:23 +Stopping task... + +Executing task +27/11/2022 01:54:04 +Stopping task... + +Executing task +27/11/2022 01:54:58 +Executing task +27/11/2022 01:58:30 +Executing task +27/11/2022 02:06:15 +Stopping task... + +Executing task +27/11/2022 02:06:35 +Stopping task... + +Executing task +27/11/2022 02:08:08 +Stopping task... + -- cgit v1.2.3