Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/Controller/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using api_cinema_challenge.Data;
using api_cinema_challenge.DTOs.Requests;
using api_cinema_challenge.DTOs.Response;
using api_cinema_challenge.Enums;
using api_cinema_challenge.Models;
using api_cinema_challenge.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace api_cinema_challenge.Controller
{
[ApiController]
[Route("/api/[controller]")]
public class UsersController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly CinemaContext _context;
private readonly TokenService _tokenService;

public UsersController(UserManager<ApplicationUser> userManager, CinemaContext context,
TokenService tokenService, ILogger<UsersController> logger)
{
_userManager = userManager;
_context = context;
_tokenService = tokenService;
}


[HttpPost]
[Route("register")]
public async Task<IActionResult> Register(RegistrationRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var result = await _userManager.CreateAsync(
new ApplicationUser { UserName = request.Username, Email = request.Email, Role = request.Role },
request.Password!
);

if (result.Succeeded)
{
request.Password = "";
return CreatedAtAction(nameof(Register), new { email = request.Email, role = Role.User }, request);
}

foreach (var error in result.Errors)
{
ModelState.AddModelError(error.Code, error.Description);
}

return BadRequest(ModelState);
}


[HttpPost]
[Route("login")]
public async Task<ActionResult<AuthResponse>> Authenticate([FromBody] AuthRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var managedUser = await _userManager.FindByEmailAsync(request.Email!);

if (managedUser == null)
{
return BadRequest("Bad credentials");
}

var isPasswordValid = await _userManager.CheckPasswordAsync(managedUser, request.Password!);

if (!isPasswordValid)
{
return BadRequest("Bad credentials");
}

var userInDb = _context.Users.FirstOrDefault(u => u.Email == request.Email);

if (userInDb is null)
{
return Unauthorized();
}

var accessToken = _tokenService.CreateToken(userInDb);
await _context.SaveChangesAsync();

return Ok(new AuthResponse
{
Username = userInDb.UserName,
Email = userInDb.Email,
Token = accessToken,
});
}
}

}
12 changes: 12 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/CustomerGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace api_cinema_challenge.DTOs
{
public class CustomerGet
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace api_cinema_challenge.DTOs
{
public class CustomerPost
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}
15 changes: 15 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/MovieGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace api_cinema_challenge.DTOs
{
public class MovieGet
{
public int Id { get; set; }
public string Title { get; set; }
public string Rating { get; set; }
public string Description { get; set; }
public int RunTimeMins { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }

}

}
10 changes: 10 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/MoviePost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace api_cinema_challenge.DTOs
{
public class MoviePost
{
public string Title { get; set; }
public string Rating { get; set; }
public string Description { get; set; }
public int RunTimeMins { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace api_cinema_challenge.DTOs.Requests
{
public class AuthRequest
{
public string? Email { get; set; }
public string? Password { get; set; }

public bool IsValid() { return true; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using api_cinema_challenge.Enums;
using System.ComponentModel.DataAnnotations;

namespace api_cinema_challenge.DTOs.Requests
{
public class RegistrationRequest
{
[Required]
public string? Email { get; set; }

[Required]
public string? Username { get { return this.Email; } set { } }

[Required]
public string? Password { get; set; }

public Role Role { get; set; } = Role.User;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace api_cinema_challenge.DTOs.Response
{
public class AuthResponse
{
public string? Username { get; set; }
public string? Email { get; set; }
public string? Token { get; set; }

}
}
14 changes: 14 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/ScreeningGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace api_cinema_challenge.DTOs
{
public class ScreeningGet
{
public int MovieId { get; set; }
public int ScreenNumber { get; set; }
public int Capacity { get; set; }
public DateTime StartsAt { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }


}
}
10 changes: 10 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/ScreeningPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace api_cinema_challenge.DTOs
{
public class ScreeningPost
{
//public int MovieId { get; set; }
public int ScreenNumber { get; set; }
public int Capacity { get; set; }
public DateTime StartsAt { get; set; }
}
}
12 changes: 12 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/TicketGet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace api_cinema_challenge.DTOs
{
public class TicketGet
{
public int Id { get; set; }

public int NumSeats { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }

}
}
7 changes: 7 additions & 0 deletions api-cinema-challenge/api-cinema-challenge/DTOs/TicketPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace api_cinema_challenge.DTOs
{
public class TicketPost
{
public int NumSeats { get; set; }
}
}
32 changes: 31 additions & 1 deletion api-cinema-challenge/api-cinema-challenge/Data/CinemaContext.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using Microsoft.EntityFrameworkCore;
using api_cinema_challenge.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace api_cinema_challenge.Data
{
Expand All @@ -20,7 +23,34 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//modelBuilder.Entity<Customer>().HasMany(t => t.Tickets);
/*modelBuilder.Entity<Customer>()
.HasMany(c => c.Tickets)
.WithOne(c => c.Customer);*/
modelBuilder.Entity<Ticket>()
.HasOne(t => t.Screening)
.WithMany(t => t.Tickets)
.HasForeignKey(t => t.ScreeningId);

modelBuilder.Entity<Ticket>()
.HasOne(t => t.Customer)
.WithMany(t => t.Tickets)
.HasForeignKey(t => t.CustomerId);

modelBuilder.Entity<Screening>()
.HasOne(s => s.Movie)
.WithMany(s => s.Screenings)
.HasForeignKey(s => s.MovieId);

}
public DbSet<Ticket> Tickets { get; set; }
public DbSet<ApplicationUser> Users { get; set; }
public DbSet<Screening> Screenings { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Movie> Movies { get; set; }


//public DbSet<Ticket> Ticket { get; set; }
//publi
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//using Microsoft.AspNetCore.Mvc;
using api_cinema_challenge.DTOs;
using api_cinema_challenge.Models;
using api_cinema_challenge.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace api_cinema_challenge.Endpoints
{
public static class CustomerEndpoint
{
public static void ConfigureCustomerEndpoints(this WebApplication app)
{
var customer = app.MapGroup("customers");

customer.MapGet("/", GetAll);
customer.MapPost("/", Create);
customer.MapPut("/{id}", Update);
customer.MapDelete("/{id}", Delete);

}

private static CustomerGet CustomerToCustomerGet(Customer c)
{
CustomerGet customerShow = new CustomerGet() {Id = c.Id, Name = c.Name, Email = c.Email, Phone = c.Phone, CreatedAt = c.CreatedAt, UpdatedAt = c.UpdatedAt };
return customerShow;
}

[Authorize(Roles = "Admin,User")]
[ProducesResponseType(StatusCodes.Status200OK)]
public static async Task<IResult> GetAll(IRepository<Customer> customerRepo) {
List<CustomerGet> response = new List<CustomerGet>();
var results = await customerRepo.GetAll();
foreach (Customer c in results) {
CustomerGet customerShow = CustomerToCustomerGet(c);
response.Add(customerShow);
}
return TypedResults.Ok(response);
}

[Authorize(Roles = "Admin")]
[ProducesResponseType(StatusCodes.Status201Created)]
public static async Task<IResult> Create(IRepository<Customer> customerRepo, CustomerPost cModel)
{
DateTime time = DateTime.UtcNow.ToUniversalTime();
Customer newCustomer = new Customer() {
Name = cModel.Name,
Email = cModel.Email,
Phone = cModel.Phone,
CreatedAt = time,
UpdatedAt = time
};
await customerRepo.Insert(newCustomer);
return TypedResults.Created($"Created object with id: {newCustomer.Id}");
}

[Authorize(Roles = "Admin,User")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> Update(IRepository<Customer> customerRepo, int id, CustomerPost cModel)
{
Customer? cTarget = await customerRepo.GetById(id);
if(cTarget!= null)
{
DateTime UpdatedTime = DateTime.UtcNow.ToUniversalTime();
cTarget.Name = cModel.Name;
cTarget.Email = cModel.Email;
cTarget.Phone = cModel.Phone;
cTarget.UpdatedAt = UpdatedTime;

await customerRepo.Update(cTarget);
return TypedResults.Created($"Updated object with id: {id}");
}
return TypedResults.NotFound();
}

[Authorize(Roles = "Admin,User")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> Delete(IRepository<Customer> customerRepo, int id)
{
Customer? cTarget = await customerRepo.GetById(id);
if (cTarget != null)
{
await customerRepo.Delete(id);
return TypedResults.Ok(CustomerToCustomerGet(cTarget));
}
return TypedResults.NotFound();
}
}
}
Loading