Exemplo n.º 1
0
        bool saveDeal(Int64 bidId)
        {
            var order = Order.FetchByBidId(bidId);

            if (order != null && order.SupplierId > 0)
            {
                return(false);
            }

            decimal TotalPrice = order.TotalPrice;
            var     discount   = BidController.GetDiscountForUser(TotalPrice, order.AppUserId);
            var     supplier   = AppSupplier.FetchByID(312);
            string  response   = "";

            decimal PriceAfterDiscount = Convert.ToDecimal(discount["PriceAfterDiscount"]);
            decimal PrecentDiscount    = Convert.ToDecimal(discount["PrecentDiscount"]);
            Int64?  CampaignId         = Convert.ToInt64(discount["CampaignId"]);
            var     paymentDetails     = new PaymentDetails
            {
                Amount        = (float)PriceAfterDiscount * 100,
                CreditId      = order.Transaction,
                Exp           = order.ExpiryDate,
                AuthNumber    = order.AuthNumber,
                NumOfPayments = order.NumOfPayments,
                SupplierToken = supplier.MastercardCode
            };

            try
            {
                response = CreditGuardManager.CreateMPITransaction(paymentDetails);
            }
            catch
            {
                Notification.SendNotificationAppUserCreditRejected(order.AppUserId, bidId);
                return(false);
            }
            if (response != "000")
            {
                Notification.SendNotificationAppUserCreditRejected(order.AppUserId, bidId);
                return(false);
            }
            order.IsSendRecived = false;
            if (CampaignId != 0)
            {
                order.CampaignId = CampaignId;
            }
            order.TotalPrice         = TotalPrice;
            order.PriceAfterDiscount = PriceAfterDiscount;
            order.PrecentDiscount    = PrecentDiscount;
            // order.SpecialInstructions = special_instructions;
            order.UserPaySupplierStatus = UserPaymentStatus.Payed;
            order.SupplierId            = 312;
            order.Save();
            var bid = Bid.FetchByID(bidId);

            bid.IsActive = false;
            bid.Save();
            Notification.SendNotificationAppUserSupplierApproved(Snoopi.web.Localization.PushStrings.GetText("SupplierApproved"), bid.AppUserId.Value, order.OrderId);
            return(true);
        }
Exemplo n.º 2
0
        public static UserCreateResults CreateSupplier(string email, string password, Int64 CityId, out AppSupplier supplier)
        {
            supplier = null;
            if (!email.IsValidEmail())
            {
                return(UserCreateResults.InvalidEmailAddress);
            }
            supplier = AppSupplier.FetchByEmail(email);
            if (supplier != null)
            {
                return(UserCreateResults.AlreadyExists);
            }
            supplier                = new AppSupplier();
            supplier.Email          = email;
            supplier.UniqueIdString = email.NormalizeEmail();

            string pwd, salt;

            EncodePassword(password, out pwd, out salt);
            supplier.Password     = pwd;
            supplier.PasswordSalt = salt;

            try
            {
                supplier.AddressLocation = new Geometry.Point(0, 0);//TODO
                supplier.CityId          = CityId;
                supplier.Save();
                return(UserCreateResults.Success);
            }
            catch
            {
                supplier = null;
                return(UserCreateResults.UnknownError);
            }
        }
Exemplo n.º 3
0
        static public Membership.UserAuthenticateResults Login(string Email, string Password, bool GenerateRememberMeCookie)
        {
            Int64 SupplierId;

            Membership.UserAuthenticateResults results = Membership.AuthenticateSupplier(Email, Password, out SupplierId);
            if (results != Membership.UserAuthenticateResults.Success)
            {
                return(results);
            }

            AppSupplierAuthToken token = AuthTokens.GenerateAuthTokenForAppSupplierId(SupplierId, GenerateRememberMeCookie ? AuthTokenTimeSpan : 0);

            if (token == null)
            {
                return(Membership.UserAuthenticateResults.LoginError);
            }

            if (GenerateRememberMeCookie)
            {
                HttpCookie cookie = new HttpCookie(@"auth-token", TeaEncryptor.Encrypt(token.Secret.ToString(@"N") + @":" + token.Key, RememberMeCookieEncryptionKey));
                cookie.Expires = token.Expiry;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            HttpContext.Current.Session[@"Authenticated"] = true;
            HttpContext.Current.Session[@"AuthTokenId"]   = token.AppSupplierAuthTokenId;
            HttpContext.Current.Session[@"SupplierId"]    = SupplierId;
            AppSupplier supplier = AppSupplier.FetchByID(SupplierId);

            HttpContext.Current.Session[@"IsProductSupplier"] = (supplier != null ? supplier.IsProduct : false);
            //HttpContext.Current.Session[@"LangCode"] = dg.Sql.Query.New<AppSupplier>().Select(AppSupplier.Columns.LangCode).Where(AppSupplier.Columns.SupplierId, SupplierId).ExecuteScalar() as string;

            return(results);
        }
Exemplo n.º 4
0
    private void check_price_deviation(SupplierProduct sp)
    {
        decimal priceThrshold, deviationPercentage;

        decimal.TryParse(Settings.GetSetting(Settings.Keys.DEVIATION_LOWEST_THRESHOLD), out priceThrshold);
        decimal.TryParse(Settings.GetSetting(Settings.Keys.DEVIATION_PERCENTAGE), out deviationPercentage);
        var  product    = Product.FetchByID(sp.ProductId);
        var  deviation  = PriceDeviation.FetchByID(sp.SupplierId, sp.ProductId);
        bool isDeviated = product.RecomendedPrice > priceThrshold && sp.Price < product.RecomendedPrice * (100 - deviationPercentage) / 100;

        if (isDeviated)
        {
            var supplier = AppSupplier.FetchByID(sp.SupplierId);
            deviation                     = deviation ?? new PriceDeviation();
            deviation.ProductId           = sp.ProductId;
            deviation.ProductName         = product.ProductName;
            deviation.RecommendedPrice    = product.RecomendedPrice;
            deviation.SupplierId          = supplier.SupplierId;
            deviation.SupplierName        = supplier.BusinessName;
            deviation.ActualPrice         = sp.Price;
            deviation.DeviationPercentage = 100 - 100 * sp.Price / product.RecomendedPrice;
            deviation.IsApproved          = false;
            deviation.TimeOfApproval      = DateTime.MinValue;
            deviation.Save();
        }
        else if (deviation != null)
        {
            PriceDeviation.Delete(sp.SupplierId, sp.ProductId);
        }
    }
Exemplo n.º 5
0
        public static Order GenerateNewOrder(ProcessingResults results, long userId, long bidId, string gifts, long supplierId, decimal totalPrice, Source source)
        {
            //  var messageId = BIdMessageController.AddNewMessage(bidId, supplierId, 0, BIdMessageController.ADMIN_STAGE);
            var messageId = BIdMessageController.AddNewMessage(bidId, supplierId);

            var order = new Order
            {
                AppUserId             = userId,
                BidId                 = bidId,
                CreateDate            = DateTime.UtcNow,
                Last4Digits           = results.Last4Digits,
                UserPaySupplierStatus = UserPaymentStatus.NotPayed,
                TotalPrice            = totalPrice,
                Transaction           = results.CardToken,
                ExpiryDate            = results.CardExpiration,
                AuthNumber            = results.AuthNumber,
                Gifts                 = gifts,
                SpecialInstructions   = results.SpecialInstructions ?? "",
                NumOfPayments         = results.NumOfPayments,
                Source                = (int)source,
            };

            order.Save();

            AppUserCard paymentToken = AppUserCard.FetchByAppUserId(userId);

            if (paymentToken == null)
            {
                paymentToken = new AppUserCard();
            }
            paymentToken.AppUserId  = userId;
            paymentToken.CardToken  = results.CardToken;
            paymentToken.ExpiryDate = results.CardExpiration;
            paymentToken.Last4Digit = results.Last4Digits;
            if (!String.IsNullOrEmpty(results.PersonalId))
            {
                paymentToken.IdNumber = results.PersonalId;
            }
            paymentToken.Save();

            AppSupplier supplier = AppSupplier.FetchByID(supplierId);

            if (supplier != null)
            {
                supplier.MaxWinningsNum = (supplier.MaxWinningsNum > 0 ? supplier.MaxWinningsNum - 1 : 0);
                if (supplier.MaxWinningsNum == 0)
                {
                    // SupplierNotification.SendNotificationMaxAutoModeMessage(supplier.SupplierId);
                }
                supplier.Save();
            }
            SMSController.sendNewBidSMS(AppUser.FetchByID(userId).Phone);
            return(order);
        }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);

            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            string email = inputData.Value <string>(@"email") ?? "";

            Response.ContentType = @"application/json";

            string      key  = AppMembership.GenerateRecoveryKeySupplier(email);
            AppSupplier user = null;

            if (key != null)
            {
                user = AppSupplier.FetchByEmail(email);
            }

            if (key == null || user == null)
            {
                RespondNotFound(Response);
            }
            else
            {
                EmailMessagingService.SendPasswordRecoveryMailForSupplier(user, key, "he-IL");

                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        jsonWriter.WriteEndObject();
                    }
                }
            }
        }
