Exemplo n.º 1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new OSUser()
                {
                    UserName = model.Email, Email = model.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 2
0
 private async Task SignInAsync(OSUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties()
     {
         IsPersistent = isPersistent, AllowRefresh = true, ExpiresUtc = DateTimeOffset.Now.AddDays(2)
     }, await user.GenerateUserIdentityAsync(UserManager));
 }
Exemplo n.º 3
0
 private async Task SignInAsync(OSUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties()
     {
         IsPersistent = isPersistent
     }, await user.GenerateUserIdentityAsync(UserManager));
 }
        public ActionResult Index(OSUser osUser, string password)
        {
            try
            {
                osUser.LastUpdate = DateTime.Now;
                osUser.IsActive   = true;
                osUser.ImageFile  = "70x70.jpg";

                ViewBag.Success = true;

                // اختصاص کد کاربر
                osUser.Id = Guid.NewGuid().ToString();

                // اختصاص نقش Public به کاربر
                osUser.Roles.Add(new IdentityUserRole()
                {
                    RoleId = StaticValues.PublicRoleID, UserId = osUser.Id
                });

                // ایجاد کاربر
                var result = UserManager.Create(osUser, password);

                if (result.Succeeded)
                {
                    UserNotifications.Send(StaticValues.AdminID, String.Format("ثبت نام کاربر '{0}'", osUser.UserName), "/Admin/OSUsers/Edit/" + osUser.Id, NotificationType.Success);

                    if (!String.IsNullOrWhiteSpace(osUser.Mobile))
                    {
                        SMSServices.Register(osUser.Firstname,
                                             osUser.Lastname,
                                             osUser.UserName,
                                             password,
                                             osUser.Mobile,
                                             osUser.Id);
                    }

                    EmailServices.Register(osUser.Firstname,
                                           osUser.Lastname,
                                           osUser.UserName,
                                           password,
                                           osUser.Email,
                                           osUser.Id);
                }
                else
                {
                    throw new Exception(result.Errors.Aggregate((a, b) => a + ", " + b));
                }
            }
            catch (Exception ex)
            {
                SetErrors(ex);
            }

            return(View(url + "Index.cshtml"));
        }
Exemplo n.º 5
0
        private IdentityResult registerUser(ref OSUser osUser)
        {
            if (UserManager.FindByEmail(osUser.Email) == null)
            {
                osUser.UserName   = osUser.Email;
                osUser.LastUpdate = DateTime.Now;
                osUser.IsActive   = true;

                // اختصاص کد کاربر
                osUser.Id = Guid.NewGuid().ToString();

                // اختصاص نقش Public به کاربر
                osUser.Roles.Add(new IdentityUserRole()
                {
                    RoleId = StaticValues.PublicRoleID, UserId = osUser.Id
                });

                // ایجاد کاربر
                var password = new Random().Next(100000, 999999).ToString();
                var result   = UserManager.Create(osUser, password);

                if (!String.IsNullOrWhiteSpace(osUser.Mobile))
                {
                    SMSServices.Register(osUser.Firstname,
                                         osUser.Lastname,
                                         osUser.UserName,
                                         password,
                                         osUser.Mobile,
                                         osUser.Id);
                }

                EmailServices.Register(osUser.Firstname,
                                       osUser.Lastname,
                                       osUser.UserName,
                                       password,
                                       osUser.Email,
                                       osUser.Id);

                return(result);
            }
            else
            {
                osUser = UserManager.FindByEmail(osUser.Email);

                return(IdentityResult.Success);
            }
        }
Exemplo n.º 6
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new OSUser()
                {
                    UserName = model.Email, Email = model.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent : false);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Exemplo n.º 7
0
        private static void sendMessage(OSUser user, string saleReferenceID, Cart cart)
        {
            if (!String.IsNullOrWhiteSpace(user.Mobile))
            {
                SMSServices.SuccessfullPayment(user.Firstname,
                                               user.Lastname,
                                               saleReferenceID,
                                               user.Mobile,
                                               user.Id);
                // اطلاع رسانی به مدیر
                CartController.NotifyNewOrder(user, cart, saleReferenceID);
            }

            EmailServices.SuccessfullPayment(user.Firstname,
                                             user.Lastname,
                                             saleReferenceID,
                                             user.Email,
                                             user.Id);
        }
