react-version #1

Merged
memartel_loc merged 290 commits from react-version into main 2023-11-04 09:48:15 -04:00
6 changed files with 108 additions and 51 deletions
Showing only changes of commit 4eb8bb7353 - Show all commits

View File

@ -132,37 +132,37 @@ public class InventoryController : Controller {
}
}
// Inventory/Delete => Décrémenter un produit. Va aller chercher directement dans la BD.
[EnableCors("_myAllowSpecificOrigins"), HttpDelete(Name = "Inventory"), AllowAnonymous]
public ActionResult<int> Delete(int? id) {
int rid = 0;
if (!id.HasValue) {
_logger.LogError(8, "Tentative de vente sans Id.");
return BadRequest();
}
try {
ProductModel prod = _context.Products.First(x => x.Id == id);
rid = prod.Id;
if (prod.Quantity > 0) {
prod.Quantity = prod.Quantity - 1;
prod.Sales = prod.Sales + 1;
prod.LastSale = DateTime.Now;
if (prod.Quantity == 0)
prod.Status = prod.Status == ProductModel.States.Clearance ?
ProductModel.States.Discontinued :
ProductModel.States.BackOrder;
} else {
_logger.LogError(8, $"Vente de produit pas en stock. Id Produit: {prod.Id}");
return BadRequest();
}
_context.Products.Update(prod);
_context.SaveChanges();
} catch (Exception e) {
_logger.LogError(8, e.Message);
return BadRequest();
}
_cache.askForRefresh();
return rid;
}
//[EnableCors("_myAllowSpecificOrigins"), HttpDelete(Name = "Inventory"), AllowAnonymous]
//public ActionResult<int> Delete(int? id) {
// int rid = 0;
// if (!id.HasValue) {
// _logger.LogError(8, "Tentative de vente sans Id.");
// return BadRequest();
// }
// try {
// ProductModel prod = _context.Products.First(x => x.Id == id);
// rid = prod.Id;
// if (prod.Quantity > 0) {
// prod.Quantity = prod.Quantity - 1;
// prod.Sales = prod.Sales + 1;
// prod.LastSale = DateTime.Now;
// if (prod.Quantity == 0)
// prod.Status = prod.Status == ProductModel.States.Clearance ?
// ProductModel.States.Discontinued :
// ProductModel.States.BackOrder;
// } else {
// _logger.LogError(8, $"Vente de produit pas en stock. Id Produit: {prod.Id}");
// return BadRequest();
// }
// _context.Products.Update(prod);
// _context.SaveChanges();
// } catch (Exception e) {
// _logger.LogError(8, e.Message);
// return BadRequest();
// }
// _cache.askForRefresh();
// return rid;
//}
#endregion
}

View File

@ -0,0 +1,21 @@
using GrossesMitainesAPI.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace GrossesMitainesAPI.Controllers;
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Administrateur")]
public class InvoiceController : Controller {
private readonly ILogger<InvoiceController> _logger;
private readonly InventoryContext _context;
public InvoiceController(ILogger<InvoiceController> logger, InventoryContext context) {
this._logger = logger;
this._context = context;
}
}

View File

@ -1,5 +1,6 @@
namespace GrossesMitainesAPI.Controllers;
#region Dependencies
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Authorization;
@ -10,44 +11,54 @@ using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Principal;
using GrossesMitainesAPI.Models;
#endregion
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api"),
Authorize(AuthenticationSchemes = "Identity.Application")]
public class LoginController : Controller {
#region DI Fields
private readonly UserManager<InventoryUser> _userMan;
private readonly RoleManager<IdentityRole> _roleMan;
private readonly SignInManager<InventoryUser> _signInMan;
public LoginController(SignInManager<InventoryUser> signin, UserManager<InventoryUser> userman, RoleManager<IdentityRole> roleMan) {
#endregion
#region Ctor
public LoginController(SignInManager<InventoryUser> signin, UserManager<InventoryUser> userman) {
this._signInMan = signin;
this._userMan = userman;
this._roleMan = roleMan;
}
#endregion
#region Utility Classes
public class LoginUser {
public string email { get; set; } = "";
public string password { get; set; } = "";
}
[HttpGet, Route("Login")]
public ReturnUserViewModel WhoAmI() {
var user = _userMan.GetUserAsync(_signInMan.Context.User);
user.Wait();
var roles = _userMan.GetRolesAsync(user.Result);
roles.Wait();
#endregion
#region API Methods
[HttpGet, Route("WhoAmI")]
public async Task<ReturnUserViewModel> WhoAmI() {
var user = await _userMan.GetUserAsync(_signInMan.Context.User);
var roles = await _userMan.GetRolesAsync(user);
string role = "";
if (roles.Result.Contains("Administrateur"))
if (roles.Contains("Administrateur"))
role = "Administrateur";
else role = "Client";
return new ReturnUserViewModel(user.Result, role);
return new ReturnUserViewModel(user, role);
}
[HttpPost, Route("Login"), AllowAnonymous]
public async Task<SignInResult> Login(LoginUser user, bool rememberMe = false) {
return await _signInMan.PasswordSignInAsync(await _userMan.FindByEmailAsync(user.email), user.password, rememberMe, false);
var User = await _userMan.FindByEmailAsync(user.email);
return await _signInMan.PasswordSignInAsync(User, user.password, rememberMe, false);
}
[HttpPost, Route("Logout")]
public void Logout() => _signInMan.SignOutAsync();
#endregion
}

View File

@ -21,7 +21,7 @@ using GrossesMitainesAPI.Services;
/// l'éxécution d'une modification de la BD.
/// </summary>
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
Authorize(AuthenticationSchemes = "Identity.Application")]
Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Administrateur")]
public class ProductController : ControllerBase {
#region DI Fields
private readonly ILogger<ProductController> _logger;

View File

@ -0,0 +1,25 @@
using GrossesMitainesAPI.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace GrossesMitainesAPI.Controllers;
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Administrateur")]
public class UserController : Controller {
private readonly UserManager<InventoryUser> _userMan;
private readonly SignInManager<InventoryUser> _signInMan;
public UserController(SignInManager<InventoryUser> signin, UserManager<InventoryUser> userman) {
this._signInMan = signin;
this._userMan = userman;
}
}

View File

@ -3,7 +3,7 @@ import { Button } from "react-bootstrap";
const Login = () => {
const [adresse, setAdresse] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [returnmess, returnMessage] = useState("");
@ -17,14 +17,13 @@ const Login = () => {
'Accept': 'text/json',
'Content-Type': 'text/json'
},
body: JSON.stringify({ username, password })
body: JSON.stringify({ email, password })
});
// Partie de display d'erreur ou de redirection (faudrait checker pour se faire un state de connexion avec un cookie pour react).
if (response.status === 200) {
var rep = await response.json();
if (rep.succeeded === true) {
const confirm = await fetch(`https://localhost:7292/api/Login`, {
const confirm = await fetch(`https://localhost:7292/api/WhoAmI`, {
method: 'GET',
credentials: 'include',
headers: {
@ -32,6 +31,7 @@ const Login = () => {
'Content-Type': 'text/json'
}
});
// TODO: Redirection vers Home et ajout du cookie pour React pour le layout.
console.log(await confirm.json())
returnMessage("WOOHOO!");
}
@ -52,8 +52,8 @@ const Login = () => {
<label>Adresse courriel </label>
<input className="form-control form-input" type='text'
placeholder="Adresse..."
value={adresse}
onChange={(e) => setAdresse(e.target.value)} />
value={email}
onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="form-group">
<label>Mot de passe: </label>