Ejemplo n.º 1
0
        public async Task <IActionResult> Put([FromBody] Address modifiedAddress)
        {
            try
            {
                if (modifiedAddress != null)
                {
                    modifiedAddress.User = await _DbContext.Users.AsTracking().Include(u => u.Role)
                                           .Include(u => u.RegistrationMethod).SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User));
                }
                ModelState.Clear();
                if (!TryValidateModel(modifiedAddress))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                _DbContext.Addresses.Update(modifiedAddress);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(modifiedAddress));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] Newsletter newsletter)
        {
            try
            {
                if (_DbContext.Newsletters.Find(newsletter.Email) != null)
                {
                    return(Created("Success", "Thank you for your subscription."));
                }

                TryValidateModel(newsletter);
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                await _DbContext.Newsletters.AddAsync(newsletter).ConfigureAwait(false);

                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Created("Success", "Thank you for your subscription."));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 3
0
        /// Ready For Test
        public async Task <IActionResult> Post([FromBody] Coupon newCoupon)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                if (!newCoupon.IsValid(ref ErrorsList))
                {
                    return(UnprocessableEntity(ErrorsList));
                }
                if (await _DbContext.Coupons.AnyAsync(c => c.Code == newCoupon.Code)
                    .ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Coupon Code already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                await _DbContext.Coupons.AddAsync(newCoupon).ConfigureAwait(false);

                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Created("Success", newCoupon));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 4
0
        private async Task <IActionResult> PrivateCreateUser(User newUser)
        {
            try
            {
                newUser.PasswordHash = newUser.Password;
                if (newUser.RegistrationMethod.Type != RegistrationTypes.Application)
                {
                    newUser.PasswordHash   = CoreFunc.StringGenerator(40, 10, 10, 10, 10);
                    newUser.EmailConfirmed = true;
                }
                ModelState.Clear();
                if (!TryValidateModel(newUser))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }
                if (await _DbContext.Users.AnyAsync(u => u.NormalizedEmail == newUser.Email.ToUpper()).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "This email is already registered.");
                    return(StatusCode(412, ErrorsList));
                }

                newUser.Id = 0;
                IdentityResult newUserResult = await _UserManager.CreateAsync(newUser, newUser.PasswordHash)
                                               .ConfigureAwait(false);

                if (!newUserResult.Succeeded)
                {
                    foreach (var error in newUserResult.Errors)
                    {
                        CoreFunc.Error(ref ErrorsList, error.Description, error.Code);
                    }
                    return(StatusCode(417, ErrorsList));
                }
                IdentityResult addedClaimResult = await _UserManager.AddClaimAsync(
                    newUser,
                    new Claim(AppConst.AccessClaims.Type, newUser.Role.AccessClaim)
                    ).ConfigureAwait(false);

                if (!addedClaimResult.Succeeded)
                {
                    _DbContext.Users.Remove(newUser);
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                    CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, null, User));
                    return(StatusCode(417, ErrorsList));
                }
                await _UserManager.SetLockoutEnabledAsync(newUser, false);

                IsUserCreated = true;
                return(Created("Success", newUser));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 5
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> Put([FromBody] DeliveryOption modifiedDeliveryOption)
        {
            try
            {
                /// get the current category
                DeliveryOption currentDeliveryOption = await _DbContext.DeliveryOptions
                                                       .SingleOrDefaultAsync(c => c.Id == modifiedDeliveryOption.Id)
                                                       .ConfigureAwait(false);

                // if the current category does not exists
                if (currentDeliveryOption == null)
                {
                    CoreFunc.Error(ref ErrorsList, "Category Not Found");
                    return(NotFound(ErrorsList));
                }

                if (await _DbContext.DeliveryOptions
                    .AnyAsync(d => d.Name.Equals(modifiedDeliveryOption.Name) && d.Id != modifiedDeliveryOption.Id).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Delivery Option Name already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                currentDeliveryOption.Name = modifiedDeliveryOption.Name;
                if (!(currentDeliveryOption.IsPremitive && currentDeliveryOption.MinimumOrderTotal == 0))
                {
                    currentDeliveryOption.MinimumOrderTotal = modifiedDeliveryOption.MinimumOrderTotal;
                }
                if (!(currentDeliveryOption.IsPremitive && currentDeliveryOption.Price == 0))
                {
                    currentDeliveryOption.Price = modifiedDeliveryOption.Price;
                }


                TryValidateModel(currentDeliveryOption);

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                _DbContext.DeliveryOptions.Update(currentDeliveryOption);

                await _DbContext.SaveChangesAsync().ConfigureAwait(false);


                return(Ok(currentDeliveryOption));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> CreateUser([FromBody] User newUser)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(newUser.Password))
                {
                    newUser.Password = CoreFunc.StringGenerator(10, 3, 3, 2, 2);
                }

                if (newUser.Role.Id == 0)
                {
                    newUser.Role = null;
                }
                TryValidateModel(newUser);

                ModelState.Remove("Role.Name");
                ModelState.Remove("Role.AccessClaim");
                ModelState.Remove("PasswordHash");
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                newUser.Role = await _DbContext.Roles.AsTracking()
                               .FirstOrDefaultAsync(r => r.Id == newUser.Role.Id).ConfigureAwait(false);

                IActionResult result = await PrivateCreateUser(newUser).ConfigureAwait(false);

                if (IsUserCreated)
                {
                    Request.Headers.TryGetValue("Origin", out StringValues OriginValue);
                    await _EmailService
                    .WelcomeNewEmployeeAsync(newUser, OriginValue)
                    .ConfigureAwait(false);
                }
                newUser.Password = string.Empty;

                return(result);
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));

                if (IsUserCreated)
                {
                    _DbContext.Remove(newUser);
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> PostQuestion([FromBody] Communication newContact)
        {
            try
            {
                if (!ReCaptchaPassed(newContact.captchaToken))
                {
                    CoreFunc.Error(ref ErrorsList, "Captcha validation failed");
                    return(StatusCode(412, ErrorsList));
                }

                if (string.IsNullOrWhiteSpace(newContact.Messages.FirstOrDefault().Body))
                {
                    CoreFunc.Error(ref ErrorsList, "Message is required.");
                    return(StatusCode(412, ErrorsList));
                }

                if (AppFunc.GetUserId(User) != 0)
                {
                    var user = await _DbContext.Users.SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User));

                    newContact.Email    = user.Email;
                    newContact.FullName = $"{user.FirstName} {user.Surname}";
                }
                newContact.Status = true;
                newContact.Type   = ContactType.Message;
                newContact.Messages[0].IsCustomer = true;
                ModelState.Clear();
                TryValidateModel(newContact);

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                await _DbContext.Communications.AddAsync(newContact).ConfigureAwait(false);

                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                //   await _EmailService.EmailConfirmationAsync(orderData).ConfigureAwait(false);
                return(Created("", $"Thank you for contacting us. We will contact you as soon as possible. "));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Put([FromBody] Comment modifiedComment)
        {
            try
            {
                ModelState.Clear();
                TryValidateModel(modifiedComment);

                foreach (var key in ModelState.Keys)
                {
                    if (key.StartsWith("User") || key.StartsWith("Product"))
                    {
                        ModelState.Remove(key);
                    }
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                Comment comment = await _DbContext.Comments
                                  .Include(c => c.User)
                                  .SingleOrDefaultAsync(c => c.Id == modifiedComment.Id && c.User.Id == AppFunc.GetUserId(User)).ConfigureAwait(false);

                if (comment == null)
                {
                    CoreFunc.Error(ref ErrorsList, "Comment not exist.");
                    return(StatusCode(412, ErrorsList));
                }

                comment.Description = modifiedComment.Description;
                comment.Rate        = modifiedComment.Rate;
                await comment.CencoredDescription();

                _DbContext.Comments.Update(comment);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(comment));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 9
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> PutTemplate([FromBody] EmailTemplate emailTemplate)
        {
            try
            {
                /// if model validation failed
                if (!TryValidateModel(emailTemplate))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    /// return Unprocessable Entity with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }


                EmailTemplate foundTemplate = await _DbContext.EmailTemplates
                                              .FirstOrDefaultAsync((et) => et.Id == emailTemplate.Id)
                                              .ConfigureAwait(false);

                if (foundTemplate == null)
                {
                    ErrorsList.Add(new Error("", "Template cannot be found."));
                    /// return Unprocessable Entity with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }

                foundTemplate.PrepareHtml(WebHost.WebRootPath);
                emailTemplate.RemoveHtmlComment();
                if (foundTemplate.HTML != emailTemplate.HTML)
                {
                    emailTemplate.SaveFilesToWWWRoot(WebHost.WebRootPath);
                }
                else
                {
                    emailTemplate.FolderName = foundTemplate.FolderName;
                }
                _DbContext.EmailTemplates.Update(emailTemplate);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(emailTemplate));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 10
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Ready For Test
        public async Task <IActionResult> Put([FromBody] Coupon modifiedCoupon)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                if (!await _DbContext.Coupons.AnyAsync(d =>
                                                       d.Code == modifiedCoupon.Code).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Coupon Not exists.");
                    return(StatusCode(412, ErrorsList));
                }

                if (await _DbContext.Coupons.AnyAsync(d => d.Code == modifiedCoupon.Code &&
                                                      d.Type != modifiedCoupon.Type).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Coupon Type Can't be Change.");
                    return(StatusCode(412, ErrorsList));
                }

                Coupon originalCoupon = await _DbContext.Coupons.FindAsync(modifiedCoupon.Code).ConfigureAwait(false);

                originalCoupon.MaxUseQuantity    = modifiedCoupon.MaxUseQuantity;
                originalCoupon.ExpiryDate        = modifiedCoupon.ExpiryDate;
                originalCoupon.DiscountAmount    = originalCoupon.DiscountAmount;
                originalCoupon.MinimumOrderPrice = originalCoupon.MinimumOrderPrice;

                _DbContext.Coupons.Update(originalCoupon);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(originalCoupon));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> Post([FromBody] DeliveryOption newDeliveryOption)
        {
            try
            {
                /// check the database to see if a Category with the same name exists
                if (await _DbContext.DeliveryOptions
                    .AnyAsync(d => d.Name.Equals(newDeliveryOption.Name)).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Delivery Option Name already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                TryValidateModel(newDeliveryOption);


                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                newDeliveryOption.IsPremitive = false;
                /// else Category object is made without any errors
                /// Add the new Category to the EF context
                await _DbContext.DeliveryOptions.AddAsync(newDeliveryOption).ConfigureAwait(false);

                /// save the changes to the database
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);


                /// return 201 created status with the new object
                /// and success message
                return(Created("", newDeliveryOption));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 12
0
        [Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test
        public async Task <IActionResult> Post([FromBody] Address newAddress)
        {
            try
            {
                //if (newAddress is null)
                //   return checkObjectIsNull(newAddress);

                if (newAddress != null)
                {
                    newAddress.User = await _DbContext.Users.AsTracking().Include(u => u.Role)
                                      .Include(u => u.RegistrationMethod)
                                      .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User));
                }
                ModelState.Clear();
                if (!TryValidateModel(newAddress))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                if (!await _DbContext.Addresses.AnyAsync(a => a.User.Id == AppFunc.GetUserId(User)))
                {
                    newAddress.IsDefault = true;
                }

                await _DbContext.Addresses.AddAsync(newAddress).ConfigureAwait(false);

                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Created("Success", newAddress));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 13
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> PostTemplate([FromBody] EmailTemplate emailTemplate)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                /// save files
                emailTemplate.SaveFilesToWWWRoot(WebHost.WebRootPath);

                _DbContext.EmailTemplates.Add(emailTemplate);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Created("", emailTemplate));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 14
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> Put([FromBody] Category modifiedCategory)
        {
            try
            {
                bool containsNewImages = true;
                TryValidateModel(modifiedCategory);

                /// if new image is not provided do not check for new images
                if (string.IsNullOrWhiteSpace(modifiedCategory.ImageBase64) && string.IsNullOrWhiteSpace(modifiedCategory.OriginalImageBase64))
                {
                    containsNewImages = false;
                    ModelState.Remove("ImageBase64");
                    ModelState.Remove("OriginalImageBase64");
                }

                if (ModelState.ContainsKey("ImageBase64"))
                {
                    ModelState.Remove("OriginalImageBase64");
                }
                /// if model validation failed
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    /// return Unprocessable Entity with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }

                /// check the database to see if a Category with the same name exists
                if (await _DbContext.Categories
                    .AnyAsync(c => c.Name == modifiedCategory.Name && c.Id != modifiedCategory.Id)
                    .ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Category with the given name already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                /// get the current category
                Category currentCatogory = await _DbContext.Categories
                                           .SingleOrDefaultAsync(c => c.Id == modifiedCategory.Id)
                                           .ConfigureAwait(false);

                // if the current category does not exists
                if (currentCatogory == null)
                {
                    CoreFunc.Error(ref ErrorsList, "Category Not Found");
                    return(NotFound(ErrorsList));
                }

                string oldImagePath         = modifiedCategory.ImagePath.Clone().ToString();
                string oldOriginalImagePath = modifiedCategory.OriginalImagePath.Clone().ToString();

                /// if new image is provided save the new image
                if (containsNewImages)
                {
                    try
                    {
                        string folderName = CoreFunc.StringGenerator(10, 3, 3, 4);
                        modifiedCategory.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                                 _WebHost.WebRootPath,
                                                                                 modifiedCategory.ImageBase64,
                                                                                 $"Images\\Categories\\{folderName}");
                        modifiedCategory.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                                         _WebHost.WebRootPath,
                                                                                         modifiedCategory.OriginalImageBase64,
                                                                                         $"Images\\Categories\\{folderName}");
                    }
                    catch (Exception ex)
                    {
                        CoreFunc.Error(ref ErrorsList, "Image cannot be saved.");
                        _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                        return(StatusCode(412, ErrorsList));
                    }
                }

                try
                {
                    /// else Category object is made without any errors
                    _DbContext.Categories.Update(modifiedCategory);

                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    if (containsNewImages)
                    {
                        CoreFunc.DeleteFromWWWRoot(modifiedCategory.ImagePath, _WebHost.WebRootPath);
                        CoreFunc.DeleteFromWWWRoot(modifiedCategory.OriginalImagePath, _WebHost.WebRootPath);
                        CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                    }
                    _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                }

                if (containsNewImages)
                {
                    CoreFunc.DeleteFromWWWRoot(oldImagePath, _WebHost.WebRootPath);
                    CoreFunc.DeleteFromWWWRoot(oldOriginalImagePath, _WebHost.WebRootPath);
                    CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                }
                return(Ok(modifiedCategory));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 15
0
        /// Done
        public async Task <IActionResult> Post([FromBody] Product newProduct)
        {
            try
            {
                if (newProduct.Category.Id == 0)
                {
                    newProduct.Category = null;
                }
                TryValidateModel(newProduct);
                ModelState.Remove("Category.Name");
                ModelState.Remove("Category.ImageBase64");
                ModelState.Remove("NutritionalInfo.Product");
                ModelState.Remove("Category.OriginalImageBase64");
                if (ModelState.ContainsKey("ImageBase64"))
                {
                    ModelState.Remove("OriginalImageBase64");
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                /// check the database to see if a Product with the same name exists
                if (await _DbContext.Products.AnyAsync(d => d.Name == newProduct.Name && d.Category.Id == newProduct.Category.Id).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Product already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                try
                {
                    string folderName = CoreFunc.StringGenerator(10, 3, 3, 4);
                    newProduct.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                       _WebHost.WebRootPath,
                                                                       newProduct.ImageBase64,
                                                                       $"Images\\Products\\{folderName}");
                    newProduct.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                               _WebHost.WebRootPath,
                                                                               newProduct.OriginalImageBase64,
                                                                               $"Images\\Products\\{folderName}");
                }
                catch (Exception ex)
                {
                    CoreFunc.Error(ref ErrorsList, "Image cannot be saved.");
                    _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                    return(StatusCode(412, ErrorsList));
                }

                try
                {
                    await _DbContext.Products.AddAsync(newProduct).ConfigureAwait(false);

                    _DbContext.Entry(newProduct.Category).State = EntityState.Unchanged;
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                catch (Exception)
                {
                    CoreFunc.DeleteFromWWWRoot(newProduct.ImagePath, _WebHost.WebRootPath);
                    CoreFunc.DeleteFromWWWRoot(newProduct.OriginalImagePath, _WebHost.WebRootPath);
                    CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                    throw;
                }

                return(Created("", newProduct));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> UpdateUser([FromBody] User modifiedUser)
        {
            try
            {
                User user = await _DbContext.Users
                            .AsTracking()
                            .Include(u => u.Role)
                            .Include(u => u.RegistrationMethod)
                            .FirstOrDefaultAsync(u => u.Id == modifiedUser.Id)
                            .ConfigureAwait(false);


                if (user == null)
                {
                    CoreFunc.Error(ref ErrorsList, "User Not Found.");
                    return(StatusCode(412, ErrorsList));
                }

                modifiedUser.Role = await _DbContext.Roles.AsTracking()
                                    .SingleOrDefaultAsync(r => r.Id == modifiedUser.Role.Id)
                                    .ConfigureAwait(false);

                ModelState.Clear();
                TryValidateModel(modifiedUser);

                ModelState.Remove("PasswordHash");
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                user.FirstName = modifiedUser.FirstName;
                user.Surname   = modifiedUser.Surname;
                if (user.RegistrationMethod.Type == RegistrationTypes.Application && user.Email != modifiedUser.Email)
                {
                    if (await _DbContext.Users.AnyAsync(d => d.NormalizedEmail == modifiedUser.Email.ToUpper()).ConfigureAwait(false))
                    {
                        CoreFunc.Error(ref ErrorsList, "This email is already registered.");
                        return(StatusCode(412, ErrorsList));
                    }

                    await _DbContext.Communications.Where(c => c.Email == user.Email)
                    .ForEachAsync(c => c.Email = modifiedUser.Email).ConfigureAwait(false);

                    await _DbContext.Newsletters.Where(c => c.Email == user.Email)
                    .ForEachAsync(c => c.Email = modifiedUser.Email).ConfigureAwait(false);

                    user.Email           = modifiedUser.Email;
                    user.NormalizedEmail = modifiedUser.Email.ToUpper();
                }
                user.PhoneNumber = modifiedUser.PhoneNumber;

                string oldAccessClaim = "";
                if (!user.Role.Equals(modifiedUser.Role))
                {
                    oldAccessClaim = user.Role.AccessClaim;
                    user.Role      = modifiedUser.Role;
                }

                _DbContext.Users.Update(user);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                if (!string.IsNullOrEmpty(oldAccessClaim))
                {
                    IdentityResult removedClaimResult = await _UserManager.RemoveClaimAsync(user,
                                                                                            new Claim(AppConst.AccessClaims.Type, oldAccessClaim)
                                                                                            ).ConfigureAwait(false);

                    if (removedClaimResult.Succeeded)
                    {
                        IdentityResult addedClaimResult = await _UserManager.AddClaimAsync(user,
                                                                                           new Claim(AppConst.AccessClaims.Type, user.Role.AccessClaim)
                                                                                           ).ConfigureAwait(false);
                    }
                }

                return(Ok(user));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> UpdateCurrentUser([FromBody] UpdateCurrentUserData currentUserData)
        {
            try
            {
                _ = int.TryParse(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value, out int userId);
                User user = await _DbContext.Users
                            .Include(u => u.RegistrationMethod)
                            .FirstOrDefaultAsync(u => u.Id == userId)
                            .ConfigureAwait(false);

                if (user == null || currentUserData.User.Id != user.Id)
                {
                    CoreFunc.Error(ref ErrorsList, "Information access is denied.");
                    return(UnprocessableEntity(ErrorsList));
                }

                ModelState.Clear();
                TryValidateModel(currentUserData.User);
                ModelState.Remove("PasswordHash");
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                if (user.RegistrationMethod.Type == RegistrationTypes.Application && !await _UserManager.CheckPasswordAsync(user, currentUserData.CurrentPassword).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Current Password is incorrect.");
                    return(StatusCode(412, ErrorsList));
                }

                user.FirstName = currentUserData.User.FirstName;
                user.Surname   = currentUserData.User.Surname;
                if (user.RegistrationMethod.Type == RegistrationTypes.Application && user.Email != currentUserData.User.Email)
                {
                    if (await _DbContext.Users.AnyAsync(d => d.NormalizedEmail == currentUserData.User.Email.ToUpper()).ConfigureAwait(false))
                    {
                        CoreFunc.Error(ref ErrorsList, "This email is already registered.");
                        return(StatusCode(412, ErrorsList));
                    }

                    await _DbContext.Communications.Where(c => c.Email == user.Email)
                    .ForEachAsync(c => c.Email = currentUserData.User.Email).ConfigureAwait(false);

                    await _DbContext.Newsletters.Where(c => c.Email == user.Email)
                    .ForEachAsync(c => c.Email = currentUserData.User.Email).ConfigureAwait(false);

                    user.Email           = currentUserData.User.Email;
                    user.NormalizedEmail = currentUserData.User.Email.ToUpper();
                }
                user.PhoneNumber = currentUserData.User.PhoneNumber;
                _DbContext.Users.Update(user);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(user));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> Post([FromBody] Comment newComment)
        {
            try
            {
                User user = await _DbContext.Users
                            .Include(u => u.Orders)
                            .ThenInclude(o => o.OrderItems)
                            .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User))
                            .ConfigureAwait(false);

                if (user.Orders.Any(o => o.Status == OrderStatusType.Delivered &&
                                    o.OrderItems.Any(oi => oi.ProductId == newComment.Product.Id)))
                {
                    Comment selectComment = await _DbContext.Comments
                                            .Include(c => c.User)
                                            .SingleOrDefaultAsync(c => c.Product.Id == newComment.Product.Id &&
                                                                  c.User.Id == AppFunc.GetUserId(User));

                    if (selectComment != null)
                    {
                        _LoggingService.Log(Request.Path, AppLogType.OrderException,
                                            new { message = $"Try to add duplicate comment.", newContact = newComment }, User);
                        CoreFunc.Error(ref ErrorsList, "You Can't add review for this product.Try again or Contact Admin.");
                        return(StatusCode(412, ErrorsList));
                    }
                }
                else
                {
                    _LoggingService.Log(Request.Path, AppLogType.OrderException,
                                        new { message = $"Try to add comment without order.", newContact = newComment }, User);
                    CoreFunc.Error(ref ErrorsList, "You Can't add review for this product.Try again or Contact Admin.");
                    return(StatusCode(412, ErrorsList));
                }

                newComment.User = user;

                newComment.User.Orders = null;

                ModelState.Clear();
                TryValidateModel(newComment);
                foreach (var key in ModelState.Keys)
                {
                    if (key.StartsWith("User") || key.StartsWith("Product"))
                    {
                        ModelState.Remove(key);
                    }
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                await _DbContext.Comments.AddAsync(newComment).ConfigureAwait(false);

                _DbContext.Entry(newComment.User).State    = EntityState.Unchanged;
                _DbContext.Entry(newComment.Product).State = EntityState.Unchanged;
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Created("", newComment));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Post([FromBody] Category newCategory)
        {
            try
            {
                TryValidateModel(newCategory);

                if (ModelState.ContainsKey("ImageBase64"))
                {
                    ModelState.Remove("OriginalImageBase64");
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                /// check the database to see if a Category with the same name exists
                if (await _DbContext.Categories
                    .AnyAsync(d => d.Name.Equals(newCategory.Name)).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Category already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                try
                {
                    string folderName = CoreFunc.StringGenerator(10, 3, 3, 4);
                    newCategory.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                        _WebHost.WebRootPath,
                                                                        newCategory.ImageBase64,
                                                                        $"Images\\Categories\\{folderName}");
                    newCategory.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                                _WebHost.WebRootPath,
                                                                                newCategory.OriginalImageBase64,
                                                                                $"Images\\Categories\\{folderName}");
                }
                catch (Exception ex)
                {
                    CoreFunc.Error(ref ErrorsList, "Image cannot be saved.");
                    _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                    return(StatusCode(412, ErrorsList));
                }
                try
                {
                    /// else Category object is made without any errors
                    /// Add the new Category to the EF context
                    await _DbContext.Categories.AddAsync(newCategory).ConfigureAwait(false);

                    /// save the changes to the database
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    CoreFunc.DeleteFromWWWRoot(newCategory.ImagePath, _WebHost.WebRootPath);
                    CoreFunc.DeleteFromWWWRoot(newCategory.OriginalImagePath, _WebHost.WebRootPath);
                    CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                    CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification));
                }

                /// return 201 created status with the new object
                /// and success message
                return(Created("", newCategory));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> PostDispute([FromBody] Communication newDispute)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(newDispute.Messages.FirstOrDefault().Body))
                {
                    CoreFunc.Error(ref ErrorsList, "Message is required.");
                    return(StatusCode(412, ErrorsList));
                }

                if (!string.IsNullOrEmpty(newDispute.Order_Id) &&
                    (await _DbContext.Orders.SingleOrDefaultAsync(o => o.Id == newDispute.Order_Id) == null))
                {
                    CoreFunc.Error(ref ErrorsList, "Cannot find your order.");
                    return(UnprocessableEntity(ErrorsList));
                }

                User user = await _DbContext.Users.SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User));

                newDispute.Email    = user.Email;
                newDispute.FullName = $"{user.FirstName} {user.Surname}";
                newDispute.Status   = true;
                newDispute.Order    = await _DbContext.Orders
                                      .Include(o => o.Payment)
                                      .Include(o => o.User)
                                      .SingleOrDefaultAsync(o => o.Id == newDispute.Order_Id);

                newDispute.Type = ContactType.Dispute;
                newDispute.Messages[0].IsCustomer = true;

                TryValidateModel(newDispute);

                foreach (var key in ModelState.Keys)
                {
                    if (key.StartsWith("User") || key.StartsWith("Order") || key.StartsWith("OrderItem"))
                    {
                        ModelState.Remove(key);
                    }
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                await _DbContext.Communications.AddAsync(newDispute).ConfigureAwait(false);

                _DbContext.Entry(newDispute.Order).State         = EntityState.Unchanged;
                _DbContext.Entry(newDispute.Order.User).State    = EntityState.Unchanged;
                _DbContext.Entry(newDispute.Order.Payment).State = EntityState.Unchanged;
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                await _EmailService.OrderDisputeAsync(newDispute.Order, newDispute).ConfigureAwait(false);

                return(Created("", newDispute));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 21
0
        private async Task <IActionResult> Update(string communicationId, bool isCustomer, Message message, bool status = false)
        {
            try
            {
                var originalCommunication = await _DbContext.Communications
                                            .Include(c => c.Messages)
                                            .SingleOrDefaultAsync(c => c.Id == communicationId);

                if (originalCommunication is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Communication Not exists.");
                    return(StatusCode(412, ErrorsList));
                }

                if (!isCustomer)
                {
                    originalCommunication.Status = status;
                }


                if (string.IsNullOrWhiteSpace(message.Body) && originalCommunication.Status)
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Message is required.");
                    return(StatusCode(412, ErrorsList));
                }

                if (!originalCommunication.Status)
                {
                    message.Body = $"{originalCommunication.CommunicationType} was closed";
                }

                message.IsCustomer = isCustomer;
                originalCommunication.Messages.Add(message);

                ModelState.Clear();
                TryValidateModel(originalCommunication);

                foreach (var key in ModelState.Keys)
                {
                    if (key.StartsWith("User") || key.StartsWith("Order") || key.StartsWith("OrderItem"))
                    {
                        ModelState.Remove(key);
                    }
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                _DbContext.Communications.Update(originalCommunication);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                if (message.IsCustomer)
                {
                    await _EmailService.MessageToAdminAsync(message, originalCommunication).ConfigureAwait(false);
                }
                else if (originalCommunication.Status)
                {
                    await _EmailService.MessageToUser(message, originalCommunication).ConfigureAwait(false);
                }

                return(Ok(originalCommunication));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 22
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> Put([FromBody] Product modifiedProduct)
        {
            try
            {
                bool containsNewImages = true;
                if (modifiedProduct.Category.Id == 0)
                {
                    modifiedProduct.Category = null;
                }

                ModelState.Remove("Category.Name");
                ModelState.Remove("Category.ImageBase64");
                ModelState.Remove("Category.OriginalImageBase64");
                ModelState.Remove("NutritionalInfo.Product");

                /// if new image is not provided do not check for new images
                if (string.IsNullOrWhiteSpace(modifiedProduct.ImageBase64) && string.IsNullOrWhiteSpace(modifiedProduct.OriginalImageBase64))
                {
                    containsNewImages = false;
                    ModelState.Remove("ImageBase64");
                    ModelState.Remove("OriginalImageBase64");
                }

                if (ModelState.ContainsKey("ImageBase64"))
                {
                    ModelState.Remove("OriginalImageBase64");
                }

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                /// check the database to see if a Product with the same name exists
                if (await _DbContext.Products.AnyAsync(d => d.Id != modifiedProduct.Id && d.Name == modifiedProduct.Name && d.Category.Id == modifiedProduct.Category.Id).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Duplicated product name in selected category.");
                    return(StatusCode(412, ErrorsList));
                }

                string oldImagePath         = modifiedProduct.ImagePath.Clone().ToString();
                string oldOriginalImagePath = modifiedProduct.OriginalImagePath.Clone().ToString();
                /// if new image is provided save the new image
                if (containsNewImages)
                {
                    try
                    {
                        string folderName = CoreFunc.StringGenerator(10, 3, 3, 4);
                        modifiedProduct.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                                _WebHost.WebRootPath,
                                                                                modifiedProduct.ImageBase64,
                                                                                $"Images\\Products\\{folderName}");
                        modifiedProduct.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4),
                                                                                        _WebHost.WebRootPath,
                                                                                        modifiedProduct.OriginalImageBase64,
                                                                                        $"Images\\Products\\{folderName}");
                    }
                    catch (Exception ex)
                    {
                        CoreFunc.Error(ref ErrorsList, "Image cannot be saved.");
                        _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                        return(StatusCode(412, ErrorsList));
                    }
                }

                try
                {
                    _DbContext.Products.Update(modifiedProduct);
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                catch (Exception)
                {
                    if (containsNewImages)
                    {
                        CoreFunc.DeleteFromWWWRoot(modifiedProduct.ImagePath, _WebHost.WebRootPath);
                        CoreFunc.DeleteFromWWWRoot(modifiedProduct.OriginalImagePath, _WebHost.WebRootPath);
                        CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                    }
                    throw;
                }

                if (containsNewImages)
                {
                    CoreFunc.DeleteFromWWWRoot(oldImagePath, _WebHost.WebRootPath);
                    CoreFunc.DeleteFromWWWRoot(oldOriginalImagePath, _WebHost.WebRootPath);
                    CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                }

                return(Ok(modifiedProduct));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> ExternalLogin(ExternalLoginDetails externalLoginInfo)
        {
            try
            {
                IEnumerable <string> policies = AppFunc.GetCurrentRequestPolicies(Request, out AppTypes apptype);
                if (apptype == AppTypes.Invalid)
                {
                    CoreFunc.Error(ref ErrorsList, "Unauthorised Application Access. 🤔");
                    return(Unauthorized(ErrorsList));
                }

                if (!TryValidateModel(externalLoginInfo))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                User externalLoginUser = new User();
                switch (externalLoginInfo.Type)
                {
                case RegistrationTypes.Google:
                    externalLoginUser = await GetGoogleUserInfo(externalLoginInfo).ConfigureAwait(false);

                    break;

                case RegistrationTypes.Facebook:
                    externalLoginUser = await GetFacebookUserInfo(externalLoginInfo).ConfigureAwait(false);

                    break;
                }

                // Check if the user is already registered
                User registeredUser = await _DbContext.Users
                                      .Include(u => u.Role)
                                      .Include(u => u.RegistrationMethod)
                                      .SingleOrDefaultAsync(u => u.RegistrationMethod.Type == externalLoginInfo.Type &&
                                                            u.RegistrationMethod.ExternalLinkedId == externalLoginUser.RegistrationMethod.ExternalLinkedId)
                                      .ConfigureAwait(false);

                // if the user is already registered
                if (registeredUser != null)
                {
                    if (!await IsUserPolicyAccepted(registeredUser, policies).ConfigureAwait(false))
                    {
                        CoreFunc.Error(ref ErrorsList, "You do not have permission to login here.");
                        return(Unauthorized(ErrorsList));
                    }

                    // sign the user in without any password
                    await _SignInManager.SignInAsync(registeredUser, externalLoginInfo.RememberMe).ConfigureAwait(false);

                    return(Ok(registeredUser));
                }

                if (apptype == AppTypes.Admin)
                {
                    CoreFunc.Error(ref ErrorsList, "You do not have permission to login here. Please contact administrator.");
                    return(Unauthorized(ErrorsList));
                }
                /// check if the user is registered using other methods
                User user = await _UserManager
                            .FindByEmailAsync(externalLoginUser?.Email).ConfigureAwait(false);

                if (user != null)
                {
                    RegistrationMethod registrationMethod = await _DbContext.RegistrationMethods
                                                            .FirstOrDefaultAsync(r => r.User.Id == user.Id).ConfigureAwait(false);

                    if (registrationMethod.Type != RegistrationTypes.Application)
                    {
                        /// in the case any exceptions return the following error
                        CoreFunc.Error(ref ErrorsList, $"Please use {registrationMethod.Type} account to login.");
                    }
                    else
                    {
                        /// in the case any exceptions return the following error
                        CoreFunc.Error(ref ErrorsList, $"Please use Email and Password to login");
                    }
                    return(StatusCode(403, ErrorsList));
                }

                externalLoginUser.Role = await _DbContext.Roles.FirstOrDefaultAsync(r => r.Name == "Customer").ConfigureAwait(false);

                // else if the user is not registered but information is received from external login
                externalLoginUser.Id = -1;
                return(StatusCode(206, externalLoginUser));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Ejemplo n.º 24
0
        private async Task <Order> CheckOrderDetail(Order orderData)
        {
            Address currentAddress = await _DbContext.Addresses.Include(a => a.User)
                                     .SingleOrDefaultAsync(a => a.Id == orderData.AddressId && a.User.Id == AppFunc.GetUserId(User));

            if (currentAddress != null)
            {
                orderData.UpdateAddress(currentAddress);
            }
            orderData.DeliveryOption = await _DbContext.DeliveryOptions.AsTracking()
                                       .SingleOrDefaultAsync(a => a.Id == orderData.DeliveryOption.Id)
                                       .ConfigureAwait(false);

            ModelState.Clear();
            TryValidateModel(orderData);
            foreach (var key in ModelState.Keys)
            {
                if (
                    (key.StartsWith("Payment") || key.StartsWith("Coupon") || key.StartsWith("OrderItems") || key.StartsWith("User")) ||
                    (AppFunc.GetUserId(User) == 0 && currentAddress == null &&
                     (key.StartsWith("Name") || key.StartsWith("City") || key.StartsWith("Postcode") || key.StartsWith("FirstLine")))
                    )
                {
                    ModelState.Remove(key);
                }
            }
            if (!ModelState.IsValid)
            {
                CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                return(null);
            }

            List <Product> productList = await _DbContext.Products.AsTracking()
                                         .Include(p => p.Category)
                                         .Where(p => orderData.OrderItems.Select(t => t.ProductId).ToList().Contains(p.Id))
                                         .ToListAsync()
                                         .ConfigureAwait(false);

            Product          originalProduct;
            List <OrderItem> CheckedOrderItems = new List <OrderItem>();

            orderData.TotalItemPrice = 0;
            foreach (var orderItem in orderData.OrderItems)
            {
                originalProduct = productList.SingleOrDefault(t => t.Id == orderItem.ProductId);
                if (originalProduct == null || !originalProduct.Status)
                {
                    _LoggingService.Log(Request.Path, AppLogType.OrderException,
                                        new { message = $"Product ({orderItem.Name}) Unavailable.", order = orderData }, User);
                    CoreFunc.Error(ref ErrorsList, $"Product ({orderItem.Name}) Unavailable.");
                    return(null);
                }
                if (orderItem.Price != originalProduct.Price)
                {
                    _LoggingService.Log(Request.Path, AppLogType.OrderException,
                                        new { message = "Product Price mismatch.", order = orderData }, User);
                    CoreFunc.Error(ref ErrorsList, "Product Price mismatch");
                    return(null);
                }
                if (orderItem.Quantity > originalProduct.StockQuantity)
                {
                    CoreFunc.Error(ref ErrorsList, $"Product '{orderItem.Name}' is out of stock");
                    return(null);
                }
                if (orderItem.Quantity == 0)
                {
                    _LoggingService.Log(Request.Path, AppLogType.OrderException,
                                        new { message = "Product quantity can't be zero.", order = orderData }, User);
                    CoreFunc.Error(ref ErrorsList, $"Product quantity can't be zero.");
                    return(null);
                }
                orderData.TotalItemPrice      += (orderItem.Quantity * originalProduct.Price ?? 0);
                originalProduct.StockQuantity -= orderItem.Quantity;
                CheckedOrderItems.Add(new OrderItem(originalProduct, orderItem.Quantity));
            }

            if (orderData.DeliveryOption.Price == 0 &&
                orderData.DeliveryOption.MinimumOrderTotal > orderData.TotalItemPrice &&
                orderData.DeliveryOption.IsPremitive)
            {
                CoreFunc.Error(ref ErrorsList, $"You do not meet the free delivery requirement of £{orderData.DeliveryOption.MinimumOrderTotal}");
                return(null);
            }

            //Check coupon
            if (orderData.Coupon != null && !string.IsNullOrEmpty(orderData.Coupon.Code))
            {
                Coupon currentCoupon = await _DbContext.Coupons.AsTracking()
                                       .SingleOrDefaultAsync(c => c.Code == orderData.Coupon.Code)
                                       .ConfigureAwait(false);

                if (currentCoupon == null ||
                    currentCoupon.MaxUseQuantity < 1 ||
                    currentCoupon.ExpiryDate < DateTime.UtcNow ||
                    orderData.TotalItemPrice < currentCoupon.MinimumOrderPrice)
                {
                    _LoggingService.Log(Request.Path, AppLogType.OrderException,
                                        new { message = "Coupon Invalid", order = orderData }, User);
                    CoreFunc.Error(ref ErrorsList, $"'{orderData.Coupon.Code}' is invalid");
                    return(null);
                }
                else
                {
                    orderData.Coupon = currentCoupon;
                }
            }

            orderData.CalculateTotalPrice();
            return(orderData);
        }