Exemplo n.º 8
0
        public static void NotifyNewOrder(OSUser user, Cart cart, string saleReferenceID)
        {
            var cartItems = CartItems.GetOrderDetails(cart.ID);

            var stateTitle = Cities.GetCityName(user.StateID.Value);
            var cityTitle  = Cities.GetCityName(user.CityID.Value);

            StringBuilder smsBody   = new StringBuilder();
            StringBuilder emailBody = new StringBuilder();

            #region SMS Body

            smsBody.Append("سفارش جدید: \n" + cart.ToPay.Value.ToPrice() + "\n");

            foreach (var item in cartItems)
            {
                smsBody.Append(item.ProductTitle);
                if (item.ProductVarentID.HasValue)
                {
                    smsBody.Append(" " + item.VarientTitle);
                }
                smsBody.Append("\n");
            }

            smsBody.Append(cart.PaymentMethodType.GetEnumDisplay() + "\n" + cart.SendMethodType.GetEnumDisplay());

            #endregion SMS Body

            #region Email Body

            emailBody.Append("سفارش جدید: <br/>" + cart.ToPay.Value.ToPrice() + "<br/>");
            emailBody.Append("محصولات: <br/>");

            foreach (var item in cartItems)
            {
                emailBody.Append(item.ProductTitle);
                if (item.ProductVarentID.HasValue)
                {
                    emailBody.Append(" " + item.VarientTitle);
                }
                emailBody.Append("<br/>");
            }

            emailBody.AppendFormat("نام و نام خانوادگی: {0} <br/>" +
                                   "{1}" +
                                   "شماره همراه: {2} <br/>" +
                                   "روش پرداخت: {3} <br/>" +
                                   "روش ارسال: {4} <br/>" +
                                   "استان: {5} <br/>" +
                                   "شهر: {6} <br/>" +
                                   "آدرس: {7}",
                                   user.Firstname + " " + user.Lastname,
                                   saleReferenceID != "-1" ? "کد رهگیری: " + saleReferenceID + "<br/>" : String.Empty,
                                   user.Mobile,
                                   cart.PaymentMethodType.GetEnumDisplay(),
                                   cart.SendMethodType.GetEnumDisplay(),
                                   stateTitle,
                                   cityTitle,
                                   user.HomeAddress);

            #endregion Email Body

            EmailServices.NotifyAdminsByEmail(AdminEmailType.NewOrder, emailBody.ToString(), user.Id);
            SMSServices.SendSMS("09120062417", smsBody.ToString(), user.Id);
        }