Exemplo n.º 7
0
        static public string SupplierName()
        {
            Int64 supplierId = SupplierId();

            if (supplierId == 0)
            {
                return(null);
            }
            else
            {
                return(AppSupplier.FetchByID(supplierId).ContactName);
            }
        }
        static public void SendWelcomeMailWithVerificationForAppSupplier(AppSupplier user, string VerifyKey, string LangCode)
        {
            string        Key        = Settings.Keys.EMAIL_TEMPLATE_NEW_APPUSER_WELCOME_VERIFY_EMAIL;
            int           TemplateId = GetEmailTemplateIdFromSettingKey(Key, string.IsNullOrEmpty(LangCode) ? user.LangCode : LangCode);
            EmailTemplate template   = TemplateId == 0 ? null : EmailTemplateController.GetItem(TemplateId);

            if (template != null)
            {
                string fromEmail    = template.FromEmail;
                string fromName     = template.FromName;
                string replyToEmail = template.ReplyToEmail;
                string replyToName  = template.ReplyToName;
                string toList       = template.ToList + @";" + user.Email;
                if (string.IsNullOrEmpty(fromEmail))
                {
                    fromEmail = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_FROM);
                }
                if (string.IsNullOrEmpty(fromName))
                {
                    fromName = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_FROM_NAME);
                }
                if (string.IsNullOrEmpty(replyToEmail))
                {
                    replyToEmail = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_REPLYTO);
                }
                if (string.IsNullOrEmpty(replyToName))
                {
                    replyToName = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_REPLYTO_NAME);
                }

                Dictionary <string, string> dictFieldHtml = new Dictionary <string, string>();
                dictFieldHtml.Add(@"USERFULLNAME", user.ContactName.Trim());
                dictFieldHtml.Add(@"USEREMAIL", user.Email);
                dictFieldHtml.Add(@"PASSWORDKEY", VerifyKey);

                string subject = EmailTemplateController.ReplaceSharpsInString(template.Subject, dictFieldHtml);

                foreach (string key in dictFieldHtml.Keys)
                {
                    dictFieldHtml[key] = dictFieldHtml[key].ToHtml().Replace("\n", @"<br />");
                }
                string body = EmailTemplateController.ReplaceSharpsInString(template.Body, dictFieldHtml);

                System.Net.Mail.MailMessage message = EmailTemplateController.BuildMailMessage(
                    fromEmail, fromName, replyToEmail, replyToName,
                    toList, template.CcList, template.BccList, subject, body, null, template.MailPriority);
                EmailTemplateController.Send(message, EmailLogController.EmailLogType.OnError, true);
            }
        }
        static public void SendPasswordRecoveryMailForSupplier(AppSupplier user, string RecoveryKey, string LangCode = "he-IL")
        {
            string        Key        = Settings.Keys.EMAIL_TEMPLATE_SUPPLIER_FORGOT_PASSWORD;
            int           TemplateId = GetEmailTemplateIdFromSettingKey(Key, LangCode);
            EmailTemplate template   = TemplateId == 0 ? null : EmailTemplateController.GetItem(TemplateId);

            if (template != null)
            {
                string fromEmail    = template.FromEmail;
                string fromName     = template.FromName;
                string replyToEmail = template.ReplyToEmail;
                string replyToName  = template.ReplyToName;
                string toList       = template.ToList + @";" + user.Email;
                if (string.IsNullOrEmpty(fromEmail))
                {
                    fromEmail = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_FROM);
                }
                if (string.IsNullOrEmpty(fromName))
                {
                    fromName = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_FROM_NAME);
                }
                if (string.IsNullOrEmpty(replyToEmail))
                {
                    replyToEmail = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_REPLYTO);
                }
                if (string.IsNullOrEmpty(replyToName))
                {
                    replyToName = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_REPLYTO_NAME);
                }

                Dictionary <string, string> dictFieldHtml = new Dictionary <string, string>();
                dictFieldHtml.Add(@"USERFIRSTNAME", user.ContactName);
                dictFieldHtml.Add(@"USEREMAIL", user.Email);
                dictFieldHtml.Add(@"PASSWORDKEY", System.Net.WebUtility.HtmlEncode(RecoveryKey));

                string subject = EmailTemplateController.ReplaceSharpsInString(template.Subject, dictFieldHtml);

                //foreach (string key in dictFieldHtml.Keys)
                //{
                //    dictFieldHtml[key] = dictFieldHtml[key].ToHtml().Replace("\n", @"<br />");
                //}
                string body = EmailTemplateController.ReplaceSharpsInString(template.Body, dictFieldHtml);

                System.Net.Mail.MailMessage message = EmailTemplateController.BuildMailMessage(
                    fromEmail, fromName, replyToEmail, replyToName,
                    toList, template.CcList, template.BccList, subject, body, null, template.MailPriority);
                EmailTemplateController.Send(message, EmailLogController.EmailLogType.OnError, true);
            }
        }
Exemplo n.º 10
0
        protected void Page_PreRender(object sender, EventArgs e)
        {
            AppSupplier supplier = AppSupplier.FetchByID(SupplierId);

            if (supplier != null)
            {
                Master.PageTitleHtml = string.Format(CommentsStrings.GetText(@"CommentsSupplierPageTitle"), supplier.BusinessName);
            }
            else
            {
                Master.PageTitle = CommentsStrings.GetText(@"CommentsPageTitle");
            }
            Master.ActiveMenu = "Comments";

            Master.AddClientScriptInclude(@"dgDateManager.js");
        }
        static public void SendNewBidToSupplier(BidMessage msg)
        {
            string        Key        = Settings.Keys.EMAIL_TEMPLATE_SUPPLIER_NEW_BID;
            AppSupplier   supplier   = SupplierUI.FetchByID(msg.SupplierId);
            int           TemplateId = GetEmailTemplateIdFromSettingKey(Key, supplier.LangCode);
            EmailTemplate template   = TemplateId == 0 ? null : EmailTemplateController.GetItem(TemplateId);

            if (template != null)
            {
                string fromEmail    = template.FromEmail;
                string fromName     = template.FromName;
                string replyToEmail = template.ReplyToEmail;
                string replyToName  = template.ReplyToName;
                if (string.IsNullOrEmpty(fromEmail))
                {
                    fromEmail = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_FROM);
                }
                if (string.IsNullOrEmpty(fromName))
                {
                    fromName = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_FROM_NAME);
                }
                if (string.IsNullOrEmpty(replyToEmail))
                {
                    replyToEmail = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_REPLYTO);
                }
                if (string.IsNullOrEmpty(replyToName))
                {
                    replyToName = Settings.GetSetting(Settings.Keys.DEFAULT_EMAIL_REPLYTO_NAME);
                }

                Dictionary <string, string> dictFieldHtml = new Dictionary <string, string>();
                dictFieldHtml.Add(@"BIDID", msg.BidId.ToString());

                string subject = EmailTemplateController.ReplaceSharpsInString(template.Subject, dictFieldHtml);

                string body = EmailTemplateController.ReplaceSharpsInString(template.Body, dictFieldHtml);

                bool   isProduction = Convert.ToBoolean(AppConfig.GetString(@"IsProduction", @"false"));
                string emailTo      = isProduction ? supplier.Email:AppConfig.GetString(@"DevMailAddress", @"");
                System.Net.Mail.MailMessage message = EmailTemplateController.BuildMailMessage(
                    fromEmail, fromName, replyToEmail, replyToName,
                    emailTo, template.CcList, template.BccList, subject, body, null, template.MailPriority);

                EmailTemplateController.Send(message, EmailLogController.EmailLogType.OnError, true, 5);
            }
        }
Exemplo n.º 12
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            Int64       SupplierId = SuppliersSessionHelper.SupplierId();
            AppSupplier supplier   = AppSupplier.FetchByID(SupplierId);

            if (supplier.ApprovedTermsDate != null || !supplier.IsService)
            {
                Save(supplier);
            }
            else
            {
                Master.MessageCenter.DisplayErrorMessage(SupplierProfileStrings.GetText(@"ErrorApproveTerms"));
            }
        }
