namespace GrossesMitainesAPI.Controllers; #region Dependencies using GrossesMitainesAPI.Data; using GrossesMitainesAPI.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Net.Mime; #endregion [EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"), Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Administrateur")] public class UserController : Controller { #region DI Fields private readonly Microsoft.AspNetCore.Identity.UserManager _userMan; private readonly SignInManager _signInMan; private readonly InventoryContext _context; private readonly ILogger _logger; #endregion #region Ctor public UserController(ILogger logger, SignInManager signin, Microsoft.AspNetCore.Identity.UserManager userman, InventoryContext context) { _logger = logger; _signInMan = signin; _userMan = userman; _context = context; } #endregion #region API Methods [HttpPost, AllowAnonymous] public ActionResult Post(SignUpUserModel sign) { InventoryUser usr; try { usr = new(sign); } catch (Exception e){ return BadRequest($"Erreur utilisateur: {e.Message}"); } try { usr.PasswordHash = new PasswordHasher().HashPassword(usr, sign.Password); } catch (Exception e){ return BadRequest($"Erreur de mot de passe: {e.Message}"); } try { var t1 = _userMan.CreateAsync(usr); t1.Wait(); var t2 = _userMan.AddToRoleAsync(usr, "Client"); t2.Wait(); } catch (Exception e) { return BadRequest(e.Message); } return new ReturnUserViewModel(usr, "Client"); } [HttpGet, Route("Adresses")] public async Task> GetAddresses(bool? all) { IList roles; string id; try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver. roles = await _userMan.GetRolesAsync(await _userMan.GetUserAsync(_signInMan.Context.User)); } catch (Exception e) { _logger.LogError(10, e.Message); roles = new List(); } try { id = _signInMan.Context.User.Identity.GetUserId(); if (all is not null && all == true && roles.Contains("Administrateur")) return Ok(_context.Addresses.Include("AspNetUser").ToList()); else return Ok(_context.Users.Include("Adresses").Where(x => x.Id == id).ToList()); } catch (Exception e) { _logger.LogError(10, e.Message); return BadRequest(e.Message); } } #endregion }