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
[EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"),
Authorize(AuthenticationSchemes = "Identity.Application")]
Authorize(AuthenticationSchemes = "Identity.Application", Roles ="Client, Administrateur")]
public class AddressController : Controller {
#region DI Fields
private readonly ILogger<AddressController> _logger;

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@ import Cookies from "universal-cookie";
const Login = () => {
const [rememberme, setPersistence] = useState(true);
const [rememberme, setPersistence] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [returnmess, returnMessage] = useState("");
@ -81,6 +81,13 @@ const Login = () => {
value={password}
onChange={(e) => setPassword(e.target.value)} />
</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>
</form>
</div>

View File

@ -1,39 +1,27 @@
import { useState } from "react";
import { Button } from "react-bootstrap";
import { useForm } from "react-hook-form";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
// const Register = () => {
// //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 = () => {
const mySwal = withReactContent(Swal);
const { register, handleSubmit, watch, formState: { errors } } = useForm();
const onSubmit = data => {
const response = fetch(`https://localhost:7292/api/User`, {
fetch(`https://localhost:7292/api/User`, {
method: 'POST',
headers: {
'Accept': 'text/json',
'Content-Type': 'text/json'
},
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");
})
}
return (
@ -43,34 +31,76 @@ return (
<div className="Error_color">
<div className="form-group">
<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>
{errors.Prénom && errors.Prénom.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 === 'required' && <span>Vous devez entrer votre prénom!</span>}
{errors.FirstName && errors.FirstName.type === 'minLength' && <span>Votre prénom doit avoir au moins 2 lettres!</span>}
</div>
<div className="form-group">
<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>
{errors.Nom && errors.Nom.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 === 'required' && <span>Vous devez entrer votre nom!</span>}
{errors.LastName && errors.LastName.type === 'minLength' && <span>Votre nom doit avoir au moins 2 lettres!</span>}
</div>
<div className="form-group">
<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>
{errors.Téléphone && errors.Télé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 === 'required' && <span>Vous devez entrer un numéro de téléphone!</span>}
{errors.Phone && errors.Phone.type === 'pattern' && <span>Téléphone non valide!</span>}
</div>
<div className="form-group">
<label>Adresse civique: </label>
<input placeholder="Votre adresse:" {...register("Adresse", { required: true })} />
<label>Numéro civique: </label>
<input placeholder="Votre numéro civique:" {...register("CivicNumber", { required: true })} />
</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 className="form-group">
<label>Adresse courriel: </label>
@ -82,15 +112,11 @@ return (
</div>
<div className="form-group">
<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>
{errors.MotPasse && errors.MotPasse.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>}
</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})} />
{errors.Password && errors.Password.type === 'required' && <span>Vous devez entrer un mot de passe!</span>}
{errors.Password && errors.Password.type === 'minLength' && <span>Votre mot de passe doit avoir au moins 5 caractères!</span>}
</div>
</div>
<Button className="btn-primary btn-ajouter-morceau" type="submit" >Confirmer</Button>
@ -98,3 +124,5 @@ return (
</div>
)
}
export default Register;