2025-03-19 15:01:58 +01:00

240 lines
8.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Manager.Services;
using ManagerService.Data;
using ManagerService.DTOs;
using ManagerService.Helpers;
using ManagerService.Service.Services;
using ManagerService.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSwag.Annotations;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("User", Description = "User management")]
public class UserController : ControllerBase
{
private UserDatabaseService _userService;
private TokensService _tokenService;
private readonly ILogger<UserController> _logger;
private readonly ProfileLogic _profileLogic;
private readonly MyInfoMateDbContext _myInfoMateDbContext;
IHexIdGeneratorService idService = new HexIdGeneratorService();
public UserController(ILogger<UserController> logger, UserDatabaseService userService, TokensService tokenService, ProfileLogic profileLogic, MyInfoMateDbContext myInfoMateDbContext)
{
_logger = logger;
_userService = userService;
_tokenService = tokenService;
_profileLogic = profileLogic;
_myInfoMateDbContext = myInfoMateDbContext;
}
/// <summary>
/// Get a list of user
/// </summary>
[ProducesResponseType(typeof(List<User>), 200)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet]
public ObjectResult Get()
{
try
{
//List<OldUser> users = _userService.GetAll();
List<User> users= _myInfoMateDbContext.Users.ToList();
return new OkObjectResult(users);
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a specific user
/// </summary>
/// <param name="id">id user</param>
[ProducesResponseType(typeof(UserDetailDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}")]
public ObjectResult GetDetail(string id)
{
try
{
User user = _myInfoMateDbContext.Users.FirstOrDefault(i => i.Id == id);
//OldUser user = _userService.GetById(id);
if (user == null)
throw new KeyNotFoundException("This user was not found");
return new OkObjectResult(user.ToDTO());
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create an user
/// </summary>
/// <param name="newUser">New user info</param>
//[AllowAnonymous]
[ProducesResponseType(typeof(UserDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost]
public ObjectResult CreateUser([FromBody] UserDetailDTO newUserDTO)
{
try
{
if (newUserDTO == null)
throw new ArgumentNullException("User param is null");
if (newUserDTO.instanceId == null)
throw new ArgumentNullException("InstanceId is null");
User newUser = new User();
newUser.InstanceId = newUserDTO.instanceId;
newUser.Email = newUserDTO.email;
newUser.FirstName = newUserDTO.firstName;
newUser.LastName = newUserDTO.lastName;
newUser.Token = _tokenService.GenerateToken(newUser.Email).ToString();
newUser.DateCreation = DateTime.Now.ToUniversalTime();
newUser.Id = idService.GenerateHexId();
List<User> users= _myInfoMateDbContext.Users.ToList();
//List<OldUser> users = _userService.GetAll();
if (users.Select(u => u.Email).Contains(newUser.Email))
throw new InvalidOperationException("This Email is already used");
newUser.Password = _profileLogic.HashPassword(newUser.Password);
//OldUser userCreated = _userService.Create(newUser);
_myInfoMateDbContext.Add(newUser);
_myInfoMateDbContext.SaveChanges();
return new OkObjectResult(newUser.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) {};
}
catch (InvalidOperationException ex)
{
return new ConflictObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Update an user
/// </summary>
/// <param name="updatedUser">User to update</param>
[ProducesResponseType(typeof(UserDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut]
public ObjectResult UpdateUser([FromBody] UserDetailDTO updatedUser)
{
try
{
if (updatedUser == null)
throw new ArgumentNullException("User param is null");
User user = _myInfoMateDbContext.Users.FirstOrDefault(u => u.Id == updatedUser.id);
//OldUser user = _userService.GetById(updatedUser.Id);
if (user == null)
throw new KeyNotFoundException("User does not exist");
//OldUser userModified = _userService.Update(updatedUser.Id, updatedUser);
user.FirstName = updatedUser.firstName;
user.LastName = updatedUser.lastName;
// TODO other field ?
_myInfoMateDbContext.SaveChanges();
return new OkObjectResult(user.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) {};
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) {};
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete an user
/// </summary>
/// <param name="id">Id of user to delete</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpDelete("{id}")]
public ObjectResult DeleteUser(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("User param is null");
User user = _myInfoMateDbContext.Users.FirstOrDefault(u => u.Id == id);
//OldUser user = _userService.GetById(id);
if (user == null)
throw new KeyNotFoundException("User does not exist");
//_userService.Remove(id);
_myInfoMateDbContext.Remove(user);
_myInfoMateDbContext.SaveChanges();
return new ObjectResult("The user has been deleted") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
}
}