Exemplo n.º 13
0
 static public bool IsAuthenticated()
 {
     if (HttpContext.Current.Session[@"Authenticated"] != null && (bool)HttpContext.Current.Session[@"Authenticated"])
     {
         return(true);
     }
     else
     {
         HttpCookie cookie = HttpContext.Current.Request.Cookies[@"auth-token"];
         if (cookie != null)
         {
             string[] auth = TeaEncryptor.Decrypt(cookie.Value, RememberMeCookieEncryptionKey).Split(':');
             if (auth.Length == 2)
             {
                 Int64 SupplierId;
                 Int64 AuthTokenId;
                 if (AuthTokens.ValidateAppSupplierAuthToken(auth[0], auth[1], false, out SupplierId, out AuthTokenId))//TODO
                 {
                     Membership.UserAuthenticateResults results = Membership.SupplierLoggedInAction(SupplierId);
                     if (results == Membership.UserAuthenticateResults.Success)
                     {
                         HttpContext.Current.Session[@"Authenticated"] = true;
                         HttpContext.Current.Session[@"AuthTokenId"]   = AuthTokenId;
                         HttpContext.Current.Session[@"SupplierId"]    = SupplierId;
                         AppSupplier supplier = AppSupplier.FetchByID(SupplierId);
                         HttpContext.Current.Session[@"IsProductSupplier"] = (supplier != null ? supplier.IsProduct : false);
                         //HttpContext.Current.Session[@"LangCode"] = dg.Sql.Query.New<AppSupplier>().Select(AppSupplier.Columns.LangCode).Where(AppSupplier.Columns.SupplierId, SupplierId).ExecuteScalar() as string;
                         return(true);
                     }
                     else
                     {
                         AppSupplierAuthToken.Delete(AuthTokenId);
                         HttpContext.Current.Response.Cookies.Set(new HttpCookie(@"auth-token", @""));
                     }
                 }
                 else
                 {
                     HttpContext.Current.Response.Cookies.Set(new HttpCookie(@"auth-token", @""));
                 }
             }
         }
     }
     return(false);
 }
Exemplo n.º 14
0
 protected void btnTerms_Click(object sender, EventArgs e)
 {
     termsLoader.Visible = true;
     if (!Page.IsValid)
     {
         return;
     }
     if (ApproveTermsCb.Checked)
     {
         Int64       SupplierId = SuppliersSessionHelper.SupplierId();
         AppSupplier supplier   = AppSupplier.FetchByID(SupplierId);
         Save(supplier);
     }
     else
     {
         Response.Redirect("EditMyProfile.aspx");
         Master.MessageCenter.DisplayErrorMessage(SupplierProfileStrings.GetText(@"ErrorApproveTerms"));
     }
     termsLoader.Visible = false;
 }
Exemplo n.º 15
0
        protected override void VerifyAccessToThisPage()
        {
            string[] permissions = Permissions.PermissionsForUser(SessionHelper.UserId());
            if (!permissions.Contains(Permissions.PermissionKeys.sys_perm))
            {
                Master.LimitAccessToPage();
            }
            IsNewMode = Request.QueryString[@"New"] != null;

            if (!IsNewMode)
            {
                if (Int64.TryParse(Request.QueryString[@"SupplierId"], out SupplierId))
                {
                    AppSupplier supplier = AppSupplier.FetchByID(SupplierId);
                    if (supplier == null)
                    {
                        Master.LimitAccessToPage();
                    }
                }
            }
        }
Exemplo n.º 16
0
        protected void Page_Init(object sender, EventArgs e)
        {
            HasEditPermission = Permissions.PermissionsForUser(SessionHelper.UserId()).Contains(Permissions.PermissionKeys.sys_perm);

            dgBids.PageIndexChanged += dgBids_PageIndexChanging;

            if (Request.QueryString["id"] == "all")
            {
                AllBids    = true;
                SupplierId = -1;
            }
            else
            {
                if (!Int64.TryParse(Request.QueryString["Id"], out SupplierId))
                {
                    SupplierId = 0;
                }
                else
                {
                    AppSupplier s = AppSupplier.FetchByID(SupplierId);
                    if (s == null)
                    {
                        HasEditPermission = false;
                    }
                }
            }
            if (!String.IsNullOrEmpty(Request.QueryString["ToDate"]))
            {
                ToDate = Convert.ToDateTime(Request.QueryString["ToDate"].ToString().Replace("%2F", "/"));
            }
            if (!String.IsNullOrEmpty(Request.QueryString["FromDate"]))
            {
                FromDate = Convert.ToDateTime(Request.QueryString["FromDate"].ToString().Replace("%2F", "/"));
            }
            if (!String.IsNullOrEmpty(Request.QueryString["BidId"]))
            {
                BidId = Convert.ToInt64(Request.QueryString["BidId"].ToString());
            }
            Action = Request.QueryString["Action"];
        }
        protected override void VerifyAccessToThisPage()
        {
            string[] permissions = Permissions.PermissionsForUser(SessionHelper.UserId());
            HasSystemPermission = permissions.Contains(Permissions.PermissionKeys.sys_perm);

            if (Int64.TryParse(Request.QueryString[@"SupplierId"], out SupplierId))
            {
                AppSupplier supplier = core.DAL.AppSupplier.FetchByID(SupplierId);
                if (supplier == null)
                {
                    Master.LimitAccessToPage();
                }
                else
                {
                    SupplierName = supplier.Email;
                }
            }
            else
            {
                Master.LimitAccessToPage();
            }
        }
Exemplo n.º 18
0
        public static UserPasswordChangeResults ChangeSupplierPassword(string email, string newPassword)
        {
            AppSupplier supplier = AppSupplier.FetchByEmail(email);

            if (supplier == null)
            {
                return(UserPasswordChangeResults.UserDoesNotExist);
            }
            if (string.IsNullOrEmpty(supplier.PasswordSalt))
            {
                string pass, salt;
                EncodePassword(newPassword, out pass, out salt);
                supplier.Password     = pass;
                supplier.PasswordSalt = salt;
            }
            else
            {
                supplier.Password = EncodePassword(newPassword, supplier.PasswordSalt);
            }
            supplier.Save();
            return(UserPasswordChangeResults.Success);
        }
Exemplo n.º 19
0
 private void Save(AppSupplier supplier)
 {
     supplier.BusinessName = txtbusiness.Text;
     supplier.ContactName  = txtContactName.Text;
     supplier.Email        = txtEmail.Text;
     supplier.ContactPhone = txtContactPhone.Text;
     supplier.HouseNum     = txtNumber.Text;
     supplier.Street       = txtStreet.Text;
     supplier.CityId       = Convert.ToInt64(ddlCity.SelectedValue);
     supplier.Phone        = txtPhone.Text;
     supplier.Description  = txtDescription.Text;
     supplier.Discount     = txtDiscount.Text;
     if (txtPassword.Text.Trim() != "" && txtConfirmPassword.Text.Trim() != "")
     {
         string pwd, salt;
         AppMembership.EncodePassword(txtPassword.Text.Trim(), out pwd, out salt);
         supplier.Password     = pwd;
         supplier.PasswordSalt = salt;
     }
     if (supplier.IsService)
     {
         supplier.ApprovedTermsDate = DateTime.Now;
         if (fuImage.HasFile)
         {
             string fn = MediaUtility.SaveFile(fuImage.PostedFile, "SupplupCityier/225x225", 0, true);
             supplier.ProfileImage = fn;
             imgImage.ImageUrl     = Snoopi.core.MediaUtility.GetImagePath("Supplier", supplier.ProfileImage, 0, 225, 225);
             ImageFileHandler(fuImage, imgImage, btnDeleteImage, imgImage.ImageUrl);
         }
         else if (supplier.ProfileImage != "" && fuImage.Visible)
         {
             MediaUtility.DeleteImageFilePath("Supplier", supplier.ProfileImage, 225, 225, 0);
             supplier.ProfileImage = "";
         }
     }
     supplier.Save();
     Response.Redirect("MyProfile.aspx");
     Master.MessageCenter.DisplaySuccessMessage(SupplierProfileStrings.GetText(@"Success"));
 }
Exemplo n.º 20
0
        private void GetCities(Int64 SupplierId)
        {
            if (ddlCity.Items.Count == 0)
            {
                Query          q          = new Query(City.TableSchema).SelectAll().OrderBy(City.Columns.CityName, dg.Sql.SortDirection.ASC);
                CityCollection citiesList = CityCollection.FetchByQuery(q);

                Int64 selectedCityId = SupplierId == 0 ? citiesList[0].CityId : AppSupplier.FetchByID(SupplierId).CityId;

                int index = 0;
                foreach (City city in citiesList)
                {
                    ddlCity.Items.Add(new ListItem(city.CityName, city.CityId.ToString()));

                    //check if to select this item
                    if (selectedCityId == city.CityId)
                    {
                        ddlCity.Items[index].Selected = true;
                    }
                    index++;
                }
            }
        }
