예제 #1
0
        public async Task <IActionResult> Delete(string key)
        {
            try
            {
                /// if the Newsletter record with the same id is not found
                Newsletter newsletter = _DbContext.Newsletters.Find(key);
                if (newsletter != null)
                {
                    /// now delete the Newsletter record
                    _DbContext.Newsletters.Remove(newsletter);

                    /// save the changes to the database
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                else
                {
                    CoreFunc.Error(ref ErrorsList, "Your key is invalid.");
                    return(StatusCode(412, ErrorsList));
                }
                /// return 200 OK status
                return(Ok($"{newsletter.Email} is now unsubscribed"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #2
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> AllTemplate()
        {
            try
            {
                List <EmailTemplate> templateList = await _DbContext.EmailTemplates
                                                    .OrderByDescending(et => et.TemplateType)
                                                    .ToListAsync()
                                                    .ConfigureAwait(false);

                EmailTemplate copyDefaultTemplate = null;
                foreach (EmailTemplate item in templateList)
                {
                    if (item.TemplateType == EmailTemplateTypes.DefaultTemplate)
                    {
                        copyDefaultTemplate = item;
                    }
                    item.PrepareDesign(WebHost.WebRootPath);
                    item.PrepareHtml(WebHost.WebRootPath);
                }

                if (copyDefaultTemplate != null)
                {
                    templateList.Remove(copyDefaultTemplate);
                    templateList = templateList.Prepend(copyDefaultTemplate).ToList();
                }
                return(Ok(templateList));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));;
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #3
0
        /// Done
        public async Task <IActionResult> Delete(int productId)
        {
            try
            {
                Product product = await _DbContext.Products.SingleOrDefaultAsync(d => d.Id == productId).ConfigureAwait(false);

                if (product is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Product not found");
                    return(NotFound(ErrorsList));
                }

                _DbContext.Products.Remove(product);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                try
                {
                    CoreFunc.DeleteFromWWWRoot(product.ImagePath, _WebHost.WebRootPath);
                    CoreFunc.DeleteFromWWWRoot(product.OriginalImagePath, _WebHost.WebRootPath);
                    CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                }
                catch (Exception ex)
                {
                    _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                }
                return(Ok($"Product '{product.Name}' was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #4
0
파일: Coupon.cs 프로젝트: p8b/OSnack
        public bool IsValid(ref List <Error> ErrorsList)
        {
            switch (this.Type)
            {
            case CouponType.FreeDelivery:
                this.DiscountAmount = 0;
                break;

            case CouponType.PercentageOfTotal:
                if (this.DiscountAmount > 100)
                {
                    CoreFunc.Error(ref ErrorsList, $"Discount Amount must be less than 100");
                    return(false);
                }
                break;

            case CouponType.DiscountPrice:
                break;

            default:
                break;
            }


            return(true);
        }
예제 #5
0
        public async Task <IActionResult> Search(
            int selectedPage,
            int maxNumberPerItemsPage,
            string searchValue = "",
            bool isSortAsce    = true,
            string sortName    = "Name")
        {
            try
            {
                int totalCount = await _DbContext.Categories
                                 .CountAsync(c => searchValue.Equals(CoreConst.GetAllRecords)?true : c.Name.Contains(searchValue))
                                 .ConfigureAwait(false);

                List <Category> list = await _DbContext.Categories
                                       .Where(c => searchValue.Equals(CoreConst.GetAllRecords)?true : c.Name.Contains(searchValue))
                                       .OrderByDynamic(sortName, isSortAsce)
                                       .Skip((selectedPage - 1) * maxNumberPerItemsPage)
                                       .Take(maxNumberPerItemsPage)
                                       .ToListAsync()
                                       .ConfigureAwait(false);

                foreach (var category in list)
                {
                    category.TotalProducts = await _DbContext.Products
                                             .CountAsync(p => p.Category.Id == category.Id)
                                             .ConfigureAwait(false);
                }
                return(Ok(new MultiResult <List <Category>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #6
0
        public async Task <IActionResult> SalesStatistics(SalesPeriod salePeriod)
        {
            try
            {
                MultiResult <List <string>, List <decimal>, List <int> > result = new MultiResult <List <string>, List <decimal>, List <int> >();
                switch (salePeriod)
                {
                case SalesPeriod.Daily:
                    result = await GetDaily(CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext));

                    break;

                case SalesPeriod.Monthly:
                    result = await GetMonthly(CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext));

                    break;

                case SalesPeriod.Yearly:
                    result = await GetYearly(CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext));

                    break;

                default:
                    break;
                }
                ;
                return(Ok(result));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #7
0
        public async Task <IActionResult> All(int productId,
                                              int selectedPage,
                                              int maxItemsPerPage)
        {
            try
            {
                int totalCount = await _DbContext.Comments.CountAsync()
                                 .ConfigureAwait(false);

                List <Comment> list = await _DbContext.Comments.Include(c => c.Product).Include(c => c.User)
                                      .Where(c => c.Product.Id == productId)
                                      .OrderBy(c => c.Date)
                                      .Skip((selectedPage - 1) * maxItemsPerPage)
                                      .Take(maxItemsPerPage)
                                      .ToListAsync()
                                      .ConfigureAwait(false);

                return(Ok(new MultiResult <List <Comment>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(ControllerContext))));
            }
            catch (Exception ex)
            {
                /// in the case any exceptions return the following error
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #8
0
        private async Task <User> UpdatePassword(User selectedUser)
        {
            User userDetails = await _DbContext.Users.FindAsync(selectedUser.Id).ConfigureAwait(false);

            if (userDetails == null)
            {
                CoreFunc.Error(ref ErrorsList, "User not found!");
                return(null);
            }
            string passResetToken = await _UserManager.GeneratePasswordResetTokenAsync(userDetails).ConfigureAwait(false);

            IdentityResult result = await _UserManager.ResetPasswordAsync(
                userDetails, passResetToken, selectedUser.Password).ConfigureAwait(false);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ErrorsList.Add(new Error(error.Code, error.Description));
                }
                return(null);
            }

            return(userDetails);
        }
예제 #9
0
        [Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test
        public async Task <IActionResult> Delete(int addressId)
        {
            try
            {
                Address address = await _DbContext.Addresses.SingleAsync(a => a.Id == addressId).ConfigureAwait(false);

                if (address is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Address not found");
                    return(NotFound(ErrorsList));
                }

                if (address.IsDefault == true)
                {
                    CoreFunc.Error(ref ErrorsList, "Unable to Delete default Address.");
                    return(StatusCode(412, ErrorsList));
                }

                _DbContext.Addresses.Remove(address);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok($"Address was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #10
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));
            }
        }
예제 #11
0
        public async Task <IActionResult> Summary()
        {
            try
            {
                int newOrderCount = await _DbContext.Orders
                                    .CountAsync(o => o.Status == OrderStatusType.InProgress).ConfigureAwait(false);

                int openDisputeCount = await _DbContext.Communications
                                       .CountAsync(o => o.Type == ContactType.Dispute && o.Status == true).ConfigureAwait(false);

                int openMessageCount = await _DbContext.Communications
                                       .CountAsync(o => o.Type == ContactType.Message && o.Status == true).ConfigureAwait(false);

                decimal totalPrice = await _DbContext.Orders
                                     .Where(o => o.Status == OrderStatusType.InProgress ||
                                            o.Status == OrderStatusType.Confirmed ||
                                            o.Status == OrderStatusType.Delivered ||
                                            o.Status == OrderStatusType.PartialyRefunded)
                                     .SumAsync(o => o.TotalPrice).ConfigureAwait(false);

                decimal totalPartialRefund = await _DbContext.Payments
                                             .Where(p => p.Type == PaymentType.PartialyRefunded)
                                             .SumAsync(p => p.RefundAmount).ConfigureAwait(false);

                return(Ok(new MultiResult <int, int, int, decimal>(newOrderCount, openDisputeCount, openMessageCount, totalPrice - totalPartialRefund, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #12
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Ready for test
        public async Task <IActionResult> Search(
            int selectedPage,
            int maxNumberPerItemsPage,
            string searchValue = "",
            string filterType  = CoreConst.GetAllRecords,
            bool isSortAsce    = true,
            string sortName    = "Code")
        {
            try
            {
                int totalCount = await _DbContext.Coupons
                                 .Where(r => filterType.Equals(CoreConst.GetAllRecords)?
                                        true : r.Type.Equals((CouponType)Enum.Parse(typeof(CouponType), filterType, true)))
                                 .CountAsync(c => searchValue.Equals(CoreConst.GetAllRecords) ? true : c.Code.Contains(searchValue))
                                 .ConfigureAwait(false);

                List <Coupon> list = await _DbContext.Coupons
                                     .Where(r => filterType.Equals(CoreConst.GetAllRecords)?true : r.Type.Equals((CouponType)Enum.Parse(typeof(CouponType), filterType, true)))
                                     .OrderByDynamic(sortName, isSortAsce)
                                     .Where(c => searchValue.Equals(CoreConst.GetAllRecords) ? true : c.Code.Contains(searchValue))
                                     .Skip((selectedPage - 1) * maxNumberPerItemsPage)
                                     .Take(maxNumberPerItemsPage)
                                     .ToListAsync()
                                     .ConfigureAwait(false);

                return(Ok(new MultiResult <List <Coupon>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #13
0
        /// Ready For Test
        public async Task <IActionResult> Delete(string communicationId)
        {
            try
            {
                Communication currentDeliveryOption = await _DbContext.Communications.SingleOrDefaultAsync(d => d.Id == communicationId)
                                                      .ConfigureAwait(false);

                if (currentDeliveryOption is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Communication not found");
                    return(NotFound(ErrorsList));
                }

                if (currentDeliveryOption.Type == Extras.CustomTypes.ContactType.Dispute)
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Dispute can't be delete.");
                    return(StatusCode(412, ErrorsList));
                }
                _DbContext.Communications.Remove(currentDeliveryOption);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok("Communication was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #14
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));
            }
        }
예제 #15
0
        /// Ready For Test
        public async Task <IActionResult> Delete(int deliveyOptionId)
        {
            try
            {
                DeliveryOption currentDeliveryOption = await _DbContext.DeliveryOptions.SingleOrDefaultAsync(d => d.Id == deliveyOptionId)
                                                       .ConfigureAwait(false);

                if (currentDeliveryOption is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Delivery Option not found");
                    return(NotFound(ErrorsList));
                }

                if (currentDeliveryOption.IsPremitive)
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Delivery Option is primitive.");
                    return(StatusCode(412, ErrorsList));
                }

                _DbContext.DeliveryOptions.Remove(currentDeliveryOption);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok("Delivery Option was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #16
0
        public async Task <IActionResult> Validate(string couponCode)
        {
            try
            {
                Coupon coupon = await _DbContext.Coupons.FindAsync(couponCode);

                if (coupon == null)
                {
                    CoreFunc.Error(ref ErrorsList, $"'{couponCode}' not found");
                    return(StatusCode(412, ErrorsList));
                }

                if (coupon.MaxUseQuantity == 0 || coupon.ExpiryDate < DateTime.UtcNow)
                {
                    CoreFunc.Error(ref ErrorsList, $"'{couponCode}' has expired");
                    return(StatusCode(412, ErrorsList));
                }

                return(Ok(coupon));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #17
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));
            }
        }
예제 #18
0
        public async Task <IActionResult> UpdateCurrentUserPassword([FromBody] UpdateCurrentUserData data)
        {
            try
            {
                _ = int.TryParse(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value, out int userId);
                User user = _DbContext.Users.Find(userId);


                if (!await _UserManager.CheckPasswordAsync(user, data.CurrentPassword).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Current Password is incorrect.");
                    return(StatusCode(412, ErrorsList));
                }


                user.Password = data.User.Password;
                User result = await UpdatePassword(user).ConfigureAwait(false);

                if (result == null)
                {
                    return(StatusCode(412, ErrorsList));
                }
                return(Ok(result));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #19
0
        public async Task <IActionResult> GetDisputeSecret(string disputeKey)
        {
            try
            {
                Communication dispute = await _DbContext.Communications
                                        .Include(c => c.Order)
                                        .ThenInclude(o => o.User)
                                        .Include(c => c.Order)
                                        .ThenInclude(o => o.OrderItems)
                                        .Include(c => c.Messages)
                                        .SingleOrDefaultAsync(c => c.Type == ContactType.Dispute && c.Id == disputeKey)
                                        .ConfigureAwait(false);

                if (dispute is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Dispute Not Found.");
                    return(StatusCode(412, ErrorsList));
                }

                return(Ok(dispute));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #20
0
        public async Task <IActionResult> ConfirmEmail([FromBody] string pathName)
        {
            try
            {
                string tokenValue = "";

                for (int i = pathName.Length - 1; i >= 0; i--)
                {
                    if (pathName[i] == '/')
                    {
                        i = -1;
                    }
                    else
                    {
                        tokenValue = pathName[i] + tokenValue;
                    }
                }

                Token token = await _DbContext.Tokens
                              .Include(t => t.User)
                              .FirstOrDefaultAsync(t => t.Url.Contains(pathName) && t.Value.Equals(tokenValue))
                              .ConfigureAwait(false);

                if (token == null || token.Type != Extras.CustomTypes.TokenTypes.ConfirmEmail)
                {
                    ErrorsList.Add(new Error("0", "Invalid Request/Token."));
                    return(StatusCode(412, ErrorsList));
                }

                if (token.ExpiaryDateTime < DateTime.UtcNow)
                {
                    ErrorsList.Add(new Error("0", "Token Expired"));
                    return(StatusCode(412, ErrorsList));
                }

                IdentityResult result = await _UserManager.ConfirmEmailAsync(token.User,
                                                                             await _UserManager.GenerateEmailConfirmationTokenAsync(token.User).ConfigureAwait(false))
                                        .ConfigureAwait(false);

                _DbContext.Entry(token.User).State = EntityState.Unchanged;
                _DbContext.Remove(entity: token);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                else
                {
                    ErrorsList.Add(new Error("0", "Unable to process your request."));
                    return(StatusCode(412, ErrorsList));
                }
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #21
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));
            }
        }
예제 #22
0
        public async Task <IActionResult> RequestPasswordReset([FromBody] string email)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(email))
                {
                    CoreFunc.Error(ref ErrorsList, "Email is required!");
                    return(StatusCode(412, ErrorsList));
                }

                User user = await _UserManager
                            .FindByEmailAsync(email).ConfigureAwait(false);

                if (user == null)
                {
                    CoreFunc.Error(ref ErrorsList, "Email not registered");
                    return(StatusCode(412, ErrorsList));
                }
                RegistrationMethod registrationMethod = await _DbContext.RegistrationMethods.FirstOrDefaultAsync(rm => rm.User.Id == user.Id).ConfigureAwait(false);

                if (registrationMethod.Type != RegistrationTypes.Application)
                {
                    CoreFunc.Error(ref ErrorsList, $"Your account is linked to your {registrationMethod.Type} account.");
                    return(StatusCode(412, ErrorsList));
                }

                if (user.LockoutEnabled)
                {
                    var currentLockoutDate =
                        await _UserManager.GetLockoutEndDateAsync(user).ConfigureAwait(false);

                    if (user.LockoutEnd > DateTimeOffset.UtcNow)
                    {
                        CoreFunc.Error(ref ErrorsList, string.Format("Account Locked for {0}"
                                                                     , CoreFunc.CompareWithCurrentTime(user.LockoutEnd)));
                        return(StatusCode(412, ErrorsList));
                    }
                    await _UserManager.SetLockoutEnabledAsync(user, false).ConfigureAwait(false);

                    await _UserManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
                }

                Request.Headers.TryGetValue("Origin", out StringValues OriginValue);
                if (!await _EmailService.PasswordResetAsync(user, OriginValue).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Unable to send email.");
                    return(StatusCode(417, ErrorsList));
                }

                return(Created("", "Created"));
            }

            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #23
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));
            }
        }
예제 #24
0
        public async Task <IActionResult> DownloadData([FromBody] string currentPassword)
        {
            try
            {
                User user = await _DbContext.Users
                            .Include(u => u.Role)
                            .Include(u => u.RegistrationMethod)
                            .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)).ConfigureAwait(false);


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

                List <Order> orders = await _DbContext.Orders
                                      .Include(o => o.User)
                                      .Include(o => o.OrderItems)
                                      .Include(o => o.Dispute)
                                      .ThenInclude(c => c.Messages)
                                      .Include(o => o.Payment)
                                      .Include(o => o.Coupon)
                                      .Where(u => u.User.Id == AppFunc.GetUserId(User)).ToListAsync().ConfigureAwait(false);

                List <Communication> questions = await _DbContext.Communications
                                                 .Include(c => c.Messages)
                                                 .Where(c => c.Email.ToUpper() == user.NormalizedEmail).ToListAsync().ConfigureAwait(false);

                List <Comment> comments = await _DbContext.Comments
                                          .Include(c => c.User)
                                          .Where(c => c.User.Id == user.Id).ToListAsync().ConfigureAwait(false);

                List <Address> addresses = await _DbContext.Addresses
                                           .Include(c => c.User)
                                           .Where(c => c.User.Id == user.Id).ToListAsync().ConfigureAwait(false);

                dynamic userData = new { userInfo = user, orders, questions, comments, addresses };
                return(Ok(JsonConvert.SerializeObject(userData, Formatting.Indented,
                                                      new JsonSerializerSettings
                {
                    Converters = new List <JsonConverter> {
                        new StringEnumConverter(), new DecimalFormatConverter()
                    },
                    ContractResolver = new DynamicContractResolver("Id", "Password", "AccessClaim", "OrderLength", "HasOrder"
                                                                   , "DeliveryOption", "Order_Id", "captchaToken", "AddressId", "UserId", "ProductId", "ImagePath", "ExternalLinkedId")
                })));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #25
0
        public async Task <IActionResult> Get(
            int selectedPage    = 1,
            int maxItemsPerPage = 5,
            string searchValue  = CoreConst.GetAllRecords,
            string filterRole   = CoreConst.GetAllRecords,
            bool isSortAsce     = true,
            string sortName     = "Name"
            )
        {
            try
            {
                _ = int.TryParse(filterRole, out int filterRoleId);
                int totalCount = await _DbContext.Users
                                 .Include(u => u.Role)
                                 .Where(u => filterRole.Equals(CoreConst.GetAllRecords) || u.Role.Id == filterRoleId)
                                 .CountAsync(u => searchValue.Equals(CoreConst.GetAllRecords) || (u.FirstName.Contains(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.Surname.Contains(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.Id.ToString().Equals(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.Email.Contains(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.PhoneNumber.Contains(searchValue))
                                             ).ConfigureAwait(false);

                List <User> list = await _DbContext.Users
                                   .Include(u => u.Role)
                                   .Include(u => u.RegistrationMethod)
                                   .Where(u => filterRole.Equals(CoreConst.GetAllRecords) || u.Role.Id == filterRoleId)
                                   .Where(u => searchValue.Equals(CoreConst.GetAllRecords) || u.FirstName.Contains(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.Surname.Contains(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.Id.ToString().Equals(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.Email.Contains(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.PhoneNumber.Contains(searchValue))
                                   .OrderByDynamic(sortName, isSortAsce)
                                   .Skip((selectedPage - 1) * maxItemsPerPage)
                                   .Take(maxItemsPerPage)
                                   .Include(u => u.Orders)
                                   .ToListAsync()
                                   .ConfigureAwait(false);

                list.ForEach(u =>
                {
                    u.OrderLength = u.Orders.Count(o => o.Status == OrderStatusType.Confirmed ||
                                                   o.Status == OrderStatusType.InProgress ||
                                                   (o.Dispute != null && o.Dispute.Status));
                    u.HasOrder = u.Orders.Count > 0;
                });

                return(Ok(new MultiResult <List <User>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
예제 #26
0
 [Authorize(AppConst.AccessPolicies.Public)] /// Ready For Test
 public async Task <IActionResult> All()
 {
     try
     {
         return(Ok(await _DbContext.DeliveryOptions.ToListAsync()));
     }
     catch (Exception ex)
     {
         CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
         return(StatusCode(417, ErrorsList));
     }
 }
예제 #27
0
 public async Task <IActionResult> AllSecret()
 {
     try
     {
         return(Ok(await _DbContext.Categories.ToListAsync().ConfigureAwait(false)));
     }
     catch (Exception ex)
     {
         CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
         return(StatusCode(417, ErrorsList));
     }
 }
예제 #28
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));
            }
        }
예제 #29
0
 [Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test
 public async Task <IActionResult> All()
 {
     try
     {
         return(Ok(await _DbContext.Addresses.
                   Where(t => t.User.Id == AppFunc.GetUserId(User)).ToListAsync()));
     }
     catch (Exception ex)
     {
         CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
         return(StatusCode(417, ErrorsList));
     }
 }
예제 #30
0
 public async Task <IActionResult> AllPublic()
 {
     try
     {
         return(Ok(await _DbContext.Categories.Include(c => c.Products)
                   .Where(c => c.Products.Count(p => p.Status) > 0)
                   .ToListAsync().ConfigureAwait(false)));
     }
     catch (Exception ex)
     {
         CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
         return(StatusCode(417, ErrorsList));
     }
 }