Exemplo n.º 9
0
        public JsonResult Payment(OSUser osUser, SendMethodType sendMethodType, PaymentMethodType paymentMethodType, string userDescription)
        {
            var jsonSuccessResult = new JsonSuccessResult();

            try
            {
                var payDate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
                var payTime = DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0');
                var orderID = payDate + payTime;

                string userID;
                int?   cityID;

                if (User.Identity.IsAuthenticated)
                {
                    userID = UserID;
                    cityID = OSUsers.GetByID(UserID).CityID;
                }
                else
                {
                    cityID = osUser.CityID;

                    IdentityResult result = registerUser(ref osUser);

                    if (result.Succeeded)
                    {
                        UserNotifications.Send(StaticValues.AdminID, String.Format("ثبت نام کاربر - در فرم سبد خرید '{0}'", osUser.UserName), "/Admin/OSUsers/Edit/" + osUser.Id, NotificationType.Success);
                        userID = osUser.Id;
                    }
                    else
                    {
                        throw new Exception(result.Errors.Aggregate((a, b) => a + ", " + b));
                    }
                }

                int total         = 0,
                    totalDiscount = 0,
                    delivaryPrice = -1;

                var cart      = GetCart(HttpContext);
                var cartItems = CartItems.GetByCartID(cart.ID, (User.Identity.IsAuthenticated ? userID : null));
                var listGifts = new List <CartItemGift>();

                foreach (var item in cartItems)
                {
                    var price = (item.DiscountPercent > 0 ? item.DiscountPrice : item.Price);

                    #region Update CartItem

                    var cartItem = CartItems.GetByID(item.ID);
                    cartItem.Price          = price;
                    cartItem.IsFreeDelivery = item.IsFreeDelivery;
                    CartItems.Update(cartItem);

                    #endregion Update CartItem

                    totalDiscount += item.Quantity * price;
                    total         += item.Quantity * item.Price;

                    foreach (var gift in item.Gifts)
                    {
                        listGifts.Add(new CartItemGift
                        {
                            CartItemID = item.ID,
                            GiftID     = gift.GiftID,
                            Price      = gift.Price,
                            LastUpdate = DateTime.Now
                        });
                    }
                }

                if (
                    (sendMethodType == SendMethodType.Free && cityID == 468) ||      // مشهد
                    (StaticValues.MaxPriceFreeDelivery && totalDiscount >= 10000) || // طرح های بالای ارسال
                    (cartItems.Any(a => a.IsFreeDelivery))                           // محصولات دارای ارسال رایگان
                    )
                {
                    delivaryPrice = 50000;
                }
                else
                {
                    delivaryPrice = StaticValues.DeliveryPrice;
                }

                // ثبت هدایا
                if (listGifts.Count > 0)
                {
                    CartItemGifts.Insert(listGifts);
                }

                var toPay = (totalDiscount + delivaryPrice);

                string refID = String.Empty;

                if (paymentMethodType == PaymentMethodType.Online)
                {
                    Logs.Alert(Utilities.GetIP(), "PaymentMethodType.Online", String.Format("payDate: {0}, payTime: {1}, orderID: {2}, toPay: {3}", payDate, payTime, orderID, toPay));
                    refID = connectToMellat(payDate, payTime, orderID, toPay);
                }

                #region Update Cart

                cart.UserID            = userID;
                cart.SendMethodType    = sendMethodType;
                cart.PaymentMethodType = paymentMethodType;
                cart.Tax             = Int32.Parse(StaticValues.Tax);
                cart.IP              = Utilities.GetIP();
                cart.UserDescription = userDescription;

                cart.Total         = total;
                cart.DelivaryPrice = delivaryPrice;
                cart.TotalDiscount = totalDiscount;
                cart.ToPay         = toPay;

                cart.DateTime = cart.LastUpdate = DateTime.Now;
                cart.CartGuid = null;

                if (paymentMethodType == PaymentMethodType.Online)
                {
                    cart.CartStatus = CartStatus.DuringPay;
                }
                else if (paymentMethodType == PaymentMethodType.Card || paymentMethodType == PaymentMethodType.Home)
                {
                    cart.CartStatus = CartStatus.FuturePay;
                }

                cart.SendStatus = SendStatus.NotChecked;
                cart.OrderID    = orderID;

                Carts.Update(cart);

                #endregion Update Cart

                logPaymentData(orderID, toPay, cart.ID);

                jsonSuccessResult.Success = true;

                if (paymentMethodType == PaymentMethodType.Online)
                {
                    jsonSuccessResult.Data = new
                    {
                        PgwSite = StaticValues.PgwSite,
                        RefID   = refID
                    }
                }
                ;
                else
                {
                    jsonSuccessResult.Data = new
                    {
                        ToPayPrice = toPay
                    };

                    OSUser user;
                    // اطلاع رسانی به مدیر سایت
                    if (User.Identity.IsAuthenticated)
                    {
                        user = OSUsers.GetByID(UserID);
                    }
                    else
                    {
                        user = osUser;
                    }

                    NotifyNewOrder(user, cart, "-1");
                }
            }
            catch (DbException ex)
            {
                jsonSuccessResult.Errors  = ex.Errors.ToArray();
                jsonSuccessResult.Success = false;

                Logs.Alert(Utilities.GetIP(), "Payment Error", ex.Errors.Aggregate((a, b) => a + ", " + b) + "_" + ex.StackTrace, LogType.Error);
            }
            catch (Exception ex)
            {
                jsonSuccessResult.Errors  = new string[] { ex.Message };
                jsonSuccessResult.Success = false;

                Logs.Alert(Utilities.GetIP(), "Payment Error", ex.Message + "_" + ex.StackTrace, LogType.Error);
            }

            return(new JsonResult()
            {
                Data = jsonSuccessResult,
            });
        }