Exemplo n.º 21
0
        public static UserRecoveryResults SupplierVerifyRecoveryKey(string email, string key, string newPassword)
        {
            AppSupplier user = AppSupplier.FetchByEmail(email);

            if (user == null)
            {
                return(UserRecoveryResults.UserDoesNotExist);
            }

            if (user.PasswordRecoveryKey != key)
            {
                return(UserRecoveryResults.KeyDoNotMatch);
            }

            if (user.PasswordRecoveryDate.AddHours(RecoveryKeyLifeInHours) < DateTime.UtcNow)
            {
                return(UserRecoveryResults.Expired);
            }

            if (newPassword == null)
            {
                return(UserRecoveryResults.Success);
            }
            else
            {
                string pwd, salt;
                EncodePassword(newPassword, out pwd, out salt);
                user.Password             = pwd;
                user.PasswordSalt         = salt;
                user.PasswordRecoveryKey  = @"";
                user.PasswordRecoveryDate = DateTime.UtcNow;
                user.IsLocked             = false;
                user.Save();

                return(UserRecoveryResults.Success);
            }
        }
Exemplo n.º 22
0
        private void HandleAll(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            if (!Request.IsLocal)
            {
                Http.Respond404(true);
            }

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);

            if (PathParams[0] == @"rematch")
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        try
                        {
                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                        }
                        catch (System.Exception ex)
                        {
                            jsonWriter.WritePropertyName(@"error");
                            jsonWriter.WriteValue(@"unknown");
                            jsonWriter.WritePropertyName(@"description");
                            jsonWriter.WriteValue(ex.ToString());
                        }
                        jsonWriter.WriteEndObject();
                    }
                }
            }
            else if (PathParams[0] == @"clean_tokens")
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        try
                        {
                            AuthTokens.DeleteAllExpired();


                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                        }
                        catch (System.Exception ex)
                        {
                            jsonWriter.WritePropertyName(@"error");
                            jsonWriter.WriteValue(@"unknown");
                            jsonWriter.WritePropertyName(@"description");
                            jsonWriter.WriteValue(ex.ToString());
                        }
                        jsonWriter.WriteEndObject();
                    }
                }
            }
            else if (PathParams[0] == @"offer")
            {
                //using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                //{
                //    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                //    {
                //        jsonWriter.WriteStartObject();
                //        try
                //        {
                //            Query qry = new Query(Bid.TableSchema);
                //            qry.Where(Bid.Columns.IsSendOffer, WhereComparision.EqualsTo, false);
                //            qry.AddWhere(Bid.Columns.EndDate, WhereComparision.LessThan, DateTime.UtcNow);

                //            BidCollection bidCollection = BidCollection.FetchByQuery(qry);


                //            Query.New<Bid>().Where(Bid.Columns.IsSendOffer, WhereComparision.EqualsTo, false)
                //                .AddWhere(Bid.Columns.EndDate, WhereComparision.LessThan, DateTime.UtcNow)
                //                .Update(Bid.Columns.IsSendOffer, true)
                //                .Execute();

                //            foreach (Bid item in bidCollection)
                //            {
                //                Query q = new Query(Offer.TableSchema);
                //                q.Where(Offer.Columns.BidId, WhereComparision.EqualsTo, item.BidId);

                //                OfferCollection offerCollection = OfferCollection.FetchByQuery(q);
                //                if (offerCollection != null && offerCollection.Count > 0)
                //                {
                //                    if (item.AppUserId != null && item.AppUserId != 0)
                //                    {
                //                        Notification.SendNotificationAppUserOffers(string.Format(Snoopi.web.Localization.PushStrings.GetText("PushOfferText"), offerCollection.Count), (Int64)item.AppUserId, item.BidId);
                //                    }
                //                    else if (item.TempAppUserId != null && item.TempAppUserId != 0)
                //                    {
                //                        Notification.SendNotificationTempUserOffers(string.Format(Snoopi.web.Localization.PushStrings.GetText("PushOfferText"), offerCollection.Count), (Int64)item.TempAppUserId, item.BidId);
                //                    }
                //                }
                //                else
                //                {
                //                    if (item.AppUserId != null && item.AppUserId != 0)
                //                    {
                //                        Notification.SendNotificationAppUserOffers(Snoopi.web.Localization.PushStrings.GetText("NoPushOfferText"), (Int64)item.AppUserId, item.BidId);
                //                        AppUserUI user = AppUserUI.GetAppUserUI((Int64)item.AppUserId);
                //                        List<BidProductUI> products = BidController.GetProductsByBid(item.BidId);
                //                        Bid b = Bid.FetchByID(item.BidId);
                //                        string subject = GlobalStrings.GetText("MailToAdmin", new CultureInfo("he-IL"));
                //                        string body = GlobalStrings.GetText("SubjectMailToAdminOffers",new CultureInfo("he-IL"));
                //                        EmailMessagingService.SendMailNoOffersToAdmin(user, b.StartDate, products, subject, body);
                //                    }
                //                    else if (item.TempAppUserId != null && item.TempAppUserId != 0)
                //                    {
                //                        Notification.SendNotificationTempUserOffers(Snoopi.web.Localization.PushStrings.GetText("NoPushOfferText"), (Int64)item.TempAppUserId, item.BidId);
                //                    }

                //                }
                //                item.IsSendOffer = true;
                //                item.Save();

                //            }
                //            jsonWriter.WritePropertyName(@"success");
                //            jsonWriter.WriteValue(true);
                //        }
                //        catch (System.Exception ex)
                //        {
                //            //RespondError(Response, HttpStatusCode.BadRequest, ex.ToString());
                //            jsonWriter.WritePropertyName(@"error");
                //            jsonWriter.WriteValue(@"unknown");
                //            jsonWriter.WritePropertyName(@"description");
                //            jsonWriter.WriteValue(ex.ToString());
                //        }
                //        jsonWriter.WriteEndObject();
                //    }
                //}
            }
            else if (PathParams[0] == @"service_offer")
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        try
                        {
                            Query qry = new Query(BidService.TableSchema);
                            qry.Where(BidService.Columns.IsSendOffer, WhereComparision.EqualsTo, false);
                            qry.AddWhere(BidService.Columns.EndDate, WhereComparision.LessThan, DateTime.UtcNow);

                            BidServiceCollection bidCollection = BidServiceCollection.FetchByQuery(qry);
                            jsonWriter.WritePropertyName(@"qry");
                            jsonWriter.WriteValue(qry.ToString());

                            Query.New <BidService>().Where(BidService.Columns.IsSendOffer, WhereComparision.EqualsTo, false)
                            .AddWhere(BidService.Columns.EndDate, WhereComparision.LessThan, DateTime.UtcNow)
                            .Update(BidService.Columns.IsSendOffer, true)
                            .Execute();

                            foreach (BidService item in bidCollection)
                            {
                                Query q = new Query(OfferService.TableSchema);
                                q.Where(OfferService.Columns.BidId, WhereComparision.EqualsTo, item.BidId);

                                OfferServiceCollection offerCollection = OfferServiceCollection.FetchByQuery(q);
                                if (offerCollection != null && offerCollection.Count > 0)
                                {
                                    if (item.AppUserId != null && item.AppUserId != 0)
                                    {
                                        Notification.SendNotificationAppUserOffers(string.Format(Snoopi.web.Localization.PushStrings.GetText("PushOfferText"), offerCollection.Count), (Int64)item.AppUserId, item.BidId, true);
                                    }
                                    else if (item.TempAppUserId != null && item.TempAppUserId != 0)
                                    {
                                        Notification.SendNotificationTempUserOffers(string.Format(Snoopi.web.Localization.PushStrings.GetText("PushOfferText"), offerCollection.Count), (Int64)item.TempAppUserId, item.BidId, true);
                                    }
                                }
                                else
                                {
                                    if (item.AppUserId != null && item.AppUserId != 0)
                                    {
                                        Notification.SendNotificationAppUserOffers(Snoopi.web.Localization.PushStrings.GetText("NoPushOfferText"), (Int64)item.AppUserId, item.BidId, true);
                                        AppUserUI           user     = AppUserUI.GetAppUserUI((Int64)item.AppUserId);
                                        List <BidProductUI> products = BidController.GetProductsByBid(item.BidId);
                                        Bid    b       = Bid.FetchByID(item.BidId);
                                        string subject = GlobalStrings.GetText("MailToAdmin");
                                        string body    = GlobalStrings.GetText("SubjectMailToAdminOffers");
                                        EmailMessagingService.SendMailNoOffersToAdmin(user, b.StartDate, products, subject, body);
                                    }
                                    else if (item.TempAppUserId != null && item.TempAppUserId != 0)
                                    {
                                        Notification.SendNotificationTempUserOffers(Snoopi.web.Localization.PushStrings.GetText("NoPushOfferText"), (Int64)item.TempAppUserId, item.BidId, true);
                                    }
                                }
                                item.IsSendOffer = true;
                                item.Save();
                            }
                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                        }
                        catch (System.Exception ex)
                        {
                            //RespondError(Response, HttpStatusCode.BadRequest, ex.ToString());
                            jsonWriter.WritePropertyName(@"error");
                            jsonWriter.WriteValue(@"unknown");
                            jsonWriter.WritePropertyName(@"description");
                            jsonWriter.WriteValue(ex.ToString());
                        }
                        jsonWriter.WriteEndObject();
                    }
                }
            }
            else if (PathParams[0] == @"order_received")
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        try
                        {
                            Query qry = new Query(Order.TableSchema);
                            qry.Where(Order.Columns.IsSendRecived, WhereComparision.EqualsTo, false);
                            qry.AddWhere(Order.Columns.ReceivedDate, WhereComparision.EqualsTo, null);
                            qry.AddWhere(Order.Columns.UserPaySupplierStatus, WhereComparision.EqualsTo, UserPaymentStatus.Payed);
                            qry.AddWhere(Order.Columns.SuppliedDate, WhereComparision.LessThanOrEqual, DateTime.UtcNow.AddHours(-24));

                            OrderCollection orderCollection = OrderCollection.FetchByQuery(qry);

                            //Query.New<Order>().Where(Order.Columns.IsSendRecived, WhereComparision.EqualsTo, false)
                            //     .AddWhere(Order.Columns.ReceivedDate, WhereComparision.EqualsTo, null)
                            //     .AddWhere(Order.Columns.CreateDate, WhereComparision.LessThanOrEqual, DateTime.UtcNow.AddHours(-24))
                            //     .Update(Order.Columns.IsSendRecived, true)
                            //     .Execute();

                            foreach (Order item in orderCollection)
                            {
                                Notification.SendNotificationAppUserReceviedOrder(Snoopi.web.Localization.PushStrings.GetText("ReceivedOrder"), (Int64)item.AppUserId, item.OrderId);
                                item.IsSendRecived = true;
                                item.Save();
                            }

                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                        }
                        catch (System.Exception ex)
                        {
                            //RespondError(Response, HttpStatusCode.BadRequest, ex.ToString());
                            jsonWriter.WritePropertyName(@"error");
                            jsonWriter.WriteValue(@"unknown");
                            jsonWriter.WritePropertyName(@"description");
                            jsonWriter.WriteValue(ex.ToString());
                        }
                        jsonWriter.WriteEndObject();
                    }
                }
            }
            else if (PathParams[0] == @"auto_push")
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        try
                        {
                            var filters = NotificationGroups.GetAutoFilters();
                            foreach (var item in filters)
                            {
                                if (item.LastRun == null || item.LastRun.Value.AddDays(1) < DateTime.Now)
                                {
                                    var users = NotificationGroups.GetUsersOfAutoFilter(item);
                                    try
                                    {
                                        Task.Run(() => Snoopi.core.FcmService.SendTemplateToMany(item.Name, item.MessageTemplate, users)).Wait();
                                    }
                                    catch (Exception ex)
                                    {
                                        using (System.IO.StreamWriter sw = System.IO.File.AppendText(AppDomain.CurrentDomain.BaseDirectory + @"\Output\push-log.txt"))
                                        {
                                            sw.WriteLine(@" ------------" + DateTime.Now + "--------------------" + '\n' + "Exception  " + ex.Message + " CallStack : " + ex.StackTrace);
                                        }
                                    }
                                    item.LastRun = DateTime.Now;
                                    item.Save();
                                }
                            }

                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                        }
                        catch (System.Exception ex)
                        {
                            //RespondError(Response, HttpStatusCode.BadRequest, ex.ToString());
                            jsonWriter.WritePropertyName(@"error");
                            jsonWriter.WriteValue(@"unknown");
                            jsonWriter.WritePropertyName(@"description");
                            jsonWriter.WriteValue(ex.ToString());
                        }
                        jsonWriter.WriteEndObject();
                    }
                }
            }
            else if (PathParams[0] == @"rate_supplier")
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        try
                        {
                            Query qry = new Query(Order.TableSchema);
                            qry.Where(Order.Columns.IsSendRateSupplier, WhereComparision.EqualsTo, false);
                            qry.AddWhere(Order.Columns.SuppliedDate, WhereComparision.LessThanOrEqual, DateTime.UtcNow.AddHours(-Settings.GetSettingInt32(Settings.Keys.RATE_SUPPLIER_AFTER_ORDER_HOUR, 24)));

                            OrderCollection orderCollection = OrderCollection.FetchByQuery(qry);

                            Query.New <Order>().Where(Order.Columns.IsSendRateSupplier, WhereComparision.EqualsTo, false)
                            .AddWhere(Order.Columns.SuppliedDate, WhereComparision.LessThanOrEqual, DateTime.UtcNow.AddHours(-Settings.GetSettingInt32(Settings.Keys.RATE_SUPPLIER_AFTER_ORDER_HOUR, 24)))
                            .Update(Order.Columns.IsSendRateSupplier, true)
                            .Execute();

                            foreach (Order item in orderCollection)
                            {
                                var         bid      = Bid.FetchByID(item.BidId);
                                AppSupplier supplier = AppSupplier.FetchByID(item.SupplierId);
                                Notification.SendNotificationAppUserRateSupplier(Snoopi.web.Localization.PushStrings.GetText("RateSupplier"), item.AppUserId, item.SupplierId.Value, supplier.BusinessName, item.BidId);
                                item.IsSendRateSupplier = true;
                                item.Save();
                            }

                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                        }
                        catch (System.Exception ex)
                        {
                            //RespondError(Response, HttpStatusCode.BadRequest, ex.ToString());
                            jsonWriter.WritePropertyName(@"error");
                            jsonWriter.WriteValue(@"unknown");
                            jsonWriter.WritePropertyName(@"description");
                            jsonWriter.WriteValue(ex.ToString());
                        }
                        jsonWriter.WriteEndObject();
                    }
                }
            }
            else if (PathParams[0] == @"test_rate_supplier")
            {
                Notification.SendNotificationAppUserRateSupplier(Snoopi.web.Localization.PushStrings.GetText("RateSupplier"), 18283, 387, "PetBool", 2345);
            }
            else
            {
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        jsonWriter.WriteStartObject();
                        jsonWriter.WritePropertyName(@"error");
                        jsonWriter.WriteValue(@"unknown");
                        jsonWriter.WriteEndObject();
                    }
                }
            }
        }
