Cleanup and re-align the controllers to the new database

This commit is contained in:
2025-06-29 22:03:13 -07:00
parent 94190a18dc
commit 1dc5a8cd7f
7 changed files with 283 additions and 308 deletions
@@ -8,39 +8,32 @@ using MistoxWebsite.Server.Entities;
namespace MistoxWebsite.Server.Controllers { namespace MistoxWebsite.Server.Controllers {
[ApiController] [ApiController]
public class AuthenticationController : ControllerBase { [Route("api/account/[controller]")]
public class AuthenticationController : MistoxControllerBase {
DatabaseService _accountContext;
EmailService _emailContext; EmailService _emailContext;
public AuthenticationController(DatabaseService DatabaseContext, EmailService emailContext) { public AuthenticationController(DatabaseService db, EmailService emailContext) : base(db) {
_accountContext = DatabaseContext;
_emailContext = emailContext; _emailContext = emailContext;
} }
[Route("api/account/login")] [Route("login")]
[HttpPost] [HttpPost]
public async Task<ActionResult<Account>> Login([FromForm] string UserName, [FromForm] string PasswordHash, [FromForm] bool StayLoggedIn) { public async Task<ActionResult<Account>> Login([FromForm] string UserName, [FromForm] string PasswordHash, [FromForm] bool StayLoggedIn) {
try { try {
Account? test = await _accountContext.GetAccount(UserName.ToLower()); Account? test = await _databaseService.GetAccount(UserName.ToLower());
if (test != null) { if (test != null) {
if (test.EmailVerified == true) { if (test.EmailVerified == true) {
if (test.SiteData.FailedPasswordLock) { if (test.FailedPasswordLock) {
if (test.SiteData.CurrentPasswordAttempts >= test.SiteData.PasswordAttempts) { if (test.CurrentPasswordAttempts >= test.PasswordAttempts) {
return new Account() { Error = "Too many failed password attempts. Please reset your password" }; return new Account() { Error = "Too many failed password attempts. Please reset your password" };
} }
} }
if (BCrypt.Net.BCrypt.Verify(PasswordHash, test.PasswordHash)) { if (BCrypt.Net.BCrypt.Verify(PasswordHash, test.PasswordHash)) {
test.SiteData.CurrentPasswordAttempts = 0; test.CurrentPasswordAttempts = 0;
await _accountContext.SetAccount(test); await _databaseService.SetAccount(test);
AccountClaims aClaims = await getClaims(test.ID);
List<Claim> claims = new List<Claim>() { List<Claim> claims = new List<Claim>() {
new Claim(ClaimTypes.Name, aClaims.UserName),
new Claim(ClaimTypes.Email, aClaims.Email),
new Claim("emailverified", aClaims.EmailVerified),
new Claim(ClaimTypes.Role, aClaims.Role),
new Claim("LockAccount", aClaims.FailedPasswordLock),
new Claim("ID", test.ID.ToString()) new Claim("ID", test.ID.ToString())
}; };
@@ -55,8 +48,8 @@ namespace MistoxWebsite.Server.Controllers {
return test; return test;
} }
else { else {
test.SiteData.CurrentPasswordAttempts += 1; test.CurrentPasswordAttempts += 1;
await _accountContext.SetAccount(test); await _databaseService.SetAccount(test);
return new Account() { Error = "Wrong password" }; return new Account() { Error = "Wrong password" };
} }
} }
@@ -71,58 +64,21 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/session")] [Route("register")]
[HttpPost]
public async Task<ActionResult<Account>> LoginSession([FromBody] Account request) {
try {
Account? test = await _accountContext.GetAccount(request.UserName.ToLower());
if (test != null) {
if (request.PasswordHash == test.PasswordHash) {
return test;
}
else {
test.SiteData.CurrentPasswordAttempts += 1;
await _accountContext.SetAccount(test);
return new Account() { Error = "Wrong password" };
}
}
return new Account() { Error = "User doesn't exist" };
} catch (Exception ex) {
return new Account() { Error = ex.Message };
}
}
[Route("api/account/claims")]
[HttpPost]
public async Task<ActionResult<AccountClaims>> Claims([FromBody] Account Account) {
AccountClaims claims = await getClaims(Account.ID);
return claims;
}
[Route("api/account/register")]
[HttpPost] [HttpPost]
public async Task<ActionResult<Account>> Register([FromForm] string Email, [FromForm] string UserName, [FromForm] string PasswordHash) { public async Task<ActionResult<Account>> Register([FromForm] string Email, [FromForm] string UserName, [FromForm] string PasswordHash) {
try { try {
if (await _accountContext.GetAccount(UserName.ToLower()) == null) { if (await _databaseService.GetAccount(UserName.ToLower()) == null) {
if (await _accountContext.GetAccount(Email.ToLower()) == null) { if (await _databaseService.GetAccount(Email.ToLower()) == null) {
Account? created = new Account() { Account? created = new Account() {
UserName = UserName.ToLower(), UserName = UserName.ToLower(),
Email = Email.ToLower(), Email = Email.ToLower(),
EmailVerified = false, EmailVerified = false,
PasswordHash = BCrypt.Net.BCrypt.HashPassword(PasswordHash), PasswordHash = BCrypt.Net.BCrypt.HashPassword(PasswordHash),
}; };
await _accountContext.NewAccount(created); await _databaseService.SetAccount(created);
created = await _accountContext.GetAccount(Email.ToLower()); created = await _databaseService.GetAccount(Email.ToLower());
if (created != null) { if (created != null) {
AccountClaims aClaims = await getClaims(created.ID);
List<Claim> claims = new List<Claim>() {
new Claim(ClaimTypes.Name, aClaims.UserName),
new Claim(ClaimTypes.Email, aClaims.Email),
new Claim("emailverified", aClaims.EmailVerified),
new Claim(ClaimTypes.Role, aClaims.Role),
new Claim("LockAccount", aClaims.FailedPasswordLock)
};
await SendVerify(created.UserName); await SendVerify(created.UserName);
return created; return created;
} }
@@ -142,16 +98,16 @@ namespace MistoxWebsite.Server.Controllers {
} }
[Route("api/account/changepassword")] [Route("changepassword")]
[HttpPost] [HttpPost]
public async Task<ActionResult<bool>> ChangePassword([FromForm]string UserName, [FromForm]string OldPassword, [FromForm]string NewPassword) { public async Task<ActionResult<bool>> ChangePassword([FromForm] string OldPassword, [FromForm] string NewPassword) {
try { try {
Account? test = await _accountContext.GetAccount(UserName.ToLower()); if (isLoggedIn()) {
if (test != null) { Account user = await getLoggedInUser();
if (BCrypt.Net.BCrypt.Verify(OldPassword, test.PasswordHash)) { if (BCrypt.Net.BCrypt.Verify(OldPassword, user.PasswordHash)) {
test.PasswordHash = BCrypt.Net.BCrypt.HashPassword(NewPassword); user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(NewPassword);
test.SiteData.CurrentPasswordAttempts = 0; user.CurrentPasswordAttempts = 0;
await _accountContext.SetAccount(test); await _databaseService.SetAccount(user);
return true; return true;
} }
} }
@@ -161,15 +117,15 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/toggleAccountLock")] [Route("toggleaccountlock")]
[HttpPost] [HttpPost]
public async Task<ActionResult<string>> ToggleAccountLock([FromForm]string UserName, [FromForm]bool AccountLock) { public async Task<ActionResult<string>> ToggleAccountLock([FromForm] bool AccountLock) {
try { try {
Account? test = await _accountContext.GetAccount(UserName); if (isLoggedIn()) {
if (test != null) { Account user = await getLoggedInUser();
test.SiteData.FailedPasswordLock = AccountLock; user.FailedPasswordLock = AccountLock;
test.SiteData.CurrentPasswordAttempts = 0; user.CurrentPasswordAttempts = 0;
await _accountContext.SetAccount(test); await _databaseService.SetAccount(user);
return "Account Lock Status Updated"; return "Account Lock Status Updated";
} }
return "Unknown Error Occurred"; return "Unknown Error Occurred";
@@ -178,18 +134,12 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/get")] [Route("get")]
[HttpPost] [HttpPost]
public async Task<ActionResult<Account?>> Get() { public async Task<ActionResult<Account?>> Get() {
try { try {
if (User.Identity != null && User.Identity.IsAuthenticated) { if (isLoggedIn()) {
string? email = User.FindFirstValue(ClaimTypes.Email); return await getLoggedInUser();
if (!string.IsNullOrEmpty(email)) {
Account? test = await _accountContext.GetAccount(email);
if (test != null) {
return test;
}
}
} }
return Ok(); return Ok();
} catch { } catch {
@@ -197,15 +147,15 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/logout")] [Route("logout")]
[HttpPost] [HttpPost]
public async Task Logout() { public async Task Logout() {
await HttpContext.SignOutAsync(); await HttpContext.SignOutAsync();
} }
[Route("api/account/sendverifyemail")] [Route("sendverifyemail")]
[HttpPost] [HttpPost]
public async Task<ActionResult<string>> SendVerify([FromForm]string UserName) { public async Task<ActionResult<string>> SendVerify([FromForm] string UserName) {
try { try {
string key = "v" + UserName; string key = "v" + UserName;
// Stop from sending multiple emails quickly // Stop from sending multiple emails quickly
@@ -218,15 +168,15 @@ namespace MistoxWebsite.Server.Controllers {
_emailContext._SentEmails.Remove(key); _emailContext._SentEmails.Remove(key);
} }
} }
Account? test = await _accountContext.GetAccount(UserName.ToLower()); Account? test = await _databaseService.GetAccount(UserName.ToLower());
if (test != null) { if (test != null) {
test.SiteData.EmailToken = Guid.NewGuid().ToString(); test.EmailToken = Guid.NewGuid().ToString();
await _accountContext.SetAccount(test); await _databaseService.SetAccount(test);
string EmailContents = EmailService.VerifyEmailEmail; string EmailContents = EmailService.VerifyEmailEmail;
EmailContents = Substitue(EmailContents, "@UserName", UserName); EmailContents = Substitue(EmailContents, "@UserName", UserName);
EmailContents = Substitue(EmailContents, "@UserName", UserName); EmailContents = Substitue(EmailContents, "@UserName", UserName);
EmailContents = Substitue(EmailContents, "@VerifyPassword", test.SiteData.EmailToken); EmailContents = Substitue(EmailContents, "@VerifyPassword", test.EmailToken);
string result = _emailContext.Send(test.Email, EmailService.VerifyEmailSubject, EmailContents); string result = _emailContext.Send(test.Email, EmailService.VerifyEmailSubject, EmailContents);
_emailContext._SentEmails.Add(key, DateTime.Now); _emailContext._SentEmails.Add(key, DateTime.Now);
@@ -238,16 +188,16 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/verifyemail")] [Route("verifyemail")]
[HttpPost] [HttpPost]
public async Task<ActionResult<bool>> VerifyEmail([FromForm]string UserName, [FromForm]string EmailToken) { public async Task<ActionResult<bool>> VerifyEmail([FromForm] string UserName, [FromForm] string EmailToken) {
try { try {
Account? test = await _accountContext.GetAccount(UserName.ToLower()); Account? test = await _databaseService.GetAccount(UserName.ToLower());
if (test != null) { if (test != null) {
if (test.SiteData.EmailToken == EmailToken) { if (!string.IsNullOrEmpty(test.EmailToken) && test.EmailToken == EmailToken) {
test.SiteData.EmailToken = ""; test.EmailToken = "";
test.EmailVerified = true; test.EmailVerified = true;
await _accountContext.SetAccount(test); await _databaseService.SetAccount(test);
return true; return true;
} }
} }
@@ -257,7 +207,7 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/sendresetpassword")] [Route("sendresetpassword")]
[HttpPost] [HttpPost]
public async Task<ActionResult<string>> ResetPassword([FromForm] string Email) { public async Task<ActionResult<string>> ResetPassword([FromForm] string Email) {
try { try {
@@ -272,15 +222,15 @@ namespace MistoxWebsite.Server.Controllers {
_emailContext._SentEmails.Remove(key); _emailContext._SentEmails.Remove(key);
} }
} }
Account? test = await _accountContext.GetAccount(Email.ToLower()); Account? test = await _databaseService.GetAccount(Email.ToLower());
if (test != null) { if (test != null) {
test.SiteData.EmailToken = Guid.NewGuid().ToString(); test.EmailToken = Guid.NewGuid().ToString();
await _accountContext.SetAccount(test); await _databaseService.SetAccount(test);
string EmailContents = EmailService.ResetPasswordEmail; string EmailContents = EmailService.ResetPasswordEmail;
EmailContents = Substitue(EmailContents, "@UserName", test.UserName); EmailContents = Substitue(EmailContents, "@UserName", test.UserName);
EmailContents = Substitue(EmailContents, "@UserName", test.UserName); EmailContents = Substitue(EmailContents, "@UserName", test.UserName);
EmailContents = Substitue(EmailContents, "@ResetPassWord", test.SiteData.EmailToken); EmailContents = Substitue(EmailContents, "@ResetPassWord", test.EmailToken);
string result = _emailContext.Send(test.Email, EmailService.VerifyEmailSubject, EmailContents); string result = _emailContext.Send(test.Email, EmailService.VerifyEmailSubject, EmailContents);
_emailContext._SentEmails.Add(key, DateTime.Now); _emailContext._SentEmails.Add(key, DateTime.Now);
@@ -288,22 +238,23 @@ namespace MistoxWebsite.Server.Controllers {
} }
return "Account Not Found"; return "Account Not Found";
} catch (Exception e) { } catch (Exception e) {
Console.WriteLine( "EmailService Error: " + e.ToString()); Console.WriteLine("EmailService Error: " + e.ToString());
return "The connection couldn't be established to the email server"; return "The connection couldn't be established to the email server";
} }
} }
[Route("api/account/resetpassword")] [Route("resetpassword")]
[HttpPost] [HttpPost]
public async Task<ActionResult<bool>> ResetPwdVerify([FromForm] string UserName, [FromForm] string NewPassword, [FromForm] string ResetToken) { public async Task<ActionResult<bool>> ResetPwdVerify([FromForm] string UserName, [FromForm] string NewPassword, [FromForm] string ResetToken) {
try { try {
Account? test = await _accountContext.GetAccount(UserName.ToLower()); Account? test = await _databaseService.GetAccount(UserName.ToLower());
if (test != null && !string.IsNullOrEmpty(test.SiteData.EmailToken)) { if (test != null && !string.IsNullOrEmpty(test.EmailToken)) {
if (test.SiteData.EmailToken == ResetToken) { if (!string.IsNullOrEmpty(test.EmailToken) && test.EmailToken == ResetToken) {
test.SiteData.CurrentPasswordAttempts = 0; test.CurrentPasswordAttempts = 0;
test.EmailToken = "";
test.PasswordHash = BCrypt.Net.BCrypt.HashPassword(NewPassword); test.PasswordHash = BCrypt.Net.BCrypt.HashPassword(NewPassword);
await _accountContext.SetAccount(test); await _databaseService.SetAccount(test);
return true; return true;
} }
} }
@@ -313,14 +264,14 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/account/delete")] [Route("delete")]
[HttpPost] [HttpPost]
public async Task<ActionResult<bool>> delete([FromForm]string UserName, [FromForm]string Password) { public async Task<ActionResult<bool>> delete([FromForm] string Password) {
try { try {
Account? test = await _accountContext.GetAccount(UserName.ToLower()); if (isLoggedIn()) {
if (test != null) { Account user = await getLoggedInUser();
if (BCrypt.Net.BCrypt.Verify(Password, test.PasswordHash)) { if (BCrypt.Net.BCrypt.Verify(Password, user.PasswordHash)) {
await _accountContext.DeleteAccount(test); await _databaseService.DeleteAccount(user.ID);
return true; return true;
} }
} }
@@ -330,37 +281,5 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
// Helper Functions
string Substitue(string message, string subString, string Replacement) {
for (int i = 0; i < (message.Length - subString.Length); i++) {
if (message.Substring(i, subString.Length) == subString) {
string before = message.Substring(0, i);
string after = message.Substring(i + subString.Length);
return before + Replacement + after;
}
}
return message;
}
async Task<AccountClaims> getClaims(int AccountID) {
try {
Account? test = await _accountContext.GetAccountByID(AccountID);
if (test != null) {
AccountClaims aClaims = new AccountClaims() {
UserName = test.UserName,
Email = test.Email,
Role = test.SiteData.Role
};
aClaims.EmailVerified = test.EmailVerified ? "1" : "0";
aClaims.FailedPasswordLock = test.SiteData.FailedPasswordLock ? "1" : "0";
return aClaims;
}
return new AccountClaims();
} catch {
return new AccountClaims();
}
}
} }
} }
@@ -0,0 +1,69 @@
using Microsoft.AspNetCore.Mvc;
using MistoxWebsite.Server.Entities;
using MistoxWebsite.Server.Services.DatabaseService;
namespace MistoxWebsite.Server.Controllers {
[ApiController]
[Route("api/cart/[controller]")]
public class CartController : MistoxControllerBase {
CartController(DatabaseService db) : base(db) { }
[Route("get")]
[HttpPost]
public async Task<ActionResult<Cart[]>> GetCart() {
try {
if (isLoggedIn()) {
return Ok(await _databaseService.GetCart(getLoggedInUserID()));
}
return StatusCode(500);
} catch {
return StatusCode(500);
}
}
[Route("add")]
[HttpPost]
public async Task<IActionResult> AddCart([FromBody] Cart cart) {
try {
if (isLoggedIn()) {
cart.AccountID = getLoggedInUserID();
await _databaseService.AddToCart(cart);
return Ok();
}
return StatusCode(500);
} catch {
return StatusCode(500);
}
}
[Route("remove")]
[HttpPost]
public async Task<IActionResult> RemoveCart([FromBody] Cart cart) {
try {
if (isLoggedIn()) {
cart.AccountID = getLoggedInUserID();
await _databaseService.RemoveFromCart(cart);
return Ok();
}
return StatusCode(500);
} catch {
return StatusCode(500);
}
}
[Route("clear")]
[HttpPost]
public async Task<IActionResult> ClearCart() {
try {
if (isLoggedIn()) {
await _databaseService.ClearCart(getLoggedInUserID());
return Ok();
}
return StatusCode(500);
} catch {
return StatusCode(500);
}
}
}
}
@@ -0,0 +1,60 @@
using Microsoft.AspNetCore.Mvc;
using MistoxWebsite.Server.Entities;
using MistoxWebsite.Server.Services.DatabaseService;
namespace MistoxWebsite.Server.Controllers {
public class MistoxControllerBase : ControllerBase {
public DatabaseService _databaseService;
public MistoxControllerBase(DatabaseService databaseService) {
_databaseService = databaseService;
}
public bool isLoggedIn() {
if (User.Identity != null && User.Identity.IsAuthenticated) {
return true;
}
return false;
}
public int getLoggedInUserID() {
return Convert.ToInt32(User.FindFirst("ID")?.Value);
}
public async Task<Account> getLoggedInUser() {
try {
Account? test = await _databaseService.GetAccount(getLoggedInUserID());
if (test != null) {
return test;
}
return new Account();
} catch {
return new Account();
}
}
public string Substitue(string message, string subString, string Replacement) {
for (int i = 0; i < (message.Length - subString.Length); i++) {
if (message.Substring(i, subString.Length) == subString) {
string before = message.Substring(0, i);
string after = message.Substring(i + subString.Length);
return before + Replacement + after;
}
}
return message;
}
public bool contains(string outer, string inner) {
if (outer.Length >= inner.Length) {
for (int i = 0; i < outer.Length - inner.Length; i++) {
if (outer.Substring(i, inner.Length) == inner) {
return true;
}
}
}
return false;
}
}
}
@@ -5,14 +5,12 @@ using MistoxWebsite.Server.Entities;
namespace MistoxWebsite.Server.Controllers { namespace MistoxWebsite.Server.Controllers {
[ApiController] [ApiController]
public class PaymentController : ControllerBase { [Route("api/payment/[controller]")]
public class PaymentController : MistoxControllerBase {
DatabaseService _databaseService;
IPayment _paymentService; IPayment _paymentService;
public PaymentController(DatabaseService databaseService) { public PaymentController(DatabaseService db) : base(db) {
_databaseService = databaseService;
if (IPayment._PaymentType == PaymentType.StripeIntent) { if (IPayment._PaymentType == PaymentType.StripeIntent) {
_paymentService = new StripeIntent(_databaseService); _paymentService = new StripeIntent(_databaseService);
} else { } else {
@@ -20,17 +18,15 @@ namespace MistoxWebsite.Server.Controllers {
_paymentService = new StripeIntent(_databaseService); _paymentService = new StripeIntent(_databaseService);
} }
// Add new payment plugins here // Add new payment plugins here
} }
[Route("api/getCheckoutToken")] [Route("getcheckouttoken")]
[HttpPost] [HttpPost]
public async Task<string> GetPaymentKey( [FromQuery] string userID ) { public async Task<string> GetCheckoutToken() {
string OrderNumber = Guid.NewGuid().ToString().Substring(0,10); string OrderNumber = Guid.NewGuid().ToString().Substring(0, 10);
Account? acc = await _databaseService.GetAccount(userID); if (isLoggedIn()) {
if (acc != null) { Cart[] carts = await _databaseService.GetCart(getLoggedInUserID());
Cart[] carts = await _databaseService.GetCart(acc); (bool, string) PaymentResponse = await _paymentService.TryGetCheckoutToken(OrderNumber, getLoggedInUserID(), carts);
(bool, string) PaymentResponse = await _paymentService.TryGetCheckoutToken(OrderNumber, acc, carts);
if (PaymentResponse.Item1) { if (PaymentResponse.Item1) {
// Returns client secret // Returns client secret
return PaymentResponse.Item2; return PaymentResponse.Item2;
@@ -40,14 +36,13 @@ namespace MistoxWebsite.Server.Controllers {
Console.WriteLine("\n"); Console.WriteLine("\n");
return "An error has occured in the payment plugin"; return "An error has occured in the payment plugin";
} }
} else {
return "Unable to find account";
} }
return "You must be logged in";
} }
[Route("/api/payment/publickey")] [Route("getpublickey")]
[HttpGet] [HttpPost]
public IActionResult GetPaymentKey() { public IActionResult GetPublicKey() {
try { try {
return Ok(IPayment._PublicKey); return Ok(IPayment._PublicKey);
} catch (Exception ex) { } catch (Exception ex) {
@@ -55,7 +50,7 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("/api/payment/response")] [Route("response")]
[HttpPost] [HttpPost]
public async Task<IActionResult> paymentWebhook() { public async Task<IActionResult> paymentWebhook() {
try { try {
@@ -8,7 +8,7 @@ namespace MistoxWebsite.Server.Controllers.Payment {
public static string _EndpointSecret = ""; public static string _EndpointSecret = "";
public static string _PublicKey = ""; public static string _PublicKey = "";
public Task<(bool, string)> TryGetCheckoutToken(string OrderNumber, Account user, Cart[] cart); public Task<(bool, string)> TryGetCheckoutToken(string OrderNumber, int userID, Cart[] cart);
public Task ValidatePurchase(string WebHookData, string Headers); public Task ValidatePurchase(string WebHookData, string Headers);
} }
@@ -12,7 +12,7 @@ namespace MistoxWebsite.Server.Controllers {
_databaseService = databaseService; _databaseService = databaseService;
} }
public async Task<(bool, string)> TryGetCheckoutToken(string OrderNumber, Account user, Cart[] cart) { public async Task<(bool, string)> TryGetCheckoutToken(string OrderNumber, int userID, Cart[] cart) {
try { try {
// build Recipt and calculate Tax // build Recipt and calculate Tax
var options = new Stripe.Tax.CalculationCreateOptions { var options = new Stripe.Tax.CalculationCreateOptions {
@@ -60,7 +60,7 @@ namespace MistoxWebsite.Server.Controllers {
Currency = "usd", Currency = "usd",
Metadata = new Dictionary<string, string> { Metadata = new Dictionary<string, string> {
{ "ordernumber", OrderNumber }, { "ordernumber", OrderNumber },
{ "user", user.ID.ToString() }, { "user", userID.ToString() },
{ "products", csv }, { "products", csv },
{ "subtotal", subtotal.ToString() }, { "subtotal", subtotal.ToString() },
{ "total", result.AmountTotal.ToString() } { "total", result.AmountTotal.ToString() }
@@ -115,10 +115,7 @@ namespace MistoxWebsite.Server.Controllers {
} }
// Clear the cart // Clear the cart
Account account = new() { await _databaseService.ClearCart(userID);
ID = userID
};
await _databaseService.ClearCart(account);
// Add data to misox receipt // Add data to misox receipt
for (int i = 0; i < productIDs.Count; i++) { for (int i = 0; i < productIDs.Count; i++) {
@@ -1,63 +1,21 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MistoxWebsite.Server.Services.DatabaseService; using MistoxWebsite.Server.Services.DatabaseService;
using MistoxWebsite.Server.Entities; using MistoxWebsite.Server.Entities;
using System.Security.Claims;
using System.Threading.Tasks;
namespace MistoxWebsite.Server.Controllers { namespace MistoxWebsite.Server.Controllers {
[ApiController] [ApiController]
public class ProductController : ControllerBase { [Route("api/product/[controller]")]
public class ProductController : MistoxControllerBase {
DatabaseService _databaseService; public ProductController(DatabaseService db) : base(db) { }
public ProductController( DatabaseService databaseService ) { [Route("set")]
_databaseService = databaseService;
}
[Route( "api/cart/get" )]
[HttpPost] [HttpPost]
public async Task<Cart[]> GetCart( [FromBody] Account acc ) { public async Task<ActionResult<bool>> CreateProduct([FromForm] Product obj, [FromForm] IFormFile[] images) {
try {
return await _databaseService.GetCart( acc );
} catch {
return new Cart[0];
}
}
[Route( "api/cart/add" )]
[HttpPost]
public async Task AddCart( [FromBody] Cart cart ) {
try {
await _databaseService.AddToCart( cart );
}catch {
}
}
[Route( "api/cart/remove" )]
[HttpPost]
public async Task RemoveCart( [FromBody] Cart cart ) {
try {
await _databaseService.RemoveFromCart( cart );
} catch {
}
}
[Route( "api/cart/clear" )]
[HttpPost]
public async Task ClearCart( [FromBody] Account acc ) {
try {
await _databaseService.ClearCart( acc );
} catch {
}
}
[Route( "api/product/create" )]
[HttpPost]
public async Task<ActionResult<bool>> CreateProduct([FromForm] Product obj, [FromForm] List<IFormFile> images){
try { try {
if (isLoggedIn()) {
Account user = await getLoggedInUser();
if (user.Role == "Admin") {
List<ProductImage> building = new List<ProductImage>(); List<ProductImage> building = new List<ProductImage>();
foreach (var file in images) { foreach (var file in images) {
using (var stream = new MemoryStream()) { using (var stream = new MemoryStream()) {
@@ -70,33 +28,26 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
obj.Images = building.ToArray(); obj.Images = building.ToArray();
await _databaseService.NewProduct(obj); await _databaseService.SetProduct(obj);
return true; return true;
}
}
return false;
} catch (Exception e) { } catch (Exception e) {
Console.WriteLine(e); Console.WriteLine(e);
return false; return false;
} }
} }
[Route( "api/product/update" )] [Route("get")]
[HttpPost] [HttpPost]
public async Task<ActionResult<bool>> UpdateProduct( [FromBody] Product obj ) { public async Task<ActionResult<Product>> GetProduct([FromForm] int productID) {
try { try {
await _databaseService.UpdateProduct( obj ); Product? product = await _databaseService.GetProduct(productID);
return true; if (product != null) {
} catch { return product;
return false;
} }
} else {
[Route( "api/product/get" )]
[HttpPost]
public async Task<ActionResult<Product>> GetProduct( [FromForm] int productID ) {
try {
Product? x = await _databaseService.GetProduct(productID);
if (x != null) {
return x;
} else {
return NotFound(); return NotFound();
} }
} catch { } catch {
@@ -104,18 +55,7 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route( "api/product/delete" )] [Route("getall")]
[HttpPost]
public async Task<ActionResult<bool>> DeleteProduct( [FromForm] int productID ) {
try {
await _databaseService.DeleteProduct(productID);
return true;
} catch {
return false;
}
}
[Route("api/product/getall")]
[HttpPost] [HttpPost]
public async Task<Product[]> GetAllProducts() { public async Task<Product[]> GetAllProducts() {
try { try {
@@ -125,14 +65,32 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route( "api/productimage/get" )] [Route("delete")]
[HttpGet] [HttpPost]
public async Task<IActionResult> GetProductImage( int ProductID, int ImageID ) { public async Task<ActionResult<bool>> DeleteProduct([FromForm] int productID) {
try {
if (isLoggedIn()) {
Account user = await getLoggedInUser();
if (user.Role == "Admin") {
await _databaseService.DeleteProduct(productID);
return true;
}
}
return false;
} catch {
return false;
}
}
[Route("getimage")]
[HttpPost]
public async Task<IActionResult> GetProductImage([FromForm] int ProductID, [FromForm] int ImageID) {
try { try {
ProductImage? img = await _databaseService.GetImage(ProductID, ImageID); ProductImage? img = await _databaseService.GetImage(ProductID, ImageID);
if (img != null) { if (img != null) {
return File(img.Image, "Image/*"); return File(img.Image, "Image/*");
} else { }
else {
return NotFound(); return NotFound();
} }
} catch { } catch {
@@ -140,51 +98,30 @@ namespace MistoxWebsite.Server.Controllers {
} }
} }
[Route("api/product/getowned")] [Route("getowned")]
[HttpPost] [HttpPost]
public async Task<ActionResult<Receipt[]>> GetOwnedProduct() { public async Task<ActionResult<Receipt[]>> GetOwnedProduct() {
try { try {
if( User.Identity != null && User.Identity.IsAuthenticated ) { if (isLoggedIn()) {
string? email = User.FindFirstValue(ClaimTypes.Email); Receipt[] returned = await _databaseService.GetAllReceipts(getLoggedInUserID());
if( !string.IsNullOrEmpty( email ) ) {
Account? test = await _databaseService.GetAccount(email);
if( test != null ) {
Receipt[] returned = await _databaseService.GetAllReceipts(test);
return returned; return returned;
} }
}
}
return new Receipt[0]; return new Receipt[0];
} catch { } catch {
return new Receipt[0]; return new Receipt[0];
} }
} }
bool contains( string outer, string inner ) { [Route("download")]
if ( outer.Length >= inner.Length ) {
for ( int i=0; i<outer.Length-inner.Length; i++ ) {
if ( outer.Substring(i, inner.Length) == inner ) {
return true;
}
}
}
return false;
}
[Route( "api/product/download" )]
[HttpGet] [HttpGet]
public async Task<ActionResult> Download( [FromQuery] string Product ) { public async Task<ActionResult> Download([FromQuery] string Product) {
try { try {
if( User.Identity != null && User.Identity.IsAuthenticated ) { if (isLoggedIn()) {
string? email = User.FindFirstValue(ClaimTypes.Email);
if( !string.IsNullOrEmpty( email ) ) {
Account? user = await _databaseService.GetAccount(email);
if (user != null){
Product[] games = await _databaseService.GetAllProducts(); Product[] games = await _databaseService.GetAllProducts();
foreach( Product product in games ) { foreach (Product product in games) {
if ( contains( Product, product.URL ) ) { if (contains(Product, product.URL)) {
Receipt? receipt = await _databaseService.GetReceipt(user, product); Receipt? receipt = await _databaseService.GetReceipt(getLoggedInUserID(), product.ID);
if( receipt != null ) { if (receipt != null) {
//FileStream fileStream = new FileStream(_FolderRoot + Product, FileMode.Open, FileAccess.Read); //FileStream fileStream = new FileStream(_FolderRoot + Product, FileMode.Open, FileAccess.Read);
//return new FileStreamResult( fileStream, "application/octet-stream" ) { //return new FileStreamResult( fileStream, "application/octet-stream" ) {
// FileDownloadName = fileStream.Name // FileDownloadName = fileStream.Name
@@ -193,8 +130,6 @@ namespace MistoxWebsite.Server.Controllers {
break; break;
} }
} }
}
}
return Unauthorized(); return Unauthorized();
} }
return Unauthorized(); return Unauthorized();