Merge branch 'react-version' of https://github.com/MarcEricMartel/420-5DW-HY-TP into react-version

This commit is contained in:
Victor Turgeon 2022-11-08 10:22:22 -05:00
commit 576152cc12
7 changed files with 121 additions and 78 deletions

View File

@ -14,7 +14,7 @@ using Microsoft.EntityFrameworkCore;
#endregion #endregion
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"), [EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
Authorize(AuthenticationSchemes = "Identity.Application")] Authorize(AuthenticationSchemes = "Identity.Application", Roles ="Client, Administrateur")]
public class AddressController : Controller { public class AddressController : Controller {
#region DI Fields #region DI Fields
private readonly ILogger<AddressController> _logger; private readonly ILogger<AddressController> _logger;

View File

@ -16,7 +16,7 @@ using System.Linq;
#endregion #endregion
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"), [EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Administrateur")] Authorize(AuthenticationSchemes = "Identity.Application", Roles = "Client, Administrateur")]
public class InvoiceController : Controller { public class InvoiceController : Controller {
#region DI Fields #region DI Fields
private readonly ILogger<InvoiceController> _logger; private readonly ILogger<InvoiceController> _logger;
@ -43,15 +43,14 @@ public class InvoiceController : Controller {
#endregion #endregion
#region API Methods #region API Methods
[HttpGet, Authorize(Roles = "Client, Administrateur")] [HttpGet]
public async Task<ActionResult<List<InvoiceModel>>> Get(bool? all = false) { public async Task<ActionResult<List<InvoiceModel>>> Get(bool? all = false) {
IList<string> roles; IList<string> roles;
string id; string id;
try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver. try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver.
var user = await _userMan.GetUserAsync(_signInMan.Context.User); var user = await _userMan.GetUserAsync(_signInMan.Context.User);
roles = await _userMan.GetRolesAsync(user); roles = await _userMan.GetRolesAsync(user);
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(10, e.Message); _logger.LogError(10, e.Message);
roles = new List<string>(); roles = new List<string>();
} }
@ -71,30 +70,27 @@ public class InvoiceController : Controller {
.Include(x => x.Products) .Include(x => x.Products)
.ThenInclude(y => y.Product) .ThenInclude(y => y.Product)
.Where(x => x.LinkedAccount != null && x.LinkedAccount.Id == id).ToList()); .Where(x => x.LinkedAccount != null && x.LinkedAccount.Id == id).ToList());
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(10, e.Message); _logger.LogError(10, e.Message);
return BadRequest(); return BadRequest();
} }
} }
[HttpGet("{id}"), Authorize(Roles = "Client, Administrateur")] [HttpGet("{id}")]
public async Task<ActionResult<InvoiceModel>> Get(int id) { public async Task<ActionResult<InvoiceModel>> Get(int id) {
IList<string> roles; IList<string> roles;
InvoiceModel inv; InvoiceModel inv;
try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver. try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver.
roles = await _userMan.GetRolesAsync(await _userMan.GetUserAsync(_signInMan.Context.User)); roles = await _userMan.GetRolesAsync(await _userMan.GetUserAsync(_signInMan.Context.User));
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(10, e.Message); _logger.LogError(10, e.Message);
roles = new List<string>(); roles = new List<string>();
} }
try { try {
inv = _context.Invoices.Where(x => x.Id == id).Include("ShippingAddress").First(); inv = _context.Invoices.Where(x => x.Id == id).Include("ShippingAddress").First();
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(10, e.Message); _logger.LogError(10, e.Message);
return BadRequest(); return BadRequest();
} }
@ -119,7 +115,11 @@ public class InvoiceController : Controller {
PhoneNumber = sinv.PhoneNumber, PhoneNumber = sinv.PhoneNumber,
PurchaseDate = DateTime.Now PurchaseDate = DateTime.Now
}; };
AddressModel ad = _context.Addresses.FirstOrDefault(x => x.CivicNumber == sinv.CivicNumber && AddressModel ad;
if (user is not null) {
inv.LinkedAccount = user;
ad = _context.Addresses.FirstOrDefault(x => x.CivicNumber == sinv.CivicNumber &&
x.Appartment == sinv.Appartment && x.Appartment == sinv.Appartment &&
x.Street == sinv.Street && x.Street == sinv.Street &&
x.City == sinv.City && x.City == sinv.City &&
@ -134,14 +134,22 @@ public class InvoiceController : Controller {
Country = sinv.Country, Country = sinv.Country,
PostalCode = sinv.PostalCode PostalCode = sinv.PostalCode
}; };
}
else ad = new() {
CivicNumber = sinv.CivicNumber,
Appartment = sinv.Appartment,
Street = sinv.Street,
City = sinv.City,
Province = sinv.Province,
Country = sinv.Country,
PostalCode = sinv.PostalCode
};
inv.ShippingAddress = ad; inv.ShippingAddress = ad;
if (user is not null)
inv.LinkedAccount = user;
try { try {
prods = _context.Products.Where(x => sinv.ProdQuant.Select(x => x.Key).Contains(x.Id)).ToList(); prods = _context.Products.Where(x => sinv.ProdQuant.Select(x => x.Key).Contains(x.Id)).ToList();
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(8, e.Message); _logger.LogError(8, e.Message);
return BadRequest(); return BadRequest();
} }
@ -158,8 +166,7 @@ public class InvoiceController : Controller {
inventProd.Status = inventProd.Status == ProductModel.States.Clearance ? inventProd.Status = inventProd.Status == ProductModel.States.Clearance ?
ProductModel.States.Discontinued : ProductModel.States.Discontinued :
ProductModel.States.BackOrder; ProductModel.States.BackOrder;
} } else inventProd.Quantity -= prod.Value;
else inventProd.Quantity -= prod.Value;
inventProd.LastSale = DateTime.Now; inventProd.LastSale = DateTime.Now;
inventProd.Sales += prod.Value; inventProd.Sales += prod.Value;
} }
@ -172,8 +179,7 @@ public class InvoiceController : Controller {
_context.Invoices.Add(inv); _context.Invoices.Add(inv);
_context.Products.UpdateRange(prods); _context.Products.UpdateRange(prods);
_context.SaveChanges(); _context.SaveChanges();
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(8, e.Message); _logger.LogError(8, e.Message);
return BadRequest(e.InnerException.Message); return BadRequest(e.InnerException.Message);
} }
@ -190,16 +196,14 @@ public class InvoiceController : Controller {
try { // Trouver la commande. try { // Trouver la commande.
inv = _context.Invoices.Where(x => x.Id == id) inv = _context.Invoices.Where(x => x.Id == id)
.Include("Product").First(); .Include("Product").First();
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(8, e.Message); _logger.LogError(8, e.Message);
return BadRequest(); return BadRequest();
} }
try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver. try { // Trouver les rôles de l'utilisateur, assumer non-admin si impossible à trouver.
roles = await _userMan.GetRolesAsync(await _userMan.GetUserAsync(_signInMan.Context.User)); roles = await _userMan.GetRolesAsync(await _userMan.GetUserAsync(_signInMan.Context.User));
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(10, e.Message); _logger.LogError(10, e.Message);
roles = new List<string>(); roles = new List<string>();
} }
@ -231,8 +235,7 @@ public class InvoiceController : Controller {
try { try {
_context.Update(inv); _context.Update(inv);
_context.SaveChanges(); _context.SaveChanges();
} } catch (Exception e) {
catch (Exception e) {
_logger.LogError(8, e.Message); _logger.LogError(8, e.Message);
return BadRequest(); return BadRequest();
} }

View File

@ -40,13 +40,15 @@ public class UserController : Controller {
#region API Methods #region API Methods
[HttpPost, AllowAnonymous] [HttpPost, AllowAnonymous]
public ActionResult<ReturnUserViewModel> Post(SignUpUserModel sign) { public ActionResult<ReturnUserViewModel> Post(SignUpUserModel sign) {
int x = 0;
InventoryUser usr; InventoryUser usr;
try { try {
usr = new() { usr = new() {
FirstName = sign.FirstName, FirstName = sign.FirstName,
LastName = sign.LastName, LastName = sign.LastName,
UserName = sign.FirstName + sign.LastName,
NormalizedUserName = (sign.FirstName + sign.LastName).ToUpper(),
Email = sign.Email, Email = sign.Email,
NormalizedEmail = sign.Email.ToUpper(),
PhoneNumber = sign.Phone PhoneNumber = sign.Phone
}; };
} catch (Exception e){ } catch (Exception e){
@ -54,9 +56,10 @@ public class UserController : Controller {
} }
try { try {
usr.Adresses = new();
usr.Adresses.Add(new AddressModel() { usr.Adresses.Add(new AddressModel() {
CivicNumber = sign.CivicNumber, CivicNumber = sign.CivicNumber,
Appartment = sign.Appartment, Appartment = sign.Appartment is not null && sign.Appartment != ""? sign.Appartment: null,
Street = sign.Street, Street = sign.Street,
City = sign.City, City = sign.City,
Province = sign.Province, Province = sign.Province,
@ -77,7 +80,6 @@ public class UserController : Controller {
t1.Wait(); t1.Wait();
var t2 = _userMan.AddToRoleAsync(usr, "Client"); var t2 = _userMan.AddToRoleAsync(usr, "Client");
t2.Wait(); t2.Wait();
} catch (Exception e) { } catch (Exception e) {
return BadRequest(e.Message); return BadRequest(e.Message);
} }

View File

@ -28,6 +28,9 @@ builder.Services.AddIdentityCore<InventoryUser>()
.AddRoles<IdentityRole>() .AddRoles<IdentityRole>()
.AddEntityFrameworkStores<InventoryContext>() .AddEntityFrameworkStores<InventoryContext>()
.AddSignInManager(); .AddSignInManager();
builder.Services.Configure<IdentityOptions>(o =>
o.User.RequireUniqueEmail = true);
builder.Services.AddAuthorization(); builder.Services.AddAuthorization();
builder.Services.AddAuthentication().AddIdentityCookies(); builder.Services.AddAuthentication().AddIdentityCookies();

View File

@ -65,6 +65,7 @@ const Topbar = () => {
S'inscrire S'inscrire
</Link> </Link>
} }
</Nav>
{user !== null && user.LoggedIn && {user !== null && user.LoggedIn &&
<Dropdown className="dropdown-gestion-container"> <Dropdown className="dropdown-gestion-container">
<Dropdown.Toggle className="dropdown-gestion" > <Dropdown.Toggle className="dropdown-gestion" >
@ -95,7 +96,7 @@ const Topbar = () => {
<Container> <Container>
<Dropdown.Divider /> <Dropdown.Divider />
<Dropdown.ItemText> <Dropdown.ItemText>
Gestion <b>Gestion</b>
</Dropdown.ItemText> </Dropdown.ItemText>
<Dropdown.Item> <Dropdown.Item>
<Link className="nav-link" to="/inventaire" > <Link className="nav-link" to="/inventaire" >
@ -122,7 +123,6 @@ const Topbar = () => {
</Dropdown.Menu> </Dropdown.Menu>
</Dropdown> </Dropdown>
} }
</Nav>
<CartButton/> <CartButton/>
</Navbar.Collapse> </Navbar.Collapse>
</Container> </Container>

View File

@ -5,7 +5,7 @@ import Cookies from "universal-cookie";
const Login = () => { const Login = () => {
const [rememberme, setPersistence] = useState(true); const [rememberme, setPersistence] = useState(false);
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [returnmess, returnMessage] = useState(""); const [returnmess, returnMessage] = useState("");
@ -81,6 +81,13 @@ const Login = () => {
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} /> onChange={(e) => setPassword(e.target.value)} />
</div> </div>
<div className="form-group" styles="display:flex;">
<label>Se souvenir de moi
<input type="checkbox"
value={rememberme}
onChange={(e) => setPersistence(!rememberme)} />
</label>
</div>
<Button className="btn-primary btn-ajouter-morceau" type="submit" >Connexion</Button> <Button className="btn-primary btn-ajouter-morceau" type="submit" >Connexion</Button>
</form> </form>
</div> </div>

View File

@ -1,38 +1,26 @@
import { useState } from "react"; import { useState } from "react";
import { Button } from "react-bootstrap"; import { Button } from "react-bootstrap";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
// const Register = () => { const Register = () => {
const mySwal = withReactContent(Swal);
// //const [username, setUsername] = useState("");
// //const [password, setPassword] = useState("");
// // const handleLogin = async (e) => {
// // e.preventDefault();
// // const response = await fetch(`https://localhost:7292/api/Login?rememberme=true`, {
// // method: 'POST',
// // headers: {
// // 'Accept': 'application/json',
// // 'Content-Type': 'application/json'
// // },
// // //body: JSON.stringify({ username, password })
// // })
// // Partie de display d'erreur ou de redirection (faudrait checker pour se faire un state de connexion).
// }
export default function App() {
const { register, handleSubmit, watch, formState: { errors } } = useForm(); const { register, handleSubmit, watch, formState: { errors } } = useForm();
const onSubmit = data => { const onSubmit = data => {
const response = fetch(`https://localhost:7292/api/User`, { fetch(`https://localhost:7292/api/User`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Accept': 'text/json', 'Accept': 'text/json',
'Content-Type': 'text/json' 'Content-Type': 'text/json'
}, },
body: JSON.stringify(data) body: JSON.stringify(data)
}).then((response) => {
if (response.ok)
mySwal.fire({
text: 'Vous vous êtes incrit avec succès!',
confirmButtonText: 'Ok'
}).then((response) => window.location.href = "/login");
}) })
} }
@ -43,34 +31,76 @@ return (
<div className="Error_color"> <div className="Error_color">
<div className="form-group"> <div className="form-group">
<label>Prénom: </label> <label>Prénom: </label>
<input placeholder="Votre prénom:" {...register("Prénom", { required: true, minLength: 2})} /> <input placeholder="Votre prénom:" {...register("FirstName", { required: true, minLength: 2})} />
</div> </div>
<div> <div>
{errors.Prénom && errors.Prénom.type === 'required' && <span>Vous devez entrer votre prénom!</span>} {errors.FirstName && errors.FirstName.type === 'required' && <span>Vous devez entrer votre prénom!</span>}
{errors.Prénom && errors.Prénom.type === 'minLength' && <span>Votre prénom doit avoir au moins 2 lettres!</span>} {errors.FirstName && errors.FirstName.type === 'minLength' && <span>Votre prénom doit avoir au moins 2 lettres!</span>}
</div> </div>
<div className="form-group"> <div className="form-group">
<label>Nom: </label> <label>Nom: </label>
<input placeholder="Votre nom:" {...register("Nom", { required: true, minLength: 2})} /> <input placeholder="Votre nom:" {...register("LastName", { required: true, minLength: 2})} />
</div> </div>
<div> <div>
{errors.Nom && errors.Nom.type === 'required' && <span>Vous devez entrer votre nom!</span>} {errors.LastName && errors.LastName.type === 'required' && <span>Vous devez entrer votre nom!</span>}
{errors.Nom && errors.Nom.type === 'minLength' && <span>Votre nom doit avoir au moins 2 lettres!</span>} {errors.LastName && errors.LastName.type === 'minLength' && <span>Votre nom doit avoir au moins 2 lettres!</span>}
</div> </div>
<div className="form-group"> <div className="form-group">
<label>Numéro de téléphone: </label> <label>Numéro de téléphone: </label>
<input placeholder="Exemple: 111-111-1111" {...register("Téléphone", { required: true, pattern: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ })} /> <input placeholder="Exemple: 111-111-1111" {...register("Phone", { required: true, pattern: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ })} />
</div> </div>
<div> <div>
{errors.Téléphone && errors.Téléphone.type === 'required' && <span>Vous devez entrer un numéro de téléphone!</span>} {errors.Phone && errors.Phone.type === 'required' && <span>Vous devez entrer un numéro de téléphone!</span>}
{errors.Téléphone && errors.Téléphone.type === 'pattern' && <span>Téléphone non valide!</span>} {errors.Phone && errors.Phone.type === 'pattern' && <span>Téléphone non valide!</span>}
</div> </div>
<div className="form-group"> <div className="form-group">
<label>Adresse civique: </label> <label>Numéro civique: </label>
<input placeholder="Votre adresse:" {...register("Adresse", { required: true })} /> <input placeholder="Votre numéro civique:" {...register("CivicNumber", { required: true })} />
</div> </div>
<div> <div>
{errors.Adresse && errors.Adresse.type === 'required' && <span>Vous devez entrer une adresse!</span>} {errors.CivicNumber && errors.CivicNumber.type === 'required' && <span>Vous devez entrer un numéro civique!</span>}
</div>
<div className="form-group">
<label>Appartement: </label>
<input placeholder="Votre identifiant d'appartement:" {...register("Appartment")} />
</div>
<div>
</div>
<div className="form-group">
<label>Rue: </label>
<input placeholder="Votre rue:" {...register("Street", { required: true })} />
</div>
<div>
{errors.Street && errors.Street.type === 'required' && <span>Vous devez entrer une rue!</span>}
</div>
<div className="form-group">
<label>Ville: </label>
<input placeholder="Votre ville:" {...register("City", { required: true })} />
</div>
<div>
{errors.City && errors.City.type === 'required' && <span>Vous devez entrer une vile!</span>}
</div>
<div className="form-group">
<label>Province: </label>
<input placeholder="Votre province:" {...register("Province", { required: true })} />
</div>
<div>
{errors.Province && errors.Province.type === 'required' && <span>Vous devez entrer une province!</span>}
</div>
<div className="form-group">
<label>Pays: </label>
<input placeholder="Votre pays:" {...register("Country", { required: true })} />
</div>
<div>
{errors.Country && errors.Country.type === 'required' && <span>Vous devez entrer un pays!</span>}
</div>
<div className="form-group">
<label>Code Postal: </label>
<input placeholder="Votre code postal:" {...register("PostalCode", { required: true })} />
</div>
<div>
{errors.PostalCode && errors.PostalCode.type === 'required' && <span>Vous devez entrer un code postal!</span>}
</div> </div>
<div className="form-group"> <div className="form-group">
<label>Adresse courriel: </label> <label>Adresse courriel: </label>
@ -82,15 +112,11 @@ return (
</div> </div>
<div className="form-group"> <div className="form-group">
<label>Mot de passe: </label> <label>Mot de passe: </label>
<input placeholder="Mot de passe..." {...register("MotPasse", { required: true, minLength: 5})} /> <input placeholder="Mot de passe..." {...register("Password", { required: true, minLength: 5})} />
</div> </div>
<div> <div>
{errors.MotPasse && errors.MotPasse.type === 'required' && <span>Vous devez entrer un mot de passe!</span>} {errors.Password && errors.Password.type === 'required' && <span>Vous devez entrer un mot de passe!</span>}
{errors.MotPasse && errors.MotPasse.type === 'minLength' && <span>Votre mot de passe doit avoir au moins 5 caractères!</span>} {errors.Password && errors.Password.type === 'minLength' && <span>Votre mot de passe doit avoir au moins 5 caractères!</span>}
</div>
<div className="form-group">
<label>Pour un acount admin, entrer le mot de passe. Sinon laisser vide: </label>
<input placeholder="Mot de passe admin..." {...register("MotPasseAdmin", { minLength: 0})} />
</div> </div>
</div> </div>
<Button className="btn-primary btn-ajouter-morceau" type="submit" >Confirmer</Button> <Button className="btn-primary btn-ajouter-morceau" type="submit" >Confirmer</Button>
@ -98,3 +124,5 @@ return (
</div> </div>
) )
} }
export default Register;