Exemplo n.º 23
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            string SupplierEmail = null;
            bool   EmailChanged  = false;

            AppSupplier supplier = null;

            if (IsNewMode)
            {
                Membership.UserCreateResults results = Membership.CreateSupplier(txtEmail.Text, txtPassword.Text.Trim(), Convert.ToInt64(ddlCity.SelectedValue), out supplier);
                switch (results)
                {
                default:
                case Membership.UserCreateResults.UnknownError:
                    Master.MessageCenter.DisplayErrorMessage(SuppliersStrings.GetText(@"MessageCreateFailedUnknown"));
                    return;

                case Membership.UserCreateResults.AlreadyExists:
                    Master.MessageCenter.DisplayErrorMessage(SuppliersStrings.GetText(@"MessageCreateFailedAlreadyExists"));
                    return;

                case Membership.UserCreateResults.InvalidEmailAddress:
                    Master.MessageCenter.DisplayErrorMessage(SuppliersStrings.GetText(@"MessageCreateFailedEmailAddressInvalid"));
                    return;

                case Membership.UserCreateResults.Success:
                    break;
                }
                SupplierId    = supplier.SupplierId;
                SupplierEmail = supplier.Email;
                //supplier.OrderDisplay = OrderDisplay.GetLastOrder() + 1;
            }
            else
            {
                supplier      = core.DAL.AppSupplier.FetchByID(SupplierId);
                SupplierEmail = supplier.Email;
            }
            supplier.BusinessName = txtBusinessName.Text;

            if (ddlIsProduct.SelectedValue == "prod")
            {
                supplier.IsProduct = true;
                supplier.IsService = false;
            }
            else
            {
                supplier.IsProduct = false;
                supplier.IsService = true;
            }
            //supplier.IsProduct = chkIsProduct.Checked;
            //supplier.IsService = chkIsService.Checked;
            supplier.IsPremium    = chkIsPremium.Checked;
            supplier.IsLocked     = chkIsLocked.Checked;
            supplier.ContactName  = txtContactName.Text;
            supplier.ContactPhone = txtContactPhone.Text;
            supplier.Phone        = txtPhone.Text;
            supplier.CityId       = Convert.ToInt64(ddlCity.SelectedValue);
            supplier.Street       = txtStreet.Text;
            supplier.HouseNum     = txtHouseNum.Text;
            try
            {
                string city = ddlCity.SelectedItem.Text;
                //var address = (city != "" ? city + " " : "") +" "+ (txtStreet.Text != "" ? txtStreet.Text+" " : "") + (txtHouseNum.Text != "" ? txtHouseNum.Text : "");
                var locationService = new GoogleLocationService();
                var point           = (city.Trim() != "" ? locationService.GetLatLongFromAddress(city) : new MapPoint());
                supplier.AddressLocation = new Geometry.Point(point.Latitude, point.Longitude);
            }
            catch (Exception) {
                supplier.AddressLocation = new Geometry.Point(0, 0);
            }
            supplier.HouseNum = txtHouseNum.Text;

            supplier.Precent     = txtPrecent.Text != "" ?Convert.ToInt32(txtPrecent.Text):0;
            supplier.SumPerMonth = txtSumPerMonth.Text != "" ? Convert.ToInt32(txtSumPerMonth.Text) : 0;
            //supplier.StatusJoinBid = chkIsStatusJoinBid.Checked;
            //supplier.AllowChangeStatusJoinBid = chkAllowChangeStatusJoinBid.Checked;
            //supplier.MaxWinningsNum =txtMaxWinningsNum.Text != "" ? Convert.ToInt32(txtMaxWinningsNum.Text) : 0;
            supplier.MastercardCode = txtMastercardCode.Text;
            supplier.Save();

            if (IsNewMode)
            {
                SupplierId = supplier.SupplierId;
                //if (chkIsStatusJoinBid.Checked == false)//handel
                //{
                //    (new Query(SupplierProduct.TableSchema).Where(SupplierProduct.Columns.SupplierId, SupplierId).Delete()).Execute();
                //    ProductCollection pcol = ProductCollection.FetchByQuery(new Query(Product.TableSchema).Where(Product.Columns.IsDeleted, false));
                //    foreach (Product item in pcol)
                //    {
                //        SupplierProduct sp = new SupplierProduct();
                //        sp.SupplierId = SupplierId;
                //        sp.ProductId = item.ProductId;
                //        sp.Gift = "";
                //        sp.Save();
                //    }
                //}
            }
            //if (chkIsService.Checked)
            if (ddlIsProduct.SelectedValue != "prod")
            {
                foreach (ListItem item in ddlServices.Items)
                {
                    if (item.Selected)
                    {
                        SupplierService supplierService = SupplierService.FetchByID(Convert.ToInt64(item.Value), SupplierId);
                        if (supplierService == null)
                        {
                            supplierService            = new SupplierService();
                            supplierService.SupplierId = SupplierId;
                            supplierService.ServiceId  = Convert.ToInt64(item.Value);
                            supplierService.Save();
                        }
                    }
                    else
                    {
                        SupplierService.Delete(Convert.ToInt64(item.Value), SupplierId);
                    }
                }
            }
            else
            {
                SupplierController.DeleteAllSupplierServices(SupplierId);
            }

            if (supplier.Email != txtEmail.Text.Trim().NormalizeEmail())
            {
                if (AppSupplier.FetchByEmail(txtEmail.Text.Trim().NormalizeEmail()) != null)
                {
                    Master.MessageCenter.DisplayWarningMessage(AppUsersStrings.GetText(@"MessageEmailChangeFailed"));
                }
                else
                {
                    supplier.Email          = txtEmail.Text.Trim().NormalizeEmail();
                    supplier.UniqueIdString = supplier.Email;//email.NormalizeEmail();
                    SupplierEmail           = supplier.Email;
                    EmailChanged            = true;
                }
            }

            SupplierEmail = supplier.Email;
            supplier.Save();

            if (txtPassword.Text.Length > 0)
            {
                if (txtConfirmPassword.Text != txtPassword.Text)
                {
                    Master.MessageCenter.DisplayErrorMessage(SuppliersStrings.GetText(@"SupplierNewPasswordConfirmInvalid"));
                    return;
                }
                Membership.UserPasswordChangeResults results;
                results = Membership.ChangeSupplierPassword(supplier.Email, txtPassword.Text);
                switch (results)
                {
                default:
                    Master.MessageCenter.DisplayWarningMessage(SuppliersStrings.GetText(@"MessagePasswordChangeFailedUnknown"));
                    break;

                case Membership.UserPasswordChangeResults.PasswordDoNotMatch:
                    Master.MessageCenter.DisplayWarningMessage(SuppliersStrings.GetText(@"MessagePasswordChangeBadOldPassword"));
                    break;

                case Membership.UserPasswordChangeResults.Success:
                    break;
                }
            }

            if (IsNewMode)
            {
                string successMessage = SuppliersStrings.GetText(@"MessageSupplierCreated");
                string url            = @"EditSupplier.aspx?Email=" + SupplierEmail + "&SupplierId=" + supplier.SupplierId;
                url += @"&message-success=" + Server.UrlEncode(successMessage);
                Response.Redirect(url, true);
            }
            else
            {
                string successMessage = SuppliersStrings.GetText(@"MessageSupplierSaved");
                if (EmailChanged)
                {
                    string url = @"EditSupplier.aspx?message-success=" + Server.UrlEncode(successMessage) + "&SupplierId=" + supplier.SupplierId;
                    if (SupplierId != supplier.SupplierId)
                    {
                        url += @"&Email=" + SupplierEmail;
                    }
                    Response.Redirect(url, true);
                }
                else
                {
                    Master.MessageCenter.DisplaySuccessMessage(successMessage);
                    LoadView();
                }
            }
        }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Int64 AppUserId;

            if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
            {
                Response.ContentType = @"application/json";

                try
                {
                    JToken jt;
                    string card_tk = null, expire_date = null, last4_digits = null, id_number = null, special_instructions = null;
                    Int64  order_id            = 0;
                    bool   is_payment_succesed = true;
                    if (inputData.TryGetValue(@"is_payment_succesed", out jt))
                    {
                        is_payment_succesed = jt.Value <bool>();
                    }
                    if (is_payment_succesed)
                    {
                        if (inputData.TryGetValue(@"card_tk", out jt))
                        {
                            card_tk = jt.Value <string>();
                        }
                        if (inputData.TryGetValue(@"expire_date", out jt))
                        {
                            expire_date = jt.Value <string>();
                        }
                        if (inputData.TryGetValue(@"last4_digits", out jt))
                        {
                            last4_digits = jt.Value <string>();
                        }
                        if (inputData.TryGetValue(@"id_number", out jt))
                        {
                            id_number = jt.Value <string>();
                        }
                    }
                    if (inputData.TryGetValue(@"order_id", out jt))
                    {
                        order_id = jt.Value <Int64>();
                    }



                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            if (Order.FetchByOrderId(order_id) == null)
                            {
                                RespondError(Response, HttpStatusCode.BadRequest, @"order not exist");
                            }
                            Order order = Order.FetchByOrderId(order_id);
                            if (is_payment_succesed)
                            {
                                AppUserCard paymentToken = AppUserCard.FetchByAppUserId(AppUserId);
                                if (paymentToken == null)
                                {
                                    paymentToken = new AppUserCard();
                                }
                                paymentToken.AppUserId  = AppUserId;
                                paymentToken.CardToken  = card_tk;
                                paymentToken.ExpiryDate = expire_date;
                                paymentToken.Last4Digit = last4_digits;
                                if (!String.IsNullOrEmpty(id_number))
                                {
                                    paymentToken.IdNumber = id_number;
                                }
                                paymentToken.Save();

                                order.Transaction           = card_tk;
                                order.Last4Digits           = last4_digits;
                                order.ExpiryDate            = expire_date;
                                order.AppUserId             = AppUserId;
                                order.UserPaySupplierStatus = UserPaymentStatus.Payed;
                            }
                            else
                            {
                                order.UserPaySupplierStatus = UserPaymentStatus.NotPayed;
                            }
                            order.Save();

                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"order_id");
                            jsonWriter.WriteValue(order.OrderId);
                            jsonWriter.WriteEndObject();

                            long supplierId = 0; // need to update from offer
                            SupplierNotification.SendNotificationCloseBidToSupplier(order.OrderId, supplierId);

                            AppSupplier supplier = AppSupplier.FetchByID(supplierId);
                            if (supplier != null && supplier.StatusJoinBid == true)
                            {
                                supplier.MaxWinningsNum = (supplier.MaxWinningsNum > 0 ? supplier.MaxWinningsNum - 1 : 0);
                                if (supplier.MaxWinningsNum == 0)
                                {
                                    SupplierNotification.SendNotificationMaxAutoModeMessage(supplier.SupplierId);
                                    supplier.StatusJoinBid = false;
                                }
                                supplier.Save();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    RespondError(Response, HttpStatusCode.InternalServerError, @"db-error");
                }
            }
        }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Int64 AppUserId;

            if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
            {
                Response.ContentType = @"application/json";

                try
                {
                    JToken jt;
                    string response_code = null, card_tk = null, expire_date = null, last4_digits = null, id_number = null, special_instructions = null, response_error_message = null;
                    Int64  bid_id = 0, offer_id = 0, donation_id = 0;
                    Int64  campaign_id = 0;
                    //if (inputData.TryGetValue(@"response_code", out jt)) response_code = jt.Value<string>();
                    //if (inputData.TryGetValue(@"response_error_message", out jt)) response_error_message = jt.Value<string>();
                    if (inputData.TryGetValue(@"card_tk", out jt))
                    {
                        card_tk = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"expire_date", out jt))
                    {
                        expire_date = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"special_instructions", out jt))
                    {
                        special_instructions = Regex.Replace(jt.Value <string>(), @"\p{Cs}", "");
                    }
                    if (inputData.TryGetValue(@"last4_digits", out jt))
                    {
                        last4_digits = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"id_number", out jt))
                    {
                        id_number = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"bid_id", out jt))
                    {
                        bid_id = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"offer_id", out jt))
                    {
                        offer_id = jt.Value <Int64>();
                    }
                    //if (inputData.TryGetValue(@"donation_id", out jt)) donation_id = jt.Value<Int64>();
                    if (inputData.TryGetValue(@"campaign_id", out jt) && jt != null)
                    {
                        campaign_id = jt.Value <Int64?>() ?? 0;
                    }


                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            if (Order.FetchByBidId(bid_id) != null)
                            {
                                RespondError(Response, HttpStatusCode.BadRequest, @"already-order");
                            }
                            Order order = new Order();
                            //if (response_code == OrderController.RESPONSE_CODE_OK)
                            //{
                            AppUserCard paymentToken = AppUserCard.FetchByAppUserId(AppUserId);
                            if (paymentToken == null)
                            {
                                paymentToken = new AppUserCard();
                            }
                            paymentToken.AppUserId  = AppUserId;
                            paymentToken.CardToken  = card_tk;
                            paymentToken.ExpiryDate = expire_date;
                            paymentToken.Last4Digit = last4_digits;
                            if (!String.IsNullOrEmpty(id_number))
                            {
                                paymentToken.IdNumber = id_number;
                            }
                            paymentToken.Save();
                            // }


                            Dictionary <string, string> result = BidController.GetDiscount(offer_id, AppUserId);

                            decimal TotalPrice = result["TotalPrice"] != null?Convert.ToDecimal(result["TotalPrice"].ToString()) : 0;

                            decimal PriceAfterDiscount = result["PriceAfterDiscount"] != null?Convert.ToDecimal(result["PriceAfterDiscount"].ToString()) : 0;

                            decimal PrecentDiscount = result["PrecentDiscount"] != null?Convert.ToDecimal(result["PrecentDiscount"].ToString()) : 0;

                            Int64?CampaignId = result["CampaignId"] != null ? (Int64?)Convert.ToInt64(result["CampaignId"].ToString()) : null;
                            if (CampaignId != 0)
                            {
                                order.CampaignId = CampaignId;
                            }
                            order.TotalPrice         = TotalPrice;
                            order.PriceAfterDiscount = PriceAfterDiscount;
                            order.PrecentDiscount    = PrecentDiscount;
                            order.BidId = bid_id;
                            order.SpecialInstructions = special_instructions;
                            //order.TransactionResponseCode = response_code;
                            //order.TransactionErrorMessage = response_error_message;
                            order.Transaction = card_tk;
                            //switch (response_code)
                            //{
                            //    case OrderController.RESPONSE_CODE_OK: order.TransactionStatus = OrderStatus.Payed;
                            //        break;
                            //    case OrderController.RESPONSE_CODE_ERROR: order.TransactionStatus = OrderStatus.NotPayed;
                            //        break;
                            //    default: order.TransactionStatus = OrderStatus.NotPayed;
                            //        break;
                            //}
                            // if (donation_id != 0) order.DonationId = donation_id;
                            order.Last4Digits = last4_digits;
                            order.ExpiryDate  = expire_date;
                            order.AppUserId   = AppUserId;
                            order.Save();

                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"order_id");
                            jsonWriter.WriteValue(order.OrderId);
                            jsonWriter.WriteEndObject();


                            if (campaign_id != null && campaign_id != 0)
                            {
                                AppUserCampaign appUserCampaign = new AppUserCampaign();
                                appUserCampaign.AppUserId  = AppUserId;
                                appUserCampaign.CampaignId = campaign_id;
                                appUserCampaign.Save();
                            }

                            Offer offer = Offer.FetchByID(offer_id);
                            // SupplierNotification.SendNotificationCloseBidToSupplier(order.OrderId, offer.SupplierId);

                            AppSupplier supplier = AppSupplier.FetchByID(offer.SupplierId);
                            if (supplier != null && supplier.StatusJoinBid == true)
                            {
                                supplier.MaxWinningsNum = (supplier.MaxWinningsNum > 0 ? supplier.MaxWinningsNum - 1 : 0);
                                if (supplier.MaxWinningsNum == 0)
                                {
                                    SupplierNotification.SendNotificationMaxAutoModeMessage(supplier.SupplierId);
                                    supplier.StatusJoinBid = false;
                                }
                                supplier.Save();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    RespondError(Response, HttpStatusCode.InternalServerError, @"db-error");
                }
            }
        }
