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
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using api_cinema_challenge.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using api_cinema_challenge.Data;
using api_cinema_challenge.Enums;
using api_cinema_challenge.Services;
using api_cinema_challenge.DataModels;
using api_cinema_challenge.DTOs.Auth;


namespace api_cinema_challenge.Controllers
{

[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/Auth/AuthRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace api_cinema_challenge.DTOs.Auth;

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,9 @@
namespace api_cinema_challenge.DTOs.Auth;


public class AuthResponse
{
public string? Username { get; set; }
public string? Email { get; set; }
public string? Token { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@


using System.ComponentModel.DataAnnotations;
using api_cinema_challenge.Enums;

namespace api_cinema_challenge.DTOs.Auth;

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.Customers
{
public class CustomerPostPut
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace api_cinema_challenge.DTOs.Movies
{
public class MoviePostPut
{
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,9 @@
namespace api_cinema_challenge.DTOs.Screenings
{
public class ScreeningPostPut
{
public int ScreenNumber { get; set; }
public int Capacity { get; set; }
public DateTime StartsAt { get; set; }
}
}
13 changes: 10 additions & 3 deletions api-cinema-challenge/api-cinema-challenge/Data/CinemaContext.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using Microsoft.EntityFrameworkCore;
using api_cinema_challenge.DataModels;
using api_cinema_challenge.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;

namespace api_cinema_challenge.Data
{
public class CinemaContext : DbContext
public class CinemaContext : IdentityUserContext<ApplicationUser>
{
private string _connectionString;
public CinemaContext(DbContextOptions<CinemaContext> options) : base(options)
Expand All @@ -20,7 +23,11 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<Movie>().HasData(new Movie { Id = 1, Description = "t", Rating = "1", Title = "bullshit", CreatedAt = new DateTime(2025, 8, 21, 13, 30, 0, DateTimeKind.Utc), UpdatedAt = new DateTime(2025, 8, 21, 13, 30, 0, DateTimeKind.Utc), RuntimeMins = 10 });
base.OnModelCreating(modelBuilder);
}
public DbSet<Movie> Movies { get; set; }
public DbSet<Screening> Screenings { get; set; }
public DbSet<Customer> Customers { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using api_cinema_challenge.Enums;
using Microsoft.AspNetCore.Identity;


namespace api_cinema_challenge.DataModels;
public class ApplicationUser : IdentityUser
{
public Role Role { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using api_cinema_challenge.DTOs.Customers;
using api_cinema_challenge.Models;
using api_cinema_challenge.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

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

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

}

[ProducesResponseType(StatusCodes.Status200OK)]
public static async Task<IResult> GetAll(IRepository<Customer> customerRepository)
{

var results = await customerRepository.Get();

return TypedResults.Ok(results);

}

[Authorize(Roles = "User")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public static async Task<IResult> Create(IRepository<Customer> customerRepository, CustomerPostPut model)
{
Customer customer = new Customer()
{
Name = model.Name,
Email = model.Email,
Phone = model.Phone,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
var entity = await customerRepository.Insert(customer);


return TypedResults.Created($"", entity);
}

[Authorize(Roles = "Admin")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> UpdateCustomer(IRepository<Customer> customerRepository, int id, CustomerPostPut model)
{
var resultGet = await customerRepository.GetOne(id);
resultGet.Name = model.Name;
resultGet.Email = model.Email;
resultGet.Phone = model.Phone;
resultGet.UpdatedAt = DateTime.UtcNow;

var result = await customerRepository.Update(resultGet);
return TypedResults.Ok(result);
}

[Authorize(Roles = "Admin")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public static async Task<IResult> Delete(IRepository<Customer> customerRepository, int id)
{
var result = await customerRepository.Delete(id);
return TypedResults.Ok(result);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using api_cinema_challenge.DTOs.Customers;
using api_cinema_challenge.DTOs.Movies;
using api_cinema_challenge.Models;
using api_cinema_challenge.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace api_cinema_challenge.Endpoints
{
public static class MovieEndpoint
{
public static void ConfigureMovieEndpoints(this WebApplication app)
{
var movie = app.MapGroup("/movies");

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

[ProducesResponseType(StatusCodes.Status200OK)]
public static async Task<IResult> GetAll(IRepository<Movie> movieRepository)
{
var results = await movieRepository.Get();

return TypedResults.Ok(results);
}

[Authorize(Roles = "User")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public static async Task<IResult> Create(IRepository<Movie> movieRepository, MoviePostPut model)
{
Movie movie = new Movie()
{
Title = model.Title,
Rating = model.Rating,
Description = model.Description,
RuntimeMins = model.RuntimeMins,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
var entity = await movieRepository.Insert(movie);


return TypedResults.Created($"", entity);
}

[Authorize(Roles = "Admin")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public static async Task<IResult> UpdateMovie(IRepository<Movie> movieRepository, int id, MoviePostPut model)
{
var resultGet = await movieRepository.GetOne(id);
resultGet.Title = model.Title;
resultGet.Rating = model.Rating;
resultGet.Description = model.Description;
resultGet.RuntimeMins = model.RuntimeMins;
resultGet.UpdatedAt = DateTime.UtcNow;

var result = await movieRepository.Update(resultGet);
return TypedResults.Ok(result);
}

[Authorize(Roles = "Admin")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public static async Task<IResult> Delete(IRepository<Movie> movieRepository, int id)
{
var result = await movieRepository.Delete(id);
return TypedResults.Ok(result);
}
}
}
Loading