using System.Linq;
using BlueWest.Domain;
using BlueWest.Domain;
using BlueWest.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
///
/// Api Controller for handling users data
///
[ApiController]
[Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
//[Authorize(Roles = "Administrator")]
[EnableCors(Constants.CorsPolicyName)]
public class UserController : ControllerBase
{
private readonly UserDbContext _dbContext;
///
/// Controller responsible to handle user data
///
///
public UserController(UserDbContext dbContext)
{
_dbContext = dbContext;
}
///
/// Gets all the users in the user table12312
///
///
[ProducesResponseType(StatusCodes.Status200OK)]
[HttpGet]
public ActionResult Get()
{
var users = _dbContext.Users.ToArray();
return Ok(users);
}
///
/// Get User by Id
///
///
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{userId}", Name = nameof(GetUserById))]
public ActionResult GetUserById(int userId)
{
var user = _dbContext.Users.FirstOrDefault(x => x.Id == userId);
if (user != null)
{
return Ok(user);
}
return new NotFoundResult();
}
///
/// Adds a user to the database
///
/// User to add
///
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddUser(UserCreate userCreate)
{
var user = new User(userCreate);
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
return CreatedAtRoute(nameof(GetUserById), new {userId = user.Id}, user);
}
///
/// Updates user data
///
/// User id
///
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut($"{{userId:int}}")]
public ActionResult UpdateUser(int userId, UserCreate userCreate)
{
return new NotFoundResult();
}
///
/// Deletes a user from the database
///
///
///
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpDelete("{id:int}")]
public ActionResult DeleteUser(int id)
{
var user = _dbContext.Users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return new NotFoundResult();
}
_dbContext.Users.Remove(user);
_dbContext.SaveChanges();
return Ok();
}
}
}