Exemplo n.º 26
0
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Int64 supplierId;

            if (IsAuthorizedRequestSupplier(Request, Response, true, out supplierId))
            {
                Response.ContentType = @"application/json";

                try
                {
                    JToken jt;
                    Int64  bidId      = 0;
                    bool   isApproved = false;
                    if (inputData.TryGetValue(@"bid_id", out jt))
                    {
                        bidId = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"is_approved", out jt))
                    {
                        isApproved = jt.Value <bool>();
                    }
                    var supplier = AppSupplier.FetchByID(supplierId);
                    var bid      = Bid.FetchByID(bidId);
                    if (bid.IsActive == false)
                    {
                        RespondError(Response, HttpStatusCode.NotAcceptable, @"inactive-bid");
                    }
                    long   orderId  = 0;
                    string response = "";
                    if (isApproved)
                    {
                        var order   = Order.FetchByBidId(bidId);
                        var offerUi = SupplierController.GetBidOfferById(bidId, supplierId);
                        if (offerUi == null || offerUi.BidId <= 0)
                        {
                            RespondError(Response, HttpStatusCode.NotAcceptable, @"inactive-bid");
                        }
                        decimal TotalPrice         = offerUi.TotalPrice;
                        var     discount           = BidController.GetDiscountForUser(TotalPrice, bid.AppUserId.Value);
                        decimal PriceAfterDiscount = Convert.ToDecimal(discount["PriceAfterDiscount"]);
                        decimal PrecentDiscount    = Convert.ToDecimal(discount["PrecentDiscount"]);
                        Int64?  CampaignId         = Convert.ToInt64(discount["CampaignId"]);
                        var     paymentDetails     = new PaymentDetails
                        {
                            Amount        = (float)PriceAfterDiscount * 100,
                            CreditId      = order.Transaction,
                            Exp           = order.ExpiryDate,
                            AuthNumber    = order.AuthNumber,
                            NumOfPayments = order.NumOfPayments,
                            SupplierToken = supplier.MastercardCode
                        };
                        try
                        {
                            response = CreditGuardManager.CreateMPITransaction(paymentDetails);
                        }
                        catch (Exception ex)
                        {
                            Helpers.LogProcessing("SupplierBidApprovalHandler - ex -", "\n exception: " + ex.ToString(), true);

                            endRequest(Response, order.AppUserId, bidId);
                        }
                        if (response != "000")
                        {
                            endRequest(Response, order.AppUserId, bidId);
                        }
                        order.IsSendRecived = false;
                        if (CampaignId != 0)
                        {
                            order.CampaignId = CampaignId;
                        }
                        order.TotalPrice         = TotalPrice;
                        order.PriceAfterDiscount = PriceAfterDiscount;
                        order.PrecentDiscount    = PrecentDiscount;
                        order.CreateDate         = DateTime.UtcNow;
                        // order.SpecialInstructions = special_instructions;
                        order.BidId                 = bidId;
                        order.AppUserId             = bid.AppUserId.Value;
                        order.UserPaySupplierStatus = UserPaymentStatus.Payed;
                        order.SupplierId            = supplierId;
                        order.Save();
                        bid.IsActive = false;
                        bid.Save();
                        var message = BIdMessageController.GetMessageByBidAndSupplier(bidId, supplierId);
                        message.IsActive = false;
                        message.Save();
                        orderId = order.OrderId;
                        //Notification.SendNotificationAppUserSupplierApproved(Snoopi.web.Localization.PushStrings.GetText("SupplierApproved"), bid.AppUserId.Value, order.OrderId);
                    }

                    else
                    {
                        var message = BIdMessageController.GetMessageByBidAndSupplier(bidId, supplierId);
                        message.ExpirationTime = DateTime.Now.AddHours(-1);
                        message.Save();
                    }

                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"success");
                            jsonWriter.WriteValue(true);
                            jsonWriter.WritePropertyName(@"order_id");
                            jsonWriter.WriteValue(orderId);
                            jsonWriter.WriteEndObject();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Helpers.LogProcessing("SupplierBidApprovalHandler - ex -", "\n exception: " + ex.ToString(), true);
                    RespondError(Response, HttpStatusCode.NotAcceptable, @"inactive-bid");
                }
            }
        }
Exemplo n.º 27
0
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Int64 AppUserId;

            if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
            {
                Response.ContentType = @"application/json";

                try
                {
                    JToken jt;
                    Int64  bid_id = 0, offer_id = 0;
                    if (inputData.TryGetValue(@"offer_id", out jt))
                    {
                        offer_id = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"bid_id", out jt))
                    {
                        bid_id = jt.Value <Int64>();
                    }
                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            int   maxBysupplier = 0;
                            Offer _offer        = Offer.FetchByID(offer_id);
                            if (_offer != null)
                            {
                                maxBysupplier = AppSupplier.FetchByID(_offer.SupplierId).MaxWinningsNum;
                            }

                            if (maxBysupplier == 0)
                            {
                                // RespondError(Response, HttpStatusCode.InternalServerError, @"supplier-maxwinningsnum-zero");
                                //  return;
                                throw new InvalidDataException(@"supplier-maxwinningsnum-zero");
                            }
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"max_winnings_num");
                            jsonWriter.WriteValue(maxBysupplier);
                            jsonWriter.WritePropertyName(@"supplier_id");
                            jsonWriter.WriteValue(_offer.SupplierId);
                            jsonWriter.WriteEndObject();
                        }
                    }
                }
                catch (InvalidDataException e)
                {
                    RespondError(Response, HttpStatusCode.InternalServerError, @"supplier-maxwinningsnum-zero");
                }

                catch (Exception e)
                {
                    RespondError(Response, HttpStatusCode.InternalServerError, @"db-error");
                }
            }
        }
 protected void Page_PreRender(object sender, EventArgs e)
 {
     Master.PageTitleHtml = string.Format(ProductsStrings.GetText(@"SupplierProductsPageTitle"), AppSupplier.FetchByID(SupplierId).BusinessName);
     Master.ActiveMenu    = "Suppliers";
 }
Exemplo n.º 29
0
        protected bool IsAuthorizedRequestSupplier(HttpRequest request, HttpResponse response, bool automaticResponseOnFail, out JObject inputJson, out Int64 AppSupplierId)
        {
            inputJson = null;

            bool hasFormData    = request.HttpMethod == "POST" || request.HttpMethod == "PUT";
            bool hasRequestBody = hasFormData || request.ContentLength > 0;

            if ((request.Headers["Authorization"] != null &&
                 request.Headers["Authorization"].StartsWith(@"Token ", StringComparison.Ordinal)) ||
                (request.HttpMethod == "GET" && request.QueryString["access_token"] != null))
            {
                string token = request.Headers["Authorization"];
                if (token != null)
                {
                    token = token.Substring(6);
                }
                else
                {
                    token = request.QueryString["access_token"];
                }

                Int64 authTokenId;
                if (AuthTokens.ValidateAppSupplierAuthToken(token, false, out AppSupplierId, out authTokenId))
                {
                    var  supplier = AppSupplier.FetchByID(AppSupplierId);
                    bool _locked  = supplier != null ? supplier.IsLocked : true;
                    return(true);
                }
                else
                {
                    if (automaticResponseOnFail)
                    {
                        RespondForbidden(response);
                    }
                    return(false);
                }
            }
            else
            { // Deprecated
                string authTokenSecret = null, authTokenKey = null;
                if (hasRequestBody
                    &&
                    (request.ContentType.StartsWith("application/x-www-form-urlencoded") ||
                     request.ContentType.StartsWith("multipart/form-data")))
                {
                    authTokenSecret = request.Form[@"auth_token_secret"] ?? "";
                    authTokenKey    = request.Form[@"auth_token_key"] ?? "";
                }
                else if (hasRequestBody && request.ContentType.StartsWith("application/json"))
                {
                    try
                    {
                        using (StreamReader reader = new StreamReader(request.InputStream))
                        {
                            using (JsonTextReader jsonReader = new JsonTextReader(reader))
                            {
                                inputJson = JObject.Load(jsonReader);
                            }
                        }
                    }
                    catch
                    {
                        RespondBadRequest(response);
                    }

                    if (inputJson != null)
                    {
                        JToken jt;
                        if (inputJson.TryGetValue(@"auth_token_secret", out jt))
                        {
                            authTokenSecret = jt.Value <string>() ?? @"";
                        }
                        if (inputJson.TryGetValue(@"auth_token_key", out jt))
                        {
                            authTokenKey = jt.Value <string>() ?? @"";
                        }
                    }
                }
                else
                {
                    authTokenSecret = request.QueryString[@"auth_token_secret"] ?? "";
                    authTokenKey    = request.QueryString[@"auth_token_key"] ?? "";

                    if (hasFormData && authTokenSecret.Length == 0 && authTokenKey.Length == 0)
                    {
                        authTokenSecret = request.Form[@"auth_token_secret"] ?? "";
                        authTokenKey    = request.Form[@"auth_token_key"] ?? "";
                    }
                }

                if (authTokenSecret != null && authTokenSecret.Length > 0 &&
                    authTokenKey != null && authTokenKey.Length > 0)
                {
                    Int64 AppSupplierAuthTokenId;
                    if (AuthTokens.ValidateAppSupplierAuthToken(authTokenSecret, authTokenKey, false, out AppSupplierId, out AppSupplierAuthTokenId))
                    {
                        return(true);
                    }
                    else
                    {
                        if (automaticResponseOnFail)
                        {
                            RespondForbidden(response);
                        }
                        return(false);
                    }
                }
                else
                {
                    AppSupplierId = 0;
                }
                if (automaticResponseOnFail)
                {
                    RespondBadRequest(response);
                }
            }

            return(false);
        }
Exemplo n.º 30
0
        public static AppUserAuthenticateResults AuthenticateAppSupplier(string Email, string Password, out Int64 AppSupplierId)
        {
            AppSupplierId = 0;
            if (!Email.NormalizeEmail().IsValidEmail() || string.IsNullOrEmpty(Password))
            {
                return(AppUserAuthenticateResults.LoginError);
            }

            List <object> user = Query.New <AppSupplier>()
                                 .Select(AppSupplier.Columns.SupplierId)
                                 .AddSelect(AppSupplier.Columns.IsLocked)
                                 .AddSelect(AppSupplier.Columns.BadLoginTries)
                                 .AddSelect(AppSupplier.Columns.Password)
                                 .AddSelect(AppSupplier.Columns.PasswordSalt)
                                 .AddSelect(AppSupplier.Columns.IsVerified)
                                 .Where(AppSupplier.Columns.UniqueIdString, Email.NormalizeEmail())
                                 .AddWhere(AppSupplier.Columns.IsDeleted, false)
                                 .ExecuteOneRowToList();

            if (user == null)
            {
                user = null;
                return(AppUserAuthenticateResults.NoMatch);
            }
            if (!Convert.ToBoolean(user[5]))
            {
                if (Settings.GetSettingBool(Settings.Keys.APPUSER_VERIFY_EMAIL, false))
                {
                    try
                    {
                        string key = GenerateRecoveryKey(Email);
                        EmailMessagingService.SendWelcomeMailWithVerificationForAppSupplier(AppSupplier.FetchByID(user[0]), key, null);
                    }
                    catch { }
                    user = null;
                    return(AppUserAuthenticateResults.NotVerified);
                }
            }
            string comparePassword = EncodePassword(Password, user[4] as string);

            if (!comparePassword.Equals(user[3] as string, StringComparison.Ordinal))
            {
                if (MaximumBadLoginTries > 0)
                {
                    Int32 BadLoginTries = Convert.ToInt32(user[2]);
                    BadLoginTries++;
                    bool IsLocked = false;
                    if (BadLoginTries >= MaximumBadLoginTries)
                    {
                        IsLocked = true;
                    }
                    Query.New <AppSupplier>()
                    .Update(AppSupplier.Columns.BadLoginTries, BadLoginTries)
                    .Update(AppSupplier.Columns.IsLocked, IsLocked)
                    .Where(AppSupplier.Columns.SupplierId, user[0])
                    .Execute();
                }
                return(AppUserAuthenticateResults.NoMatch);
            }
            AppSupplierId = Convert.ToInt64(user[0]);
            Query.New <AppSupplier>()
            .Update(AppSupplier.Columns.LastLogin, DateTime.UtcNow)
            .Update(AppSupplier.Columns.BadLoginTries, 0)
            .Where(AppSupplier.Columns.SupplierId, user[0])
            .Execute();
            return(AppUserAuthenticateResults.Success);
        }