示例#1
0
        public IActionResult Create(string email, IFormFile file)
        {
            // List of messages to return to the client
            var messages = new List <Message>();

            #region application descriptor validations

            // File with JSON application descriptor is required
            if (file == null)
            {
                messages.Add(new Message(MessageTypeEnum.Error,
                                         0001,
                                         new List <string>()));
                return(BadRequest(messages));
            }

            // Get JObject from input file
            JObject applicationDescriptorJObject;
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
                // Try to parse file to JObject - only valid JSON files are parsed
                try
                {
                    applicationDescriptorJObject = JObject.Parse(reader.ReadToEnd());
                }
                // If parsing was unsuccessfull, return error message containing location of error
                catch (JsonReaderException e)
                {
                    messages.Add(new Message(MessageTypeEnum.Error,
                                             0002,
                                             new List <string>()
                    {
                        e.Message
                    }));
                    return(BadRequest(messages));
                }
            }
            var sharedAppInitHelper = new SharedAppInitHelper();

            // With successfully parsed JSON file, validate it against schema
            var schemaValidationMessages = sharedAppInitHelper.ValidateJSONAgainstSchema(applicationDescriptorJObject);
            // If validation JSON is not valid return errors
            if (schemaValidationMessages.Count != 0)
            {
                return(BadRequest(schemaValidationMessages));
            }
            // Get ApplicationDescriptor class instance from JObject
            var applicationDescriptor = applicationDescriptorJObject.ToObject <ApplicationDescriptor>();

            // LoginApplicationName must be unique
            var applicationRepository = new ApplicationRepository(context);
            var applicationModel      = applicationRepository.GetByLoginApplicationName(applicationDescriptor.LoginApplicationName);
            if (applicationModel != null)
            {
                messages.Add(new Message(MessageTypeEnum.Error,
                                         0003,
                                         new List <string>()
                {
                    applicationDescriptor.LoginApplicationName
                }));
            }
            // Validate datasets and attributes
            messages.AddRange(sharedAppInitHelper.ValidateDescriptor(applicationDescriptor));

            if (messages.Count != 0)
            {
                return(BadRequest(messages));
            }

            #endregion

            // Set default values to the application descriptor
            sharedAppInitHelper.SetDefaultDescriptorValues(applicationDescriptor);

            #region create new application

            using (var transaction = context.Database.BeginTransaction())
            {
                // Create new application and add it to the database
                var serializedApplicationDescriptor = JsonConvert.SerializeObject(applicationDescriptor);
                var newApplication = new ApplicationModel {
                    LoginApplicationName      = applicationDescriptor.LoginApplicationName,
                    ApplicationDescriptorJSON = serializedApplicationDescriptor
                };
                applicationRepository.Add(newApplication);

                // Create new admin account for the application
                // Random password
                string newPassword;
                var    minPasswordLength = applicationDescriptor.SystemDatasets.UsersDatasetDescriptor.PasswordAttribute.Min;
                if (minPasswordLength != null)
                {
                    newPassword = PasswordHelper.GenerateRandomPassword((int)minPasswordLength);
                }
                else
                {
                    newPassword = PasswordHelper.GenerateRandomPassword(Constants.MinSaferPasswordLength);
                }
                // Admin rights
                var appInitHelper    = new AppInitHelper();
                var newRights        = appInitHelper.GetAdminRights(newApplication, applicationDescriptor);
                var rightsRepository = new RightsRepository(context);
                rightsRepository.Add(newRights);
                var salt    = PasswordHelper.GetSalt();
                var newUser = new UserModel
                {
                    Application  = newApplication,
                    PasswordHash = PasswordHelper.ComputeHash(salt + newPassword),
                    PasswordSalt = salt,
                    Data         = appInitHelper.GetDefaultAdminDataDictionary(applicationDescriptor.SystemDatasets.UsersDatasetDescriptor),
                    Rights       = newRights,
                    Language     = applicationDescriptor.DefaultLanguage
                };
                var userRepository = new UserRepository(context);
                userRepository.Add(newUser);

                // Try to send login details to admin account to email from parametres
                try
                {
                    appInitHelper.SendEmailWithCredentials(email, applicationDescriptor.ApplicationName, newApplication.LoginApplicationName, newPassword);
                }
                catch
                {
                    messages.Add(new Message(MessageTypeEnum.Error,
                                             0025,
                                             new List <string>()
                    {
                        email
                    }));
                    return(BadRequest(messages));
                }

                // Commit all
                transaction.Commit();
            }
            // If everythong was ok, save changes to the database
            context.SaveChangesAsync();

            #endregion

            messages.Add(new Message(MessageTypeEnum.Info,
                                     0026,
                                     new List <string>()
            {
                applicationDescriptor.ApplicationName, email
            }));
            return(Ok(messages));
        }
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        MembershipController member = new MembershipController();
        RoleController       role   = new RoleController();
        UserInfo             user   = member.GetUserDetails(GetPortalID, UserName.Text);

        if (user.UserExists && user.IsApproved)
        {
            if (!(string.IsNullOrEmpty(UserName.Text) && string.IsNullOrEmpty(PasswordAspx.Text)))
            {
                if (PasswordHelper.ValidateUser(user.PasswordFormat, PasswordAspx.Text, user.Password, user.PasswordSalt))
                {
                    string userRoles = role.GetRoleNames(user.UserName, GetPortalID);
                    strRoles += userRoles;
                    if (strRoles.Length > 0)
                    {
                        SetUserRoles(strRoles);
                        SessionTracker sessionTracker = (SessionTracker)Session["Tracker"];
                        sessionTracker.PortalID = GetPortalID.ToString();
                        sessionTracker.Username = UserName.Text;
                        Session["Tracker"]      = sessionTracker;
                        SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                        SLog.SessionTrackerUpdateUsername(sessionTracker, sessionTracker.Username, GetPortalID.ToString());

                        if (Request.QueryString["ReturnUrl"] != null)
                        {
                            FormsAuthentication.SetAuthCookie(UserName.Text, RememberMe.Checked);
                            string PageNotFoundPage      = Path.Combine(this.Request.ApplicationPath.ToString(), pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalPageNotFound) + ".aspx").Replace("\\", "/");;
                            string UserRegistrationPage  = Path.Combine(this.Request.ApplicationPath.ToString(), pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalRegistrationPage) + ".aspx").Replace("\\", "/");;
                            string PasswordRecoveryPage  = Path.Combine(this.Request.ApplicationPath.ToString(), pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalPasswordRecovery) + ".aspx").Replace("\\", "/");;
                            string ForgotPasswordPage    = Path.Combine(this.Request.ApplicationPath.ToString(), pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalForgotPassword) + ".aspx").Replace("\\", "/");;
                            string PageNotAccessiblePage = Path.Combine(this.Request.ApplicationPath.ToString(), pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalPageNotAccessible) + ".aspx").Replace("\\", "/");;

                            string ReturnUrlPage = Request.QueryString["ReturnUrl"].Replace("%2f", "-").ToString();

                            if (ReturnUrlPage == PageNotFoundPage || ReturnUrlPage == UserRegistrationPage || ReturnUrlPage == PasswordRecoveryPage || ReturnUrlPage == ForgotPasswordPage || ReturnUrlPage == PageNotAccessiblePage)
                            {
                                Response.Redirect("~/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx", false);
                            }
                            else
                            {
                                Response.Redirect(ResolveUrl(Request.QueryString["ReturnUrl"].ToString()), false);
                            }
                        }
                        else
                        {
                            FormsAuthentication.SetAuthCookie(UserName.Text, RememberMe.Checked);
                            if (IsUseFriendlyUrls)
                            {
                                if (GetPortalID > 1)
                                {
                                    Response.Redirect("~/portal/" + GetPortalSEOName + "/" + "Single-Address-Checkout.aspx", false);
                                }
                                else
                                {
                                    Response.Redirect("~/" + "Single-Address-Checkout" + ".aspx", false);
                                }
                            }
                            else if (!IsUseFriendlyUrls)
                            {
                                if (GetPortalID > 1)
                                {
                                    Response.Redirect("~/portal/" + GetPortalSEOName + "/" + "Single-Address-Checkout", false);
                                }
                                else
                                {
                                    Response.Redirect("~/" + "Single-Address-Checkout", false);
                                }
                            }
                            else
                            {
                                Response.Redirect(ResolveUrl("~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage)), false);
                            }
                        }

                        //update Cart for that User in AspxCommerce
                        //TODO:: get customerID from userNAme
                        int customerID = GetCustomerID;
                        if (customerID == 0)
                        {
                            SettingProvider     objSP        = new SettingProvider();
                            CustomerGeneralInfo sageUserCust = objSP.CustomerIDGetByUsername(user.UserName, GetPortalID, GetStoreID);
                            if (sageUserCust != null)
                            {
                                customerID = sageUserCust.CustomerID;
                            }
                        }
                        UpdateCartAnonymoususertoRegistered(GetStoreID, GetPortalID, customerID, sessionCode);
                    }
                    else
                    {
                        FailureText.Text = GetSageMessage("UserLogin", "Youarenotauthenticatedtothisportal");//"You are not authenticated to this portal!";
                    }
                }
                else
                {
                    FailureText.Text = GetSageMessage("UserLogin", "UsernameandPasswordcombinationdoesntmatched");//"Username and Password combination doesn't matched!";
                }
            }
        }
        else
        {
            FailureText.Text = GetSageMessage("UserLogin", "UserDoesnotExist");
        }
    }
示例#3
0
        public void ShouldReturnRightSaltLenght()
        {
            var testsalt = PasswordHelper.GenerateSalt();

            Assert.IsTrue(testsalt.Length > 0);
        }
示例#4
0
 protected void wzdPasswordRecover_NextButtonClick(object sender, WizardNavigationEventArgs e)
 {
     try
     {
         if (txtPassword.Text != null && txtRetypePassword.Text != "" && txtRetypePassword.Text == txtPassword.Text)
         {
             if (txtPassword.Text.Length < 4)
             {
                 ShowMessage("", GetSageMessage("PasswordRecovery", "PasswordLength"), "", SageMessageType.Alert);
                 e.Cancel = true;
             }
             else
             {
                 if (hdnRecoveryCode.Value != "")
                 {
                     sageframeuser = UserManagementController.GetUsernameByActivationOrRecoveryCode(hdnRecoveryCode.Value, GetPortalID);
                     if (sageframeuser.CodeForUsername != null)
                     {
                         UserInfo userOld = m.GetUserDetails(GetPortalID, sageframeuser.CodeForUsername);
                         string   Password, PasswordSalt;
                         PasswordHelper.EnforcePasswordSecurity(m.PasswordFormat, txtPassword.Text, out Password, out PasswordSalt);
                         UserInfo user = new UserInfo(userOld.UserID, Password, PasswordSalt, m.PasswordFormat);
                         m.ChangePassword(user);
                         List <ForgotPasswordInfo> messageTemplates = UserManagementController.GetMessageTemplateListByMessageTemplateTypeID(SystemSetting.PASSWORD_RECOVERED_SUCCESSFUL_EMAIL, GetPortalID);
                         foreach (ForgotPasswordInfo messageTemplate in messageTemplates)
                         {
                             DataTable dtTokenValues           = UserManagementController.GetPasswordRecoverySuccessfulTokenValue(userOld.UserName, GetPortalID);
                             string    replacedMessageSubject  = MessageToken.ReplaceAllMessageToken(messageTemplate.Subject, dtTokenValues);
                             string    replacedMessageTemplate = MessageToken.ReplaceAllMessageToken(messageTemplate.Body, dtTokenValues);
                             try
                             {
                                 MailHelper.SendMailNoAttachment(messageTemplate.MailFrom, userOld.Email, replacedMessageSubject, replacedMessageTemplate, string.Empty, string.Empty);
                             }
                             catch (Exception)
                             {
                                 ShowMessage("", GetSageMessage("PasswordRecovery", "SecureConnectionFPRError"), "", SageMessageType.Alert);
                                 e.Cancel = true;
                                 divRecoverpwd.Visible = false;
                             }
                         }
                         UserManagementController.DeactivateRecoveryCode(userOld.UserName, GetPortalID);
                         ForgotPasswordInfo template = UserManagementController.GetMessageTemplateByMessageTemplateTypeID(SystemSetting.PASSWORD_RECOVERED_SUCESSFUL_INFORMATION, GetPortalID);
                         if (template != null)
                         {
                             ((Literal)WizardStep2.FindControl("litPasswordChangedSuccessful")).Text = template.Body;
                         }
                     }
                     else
                     {
                         e.Cancel = true;
                         ShowMessage("", GetSageMessage("PasswordRecovery", "UnknownErrorPleaseTryAgaing"), "", SageMessageType.Alert);
                     }
                 }
                 else
                 {
                     e.Cancel = true;
                     ShowMessage("", GetSageMessage("PasswordRecovery", "UnknownError"), "", SageMessageType.Alert);
                 }
             }
         }
         else
         {
             ShowMessage("", GetSageMessage("PasswordRecovery", "PleaseEnterAllRequiredFields"), "", SageMessageType.Alert);
             e.Cancel = true;
         }
     }
     catch (Exception ex)
     {
         ProcessException(ex);
     }
 }
示例#5
0
        public void Add(AddUserInput input)
        {
            this.Trim(input);

            input.Validate();

            if (input.AccountName.IsNullOrEmpty() && input.MobilePhone.IsNullOrEmpty() && input.Email.IsNullOrEmpty())
            {
                throw new InvalidInputException("用户名/手机号码/邮箱至少填一个");
            }

            string accountName = null;

            if (input.AccountName.IsNotNullOrEmpty())
            {
                accountName = input.AccountName.ToLower();
                AceUtils.EnsureAccountNameLegal(accountName);
                bool exists = this.DbContext.Query <Sys_User>().Where(a => a.AccountName == accountName).Any();
                if (exists)
                {
                    throw new InvalidInputException("用户名[{0}]已存在".ToFormat(input.AccountName));
                }
            }

            string mobilePhone = null;

            if (input.MobilePhone.IsNotNullOrEmpty())
            {
                mobilePhone = input.MobilePhone;
                if (AceUtils.IsMobilePhone(mobilePhone) == false)
                {
                    throw new InvalidInputException("请输入正确的手机号码");
                }

                bool exists = this.DbContext.Query <Sys_User>().Where(a => a.MobilePhone == mobilePhone).Any();
                if (exists)
                {
                    throw new InvalidInputException("手机号码[{0}]已存在".ToFormat(mobilePhone));
                }
            }

            string email = null;

            if (input.Email.IsNotNullOrEmpty())
            {
                email = input.Email.ToLower();
                if (AceUtils.IsEmail(email) == false)
                {
                    throw new InvalidInputException("请输入正确的邮箱地址");
                }

                bool exists = this.DbContext.Query <Sys_User>().Where(a => a.Email == email).Any();
                if (exists)
                {
                    throw new InvalidInputException("邮箱地址[{0}]已存在".ToFormat(input.Email));
                }
            }

            Sys_User user = this.CreateEntity <Sys_User>();

            user.AccountName = accountName;
            user.Name        = input.Name;
            user.Gender      = input.Gender;
            user.MobilePhone = mobilePhone;
            user.Birthday    = input.Birthday;
            user.WeChat      = input.WeChat;
            user.Email       = email;
            user.Description = input.Description;
            user.State       = AccountState.Normal;

            string userSecretkey     = UserHelper.GenUserSecretkey();
            string encryptedPassword = PasswordHelper.Encrypt(input.Password, userSecretkey);

            Sys_UserLogOn logOnEntity = new Sys_UserLogOn();

            logOnEntity.Id            = IdHelper.CreateStringSnowflakeId();
            logOnEntity.UserId        = user.Id;
            logOnEntity.UserSecretkey = userSecretkey;
            logOnEntity.UserPassword  = encryptedPassword;

            List <string>       roleIds   = input.GetRoles();
            List <Sys_UserRole> userRoles = roleIds.Select(a =>
            {
                return(new Sys_UserRole()
                {
                    Id = IdHelper.CreateStringSnowflakeId(),
                    UserId = user.Id,
                    RoleId = a,
                });
            }).ToList();

            user.RoleIds = string.Join(",", roleIds);

            List <string>      orgIds   = input.GetOrgs();
            List <Sys_UserOrg> userOrgs = orgIds.Select(a =>
            {
                return(new Sys_UserOrg()
                {
                    Id = IdHelper.CreateStringSnowflakeId(),
                    UserId = user.Id,
                    OrgId = a,
                    DisablePermission = false
                });
            }).ToList();

            user.OrgIds = string.Join(",", orgIds);

            List <string>       postIds   = input.GetPosts();
            List <Sys_UserPost> userPosts = postIds.Select(a =>
            {
                return(new Sys_UserPost()
                {
                    Id = IdHelper.CreateStringSnowflakeId(),
                    UserId = user.Id,
                    PostId = a
                });
            }).ToList();

            user.PostIds = string.Join(",", postIds);

            this.DbContext.DoWithTransaction(() =>
            {
                this.DbContext.Insert(user);
                this.DbContext.Insert(logOnEntity);
                this.DbContext.InsertRange(userRoles);
                this.DbContext.InsertRange(userOrgs);
                this.DbContext.InsertRange(userPosts);
            });
        }
示例#6
0
        private void LoginUser()
        {
            MembershipController member = new MembershipController();
            RoleController       role   = new RoleController();
            UserInfo             user   = member.GetUserDetails(GetPortalID, UserName.Text);

            HttpContext.Current.Session["IsLoginClick" + user.UserName] = false;
            if (user.UserExists && user.IsApproved)
            {
                if (!(string.IsNullOrEmpty(UserName.Text) && string.IsNullOrEmpty(Password.Text)))
                {
                    if (PasswordHelper.ValidateUser(user.PasswordFormat, Password.Text, user.Password, user.PasswordSalt))
                    {
                        SucessFullLogin(user);
                    }
                    else
                    {
                        if (Session[SessionKeys.LoginHitCount] == null)
                        {
                            Session[SessionKeys.LoginHitCount] = 1;
                        }
                        else
                        {
                            loginhit = Convert.ToInt32(Session[SessionKeys.LoginHitCount]);
                            loginhit++;
                            Session[SessionKeys.LoginHitCount] = loginhit;
                        }
                        CaptchaValue.Text = string.Empty;
                        if (loginhit == 3)
                        {
                            Page.Response.Redirect(Page.Request.Url.ToString(), true);
                        }
                        if (loginhit > 3)
                        {
                            InitializeCaptcha();
                            CaptchaValue.Text = string.Empty;
                        }
                        FailureText.Text = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "UsernameandPasswordcombinationdoesntmatched"));//"Username and Password combination doesn't matched!";
                    }
                }
            }
            else
            {
                if (Session[SessionKeys.LoginHitCount] == null)
                {
                    Session[SessionKeys.LoginHitCount] = 1;
                }
                else
                {
                    loginhit = Convert.ToInt32(Session[SessionKeys.LoginHitCount]);
                    loginhit++;
                    Session[SessionKeys.LoginHitCount] = loginhit;
                }
                FailureText.Text  = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "UserDoesnotExist"));
                CaptchaValue.Text = string.Empty;
                if (loginhit == 3)
                {
                    Page.Response.Redirect(Page.Request.Url.ToString(), true);
                }
                if (loginhit > 3)
                {
                    InitializeCaptcha();
                    CaptchaValue.Text = string.Empty;
                }
            }
        }
        protected SendControlViewModel(Wallet wallet, string title)
            : base(title)
        {
            Global = Locator.Current.GetService <Global>();
            Wallet = wallet;

            LabelSuggestion             = new SuggestLabelViewModel();
            _buildTransactionButtonText = DoButtonText;

            this.ValidateProperty(x => x.Address, ValidateAddress);
            this.ValidateProperty(x => x.CustomChangeAddress, ValidateCustomChangeAddress);
            this.ValidateProperty(x => x.Password, ValidatePassword);
            this.ValidateProperty(x => x.UserFeeText, ValidateUserFeeText);

            ResetUi();

            CoinList = new CoinListViewModel(Wallet, Global.Config, Global.UiConfig, displayCommonOwnershipWarning: true);

            Observable.FromEventPattern(CoinList, nameof(CoinList.SelectionChanged))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => SetFeesAndTexts());

            _minMaxFeeTargetsEqual = this.WhenAnyValue(x => x.MinimumFeeTarget, x => x.MaximumFeeTarget, (x, y) => x == y)
                                     .ToProperty(this, x => x.MinMaxFeeTargetsEqual, scheduler: RxApp.MainThreadScheduler);

            SetFeeTargetLimits();
            FeeTarget        = Global.UiConfig.FeeTarget;
            FeeDisplayFormat = (FeeDisplayFormat)(Enum.ToObject(typeof(FeeDisplayFormat), Global.UiConfig.FeeDisplayFormat) ?? FeeDisplayFormat.SatoshiPerByte);
            SetFeesAndTexts();

            this.WhenAnyValue(x => x.AmountText)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x =>
            {
                if (Money.TryParse(x.TrimStart('~', ' '), out Money amountBtc))
                {
                    SetAmountWatermark(amountBtc);
                }
                else
                {
                    SetAmountWatermark(Money.Zero);
                }

                SetFees();
            });

            AmountKeyUpCommand = ReactiveCommand.Create((KeyEventArgs key) =>
            {
                if (IsMax)
                {
                    SetFeesAndTexts();
                }
                else if (BitcoinInput.TryCorrectAmount(AmountText, out var betterAmount))
                {
                    AmountText = betterAmount;
                }
            });

            this.WhenAnyValue(x => x.IsBusy, x => x.IsHardwareBusy)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => BuildTransactionButtonText = IsHardwareBusy
                                                ? WaitingForHardwareWalletButtonTextString
                                                : IsBusy
                                                        ? DoingButtonText
                                                        : DoButtonText);

            Observable
            .Merge(this.WhenAnyValue(x => x.FeeTarget).Select(_ => true))
            .Merge(this.WhenAnyValue(x => x.IsEstimateAvailable).Select(_ => true))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                IsSliderFeeUsed = IsEstimateAvailable;
                SetFeesAndTexts();
            });

            this.WhenAnyValue(x => x.IsSliderFeeUsed)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(enabled => FeeControlOpacity = enabled ? 1 : 0.5);                     // Give the control the disabled feeling. Real Disable it not a solution as we have to detect if the slider is moved.

            MaxCommand = ReactiveCommand.Create(() => IsMax = !IsMax, outputScheduler: RxApp.MainThreadScheduler);

            this.WhenAnyValue(x => x.IsMax)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                if (IsMax)
                {
                    SetFeesAndTexts();

                    LabelToolTip = "Spending whole coins does not generate change, thus labeling is unnecessary.";
                }
                else
                {
                    AmountText = "0.0";

                    LabelToolTip = "Who can link this transaction to you? E.g.: \"Max, BitPay\"";
                }
            });

            // Triggering the detection of same address values.
            this.WhenAnyValue(x => x.Address)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => this.RaisePropertyChanged(nameof(CustomChangeAddress)));

            this.WhenAnyValue(x => x.CustomChangeAddress)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => this.RaisePropertyChanged(nameof(Address)));

            this.WhenAnyValue(x => x.IsCustomChangeAddressVisible)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                this.RaisePropertyChanged(nameof(Address));
                this.RaisePropertyChanged(nameof(CustomChangeAddress));
            });

            FeeRateCommand = ReactiveCommand.Create(ChangeFeeRateDisplay, outputScheduler: RxApp.MainThreadScheduler);

            OnAddressPasteCommand = ReactiveCommand.Create((BitcoinUrlBuilder url) => OnAddressPaste(url));

            BuildTransactionCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    IsBusy = true;
                    MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.BuildingTransaction);

                    var label             = new SmartLabel(LabelSuggestion.Label);
                    LabelSuggestion.Label = label;
                    if (!IsMax && label.IsEmpty)
                    {
                        NotificationHelpers.Warning("Label is required.", "");
                        return;
                    }

                    var selectedCoinViewModels = CoinList.Coins.Where(cvm => cvm.IsSelected);
                    var selectedCoinReferences = selectedCoinViewModels.Select(cvm => cvm.Model.OutPoint).ToList();

                    if (!selectedCoinReferences.Any())
                    {
                        NotificationHelpers.Warning("No coins are selected to spend.", "");
                        return;
                    }

                    BitcoinAddress address;
                    try
                    {
                        address = BitcoinAddress.Create(Address, Global.Network);
                    }
                    catch (FormatException)
                    {
                        NotificationHelpers.Warning("Invalid address.", "");
                        return;
                    }

                    var requests = new List <DestinationRequest>();

                    if (IsCustomChangeAddressVisible && !string.IsNullOrWhiteSpace(CustomChangeAddress))
                    {
                        try
                        {
                            var customChangeAddress = BitcoinAddress.Create(CustomChangeAddress, Global.Network);

                            if (customChangeAddress == address)
                            {
                                NotificationHelpers.Warning("The active address and the change address cannot be the same.", "");
                                return;
                            }

                            requests.Add(new DestinationRequest(customChangeAddress, MoneyRequest.CreateChange(subtractFee: true), label));
                        }
                        catch (FormatException)
                        {
                            NotificationHelpers.Warning("Invalid custom change address.", "");
                            return;
                        }
                    }

                    MoneyRequest moneyRequest;
                    if (IsMax)
                    {
                        moneyRequest = MoneyRequest.CreateAllRemaining(subtractFee: true);
                    }
                    else
                    {
                        if (!Money.TryParse(AmountText, out Money amount) || amount == Money.Zero)
                        {
                            NotificationHelpers.Warning("Invalid amount.");
                            return;
                        }

                        if (amount == selectedCoinViewModels.Sum(x => x.Amount))
                        {
                            NotificationHelpers.Warning("Looks like you want to spend whole coins. Try Max button instead.", "");
                            return;
                        }
                        moneyRequest = MoneyRequest.Create(amount, subtractFee: false);
                    }

                    if (FeeRate is null || FeeRate.SatoshiPerByte < 1)
                    {
                        NotificationHelpers.Warning("Invalid fee rate.", "");
                        return;
                    }

                    var feeStrategy = FeeStrategy.CreateFromFeeRate(FeeRate);

                    var activeDestinationRequest = new DestinationRequest(address, moneyRequest, label);
                    requests.Add(activeDestinationRequest);

                    var intent = new PaymentIntent(requests);
                    try
                    {
                        MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.DequeuingSelectedCoins);
                        OutPoint[] toDequeue = selectedCoinViewModels.Where(x => x.CoinJoinInProgress).Select(x => x.Model.OutPoint).ToArray();
                        if (toDequeue is { } && toDequeue.Any())
                        {
                            await Wallet.ChaumianClient.DequeueCoinsFromMixAsync(toDequeue, DequeueReason.TransactionBuilding);
                        }
                    }
                    catch
                    {
                        NotificationHelpers.Error("Cannot spend mixing coins.", "");
                        return;
                    }
                    finally
                    {
                        MainWindowViewModel.Instance.StatusBar.TryRemoveStatus(StatusType.DequeuingSelectedCoins);
                    }

                    if (!Wallet.KeyManager.IsWatchOnly)
                    {
                        try
                        {
                            PasswordHelper.GetMasterExtKey(Wallet.KeyManager, Password, out string compatiblityPasswordUsed);                             // We could use TryPassword but we need the exception.
                            if (compatiblityPasswordUsed is { })
                            {
                                Password = compatiblityPasswordUsed;                                 // Overwrite the password for BuildTransaction function.
                                NotificationHelpers.Warning(PasswordHelper.CompatibilityPasswordWarnMessage);
                            }
                        }
                        catch (SecurityException ex)
                        {
                            NotificationHelpers.Error(ex.Message, "");
                            return;
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError(ex);
                            NotificationHelpers.Error(ex.ToUserFriendlyString());
                            return;
                        }
                    }
示例#8
0
        public async System.Threading.Tasks.Task Update(Team team)
        {
            team.password = PasswordHelper.HashPassword(team.password);

            await Teams.ReplaceOneAsync(new BsonDocument("id", team.id), team);
        }
示例#9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password">前端传过来的是经过md5加密后的密码</param>
        /// <param name="user"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CheckLogin(string loginName, string password, out SysUser user, out string token, out string msg)
        {
            user  = null;
            msg   = null;
            token = null;
            loginName.NotNullOrEmpty();
            password.NotNullOrEmpty();

            var view = this.DbContext.JoinQuery <SysUser, SysUserLogOn>((u, userLogOn) => new object[]
            {
                JoinType.InnerJoin, u.Id == userLogOn.UserId
            })
                       .Select((u, userLogOn) => new { User = u, UserLogOn = userLogOn });

            loginName = loginName.ToLower();
            if (AceUtils.IsMobilePhone(loginName))
            {
                view = view.Where(a => a.User.MobilePhone == loginName);
            }
            else if (AceUtils.IsEmail(loginName))
            {
                view = view.Where(a => a.User.Email == loginName);
            }
            else
            {
                view = view.Where(a => a.User.AccountName == loginName);
            }

            view = view.Where(a => a.User.State != AccountState.Closed);

            var viewEntity = view.FirstOrDefault();

            if (viewEntity == null)
            {
                msg = "账户不存在,请重新输入";
                return(false);
            }
            if (!viewEntity.User.IsAdmin())
            {
                if (viewEntity.User.State == AccountState.Disabled)
                {
                    msg = "账户被禁用,请联系管理员";
                    return(false);
                }
            }

            SysUser      userEntity      = viewEntity.User;
            SysUserLogOn userLogOnEntity = viewEntity.UserLogOn;

            string dbPassword = PasswordHelper.EncryptMD5Password(password, userLogOnEntity.UserSecretkey);

            if (dbPassword != userLogOnEntity.UserPassword)
            {
                msg = "密码不正确,请重新输入";
                return(false);
            }

            DateTime lastVisitTime = DateTime.Now;

            token = TokenHelper.NewRefreshToken();
            this.DbContext.Update <SysUserLogOn>(a => a.Id == userLogOnEntity.Id, a => new SysUserLogOn()
            {
                LogOnCount        = a.LogOnCount + 1,
                PreviousVisitTime = userLogOnEntity.LastVisitTime,
                LastVisitTime     = lastVisitTime,
                Token             = TokenHelper.NewRefreshToken(),
                RefreshToken      = TokenHelper.NewRefreshToken(),
                Expiresin         = 7200,
                ExpiresinTime     = DateTimeHelper.TimeStamp().ToLong(0) + 7200
            });
            user = userEntity;
            return(true);
        }
示例#10
0
 public User LoginUser(LogInViewModel logIn)
 {
     logIn.Password = PasswordHelper.EncodePasswordMd5(logIn.Password);
     return(_context.Users.Include(r => r.Role).SingleOrDefault(u => u.Number == logIn.Number.Trim() && u.Password == logIn.Password));
 }
示例#11
0
        public void GivenPass_Check_ReturnValidHash()
        {
            PasswordHelper.CreatePasswordHash("passssss", out var hash, out var salt);

            PasswordHelper.VerifyPasswordHash("passssss", hash, salt).Should().BeTrue();
        }
示例#12
0
        public IActionResult Inscription(Compte compte)
        {
            Adresse adresse;

            try
            {
                if (compte == null)
                {
                    throw new ArgumentNullException(nameof(compte));
                }


                if (!InputValidationHelper.IsValidEmail(compte.Email))
                {
                    return(BadRequest("Adresse courriel invalide"));
                }

                if (!InputValidationHelper.IsValidUsername(compte.NomUtilisateur))
                {
                    return(BadRequest("Nom d'utilisateur invalide"));
                }

                if (!InputValidationHelper.IsValidFirstName(compte.Prenom))
                {
                    return(BadRequest("Nom invalide"));
                }

                if (!InputValidationHelper.IsValidLastName(compte.Nom))
                {
                    return(BadRequest("Prénom invalide"));
                }

                if (!InputValidationHelper.IsValidBirthDate(compte.DateNaissance))
                {
                    return(BadRequest("Vous devez être âgé de 18 ans ou plus"));
                }

                if (!InputValidationHelper.IsValidPassword(compte.MotPasse))
                {
                    return(BadRequest("Le mot de passe doit contenir au moins 1 majuscule, 1 minuscule, 1 chiffre," +
                                      " 1 caractère spécial ainsi qu'être d'une longueur minimale de 5 caractères"));
                }

                if (!InputValidationHelper.IsValidAddress(compte.Adresse))
                {
                    return(BadRequest("Adresse invalide"));
                }

                compte.MotPasse = PasswordHelper.HashPassword(compte.MotPasse);

                adresse = _db.Adresse.Where(a => a.NumeroCivique == compte.Adresse.NumeroCivique &&
                                            a.Rue == compte.Adresse.Rue && a.Ville == compte.Adresse.Ville &&
                                            a.CodePostal == compte.Adresse.CodePostal).FirstOrDefault();
                if (adresse != null)
                {
                    compte.Adresse = adresse;
                }

                _db.Add(compte);
                _db.SaveChanges();


                return(Created("", ""));
            }
            catch (ArgumentNullException)
            {
                return(Unauthorized("Informations erronées"));
            }
        }
示例#13
0
 public Usuario GerarNovoUsuarioFuncionario()
 {
     return(new Usuario(PasswordHelper.GerarSenhaAutomatica()));
 }
示例#14
0
 public bool IsExist(string email, string password)
 {
     return(_userRepository.IsExist(email.Trim().ToLower(), PasswordHelper.EncodePasswordMd5(password)));
 }
示例#15
0
 private void RegisterUser()
 {
     try
     {
         if (string.IsNullOrEmpty(UserName.Text) || string.IsNullOrEmpty(FirstName.Text) || string.IsNullOrEmpty(LastName.Text) || string.IsNullOrEmpty(Email.Text))
         {
             ShowMessage("", GetSageMessage("UserRegistration", "PleaseEnterAllRequiredFields"), "", SageMessageType.Alert);
         }
         else if (UserName.Text.Length > 50)
         {
             ShowMessage("", "Username should not be greater than 50 characters", "", SageMessageType.Alert);
         }
         else
         {
             int      UserRegistrationType = pagebase.GetSettingIntValueByIndividualKey(SageFrameSettingKeys.PortalUserRegistration);
             bool     isUserActive         = UserRegistrationType == 2 ? true : false;
             UserInfo objUser = new UserInfo();
             objUser.ApplicationName = Membership.ApplicationName;
             objUser.FirstName       = Server.HtmlEncode(FirstName.Text);
             objUser.UserName        = Server.HtmlEncode(UserName.Text);
             objUser.LastName        = Server.HtmlEncode(LastName.Text);
             string Pwd, PasswordSalt;
             PasswordHelper.EnforcePasswordSecurity(_member.PasswordFormat, Password.Text, out Pwd, out PasswordSalt);
             objUser.Password         = Pwd;
             objUser.PasswordSalt     = PasswordSalt;
             objUser.Email            = Email.Text;
             objUser.SecurityQuestion = " ";
             objUser.SecurityAnswer   = " ";
             objUser.IsApproved       = true;
             objUser.CurrentTimeUtc   = DateTime.Now;
             objUser.CreatedDate      = DateTime.Now;
             objUser.UniqueEmail      = 0;
             objUser.PasswordFormat   = _member.PasswordFormat;
             objUser.PortalID         = GetPortalID;
             objUser.AddedOn          = DateTime.Now;
             objUser.AddedBy          = GetUsername;
             objUser.UserID           = Guid.NewGuid();
             objUser.RoleNames        = SystemSetting.REGISTER_USER_ROLENAME;
             objUser.StoreID          = GetStoreID;
             objUser.CustomerID       = 0;
             UserCreationStatus status = new UserCreationStatus();
             CheckRegistrationType(UserRegistrationType, ref objUser);
             MembershipDataProvider.CreatePortalUser(objUser, out status, UserCreationMode.REGISTER);
             if (status == UserCreationStatus.DUPLICATE_USER)
             {
                 ShowMessage("", GetSageMessage("UserManagement", "NameAlreadyExists"), "", SageMessageType.Alert);
                 GenerateCaptchaImage();
             }
             else if (status == UserCreationStatus.DUPLICATE_EMAIL)
             {
                 ShowMessage("", GetSageMessage("UserManagement", "EmailAddressAlreadyIsInUse"), "", SageMessageType.Alert);
                 GenerateCaptchaImage();
             }
             else if (status == UserCreationStatus.SUCCESS)
             {
                 try
                 {
                     IsModuleInstalled(1);
                     MembershipUser userInfo = Membership.GetUser(UserName.Text);
                     if (chkIsSubscribeNewsLetter.Checked)
                     {
                         int?newID = 0;
                         ManageNewsLetterSubscription(Email.Text, ref newID);
                         IsModuleInstalled(2);
                     }
                     HandlePostRegistration(UserRegistrationType);
                 }
                 catch (Exception)
                 {
                     ShowMessage("", GetSageMessage("UserManagement", "SecureConnection"), "", SageMessageType.Alert);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ProcessException(ex);
     }
 }
 public void PasswordHelperGenerateSalt()
 {
     PasswordHelper.GenerateSalt()
     .Should().NotBeNull();
 }
示例#17
0
        private void LogInPublicModeRegistration()
        {
            string strRoles             = string.Empty;
            MembershipController member = new MembershipController();
            RoleController       role   = new RoleController();
            UserInfo             user   = member.GetUserDetails(GetPortalID, UserName.Text);

            if (!(string.IsNullOrEmpty(UserName.Text) && string.IsNullOrEmpty(Password.Text)))
            {
                if (PasswordHelper.ValidateUser(user.PasswordFormat, Password.Text, user.Password, user.PasswordSalt))
                {
                    string userRoles = role.GetRoleNames(user.UserName, GetPortalID);
                    strRoles += userRoles;
                    if (strRoles.Length > 0)
                    {
                        SetUserRoles(strRoles);
                        SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker];
                        sessionTracker.PortalID      = GetPortalID.ToString();
                        sessionTracker.Username      = UserName.Text;
                        Session[SessionKeys.Tracker] = sessionTracker;
                        SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog();
                        SLog.SessionTrackerUpdateUsername(sessionTracker, sessionTracker.Username, GetPortalID.ToString());
                        {
                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                                             user.UserName,
                                                                                             DateTime.Now,
                                                                                             DateTime.Now.AddMinutes(30),
                                                                                             true,
                                                                                             GetPortalID.ToString(),
                                                                                             FormsAuthentication.FormsCookiePath);

                            StoreSettingConfig ssc = new StoreSettingConfig();


                            if (ssc.GetStoreSettingsByKey(StoreSetting.AllowRealTimeNotifications, GetStoreID, GetPortalID, GetCurrentCultureName).ToLower() == "true")
                            {
                                RealTimeHelper.UpdateAdminNotifications(GetStoreID, GetPortalID);
                            }


                            // Encrypt the ticket.
                            string encTicket = FormsAuthentication.Encrypt(ticket);

                            // Create the cookie.
                            string randomCookieValue = GenerateRandomCookieValue();
                            Session[SessionKeys.RandomCookieValue] = randomCookieValue;
                            SecurityPolicy  objSecurity            = new SecurityPolicy();
                            HttpCookie      cookie                 = new HttpCookie(objSecurity.FormsCookieName(GetPortalID), encTicket);
                            SageFrameConfig objConfig              = new SageFrameConfig();
                            string          ServerCookieExpiration = objConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.ServerCookieExpiration);
                            int             expiryTime             = Math.Abs(int.Parse(ServerCookieExpiration));
                            expiryTime     = expiryTime < 5 ? 5 : expiryTime;
                            cookie.Expires = DateTime.Now.AddMinutes(expiryTime);
                            Response.Cookies.Add(cookie);
                            string sessionCode = string.Empty;
                            if (HttpContext.Current.Session.SessionID != null)
                            {
                                sessionCode = HttpContext.Current.Session.SessionID.ToString();
                            }
                            int CustomerID = GetUserDetailsByUserName(UserName.Text, GetPortalID).CustomerID;
                            UpdateCartAnonymoususertoRegistered(GetStoreID, GetPortalID, CustomerID, sessionCode);
                            if (!IsParent)
                            {
                                Response.Redirect(ResolveUrl("~/portal/" + GetPortalSEOName + "/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + Extension), false);
                            }
                            else
                            {
                                Response.Redirect(ResolveUrl("~/" + pagebase.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + Extension), false);
                            }
                        }
                    }
                }
            }
        }
        public void PasswordHelperHashPasswordSaltIsNullThrowArgumentNullException()
        {
            Action action = () => PasswordHelper.HashPassword(null, "a");

            action.Should().Throw <ArgumentNullException>();
        }
示例#19
0
        internal async Task RunAsync(string walletName, bool mixAll, bool keepMixAlive)
        {
            try
            {
                Logger.LogSoftwareStarted("Wasabi Daemon");

                KeyManager keyManager = TryGetKeyManagerFromWalletName(walletName);
                if (keyManager is null)
                {
                    return;
                }

                string password = null;
                var    count    = 3;
                string compatibilityPassword = null;
                do
                {
                    if (password != null)
                    {
                        if (count > 0)
                        {
                            Logger.LogError($"Wrong password. {count} attempts left. Try again.");
                        }
                        else
                        {
                            Logger.LogCritical($"Wrong password. {count} attempts left. Exiting...");
                            return;
                        }
                        count--;
                    }
                    Console.Write("Password: "******"Correct password.");

                await Global.InitializeNoWalletAsync();

                if (Global.KillRequested)
                {
                    return;
                }

                await Global.InitializeWalletServiceAsync(keyManager);

                if (Global.KillRequested)
                {
                    return;
                }

                await TryQueueCoinsToMixAsync(mixAll, password);

                bool mixing;
                do
                {
                    if (Global.KillRequested)
                    {
                        break;
                    }

                    await Task.Delay(3000);

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    bool anyCoinsQueued = Global.ChaumianClient.State.AnyCoinsQueued();
                    if (!anyCoinsQueued && keepMixAlive)                     // If no coins queued and mixing is asked to be kept alive then try to queue coins.
                    {
                        await TryQueueCoinsToMixAsync(mixAll, password);
                    }

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    mixing = anyCoinsQueued || keepMixAlive;
                } while (mixing);

                if (!Global.KillRequested)                 // This only has to run if it finishes by itself. Otherwise the Ctrl+c runs it.
                {
                    await Global.ChaumianClient?.DequeueAllCoinsFromMixAsync("Stopping Wasabi.");
                }
            }
            catch
            {
                if (!Global.KillRequested)
                {
                    throw;
                }
            }
            finally
            {
                Logger.LogInfo($"{nameof(Daemon)} stopped.");
            }
        }
 public void PasswordHelperHashPassword()
 {
     PasswordHelper.HashPassword("a", "a")
     .Should().NotBeNullOrEmpty();
 }
示例#21
0
        internal async Task RunAsync(string walletName, string destinationWalletName, bool keepMixAlive)
        {
            try
            {
                Logger.LogSoftwareStarted("Wasabi Daemon");

                KeyManager keyManager = Global.WalletManager.GetWalletByName(walletName).KeyManager;

                string password = null;
                var    count    = 3;
                string compatibilityPassword = null;
                do
                {
                    if (password != null)
                    {
                        if (count > 0)
                        {
                            Logger.LogError($"Wrong password. {count} attempts left. Try again.");
                        }
                        else
                        {
                            Logger.LogCritical($"Wrong password. {count} attempts left. Exiting...");
                            return;
                        }
                        count--;
                    }
                    Console.Write("Password: "******"Correct password.");

                await Global.InitializeNoWalletAsync();

                if (Global.KillRequested)
                {
                    return;
                }

                Wallet = await Global.WalletManager.StartWalletAsync(keyManager);

                if (Global.KillRequested)
                {
                    return;
                }

                KeyManager destinationKeyManager           = Global.WalletManager.GetWalletByName(destinationWalletName).KeyManager;
                bool       isDifferentDestinationSpecified = keyManager.ExtPubKey != destinationKeyManager.ExtPubKey;
                if (isDifferentDestinationSpecified)
                {
                    await Global.WalletManager.StartWalletAsync(destinationKeyManager);
                }

                do
                {
                    if (Global.KillRequested)
                    {
                        break;
                    }

                    // If no coins enqueued then try to enqueue the large anonset coins and mix to another wallet.
                    if (isDifferentDestinationSpecified && !AnyCoinsQueued())
                    {
                        Wallet.ChaumianClient.DestinationKeyManager = destinationKeyManager;
                        await TryQueueCoinsToMixAsync(password, minAnonset : Wallet.ServiceConfiguration.MixUntilAnonymitySet);
                    }

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    // If no coins were enqueued then try to enqueue coins those have less anonset and mix into the same wallet.
                    if (!AnyCoinsQueued())
                    {
                        Wallet.ChaumianClient.DestinationKeyManager = Wallet.ChaumianClient.KeyManager;
                        await TryQueueCoinsToMixAsync(password, maxAnonset : Wallet.ServiceConfiguration.MixUntilAnonymitySet - 1);
                    }

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    await Task.Delay(3000);
                }
                // Keep this loop alive as long as a coin is enqueued or keepalive was specified.
                while (keepMixAlive || AnyCoinsQueued());

                await Global.DisposeAsync();
            }
            catch
            {
                if (!Global.KillRequested)
                {
                    throw;
                }
            }
            finally
            {
                Logger.LogInfo($"{nameof(Daemon)} stopped.");
            }
        }
        public void PasswordHelperValidatePasswordHashedPasswordIsNullThrowArgumentNullException()
        {
            Action action = () => PasswordHelper.ValidateHashPassword("a", "a", null);

            action.Should().Throw <ArgumentNullException>();
        }
示例#23
0
        public IHttpActionResult SendEmailForgotPassword(ForgotPasswordDto dtoForgotPassword)
        {
            var          dtoBase        = new DtoBase();
            const string randomPassword = "******";
            var          user           = _userService.FirstOrDefault(o => o.Email == dtoForgotPassword.Email);

            if (user != null)
            {
                var courier = _courierService.GetById(user.Id);
                if (courier != null)
                {
                    var webLink   = AppSettingsReader.GetValue("Url", typeof(String)) as string;
                    var urlSignIn = webLink + "/Authentication/SignIn";
                    var imgSrc    = webLink + "/Content/quickspatch/img/logo-o.svg";

                    var urlChangePass           = webLink + "/Authentication/ChangeRestorePassword?code=" + PasswordHelper.HashString(user.Id.ToString(), user.UserName);
                    var fromEmail               = AppSettingsReader.GetValue("EmailFrom", typeof(String)) as string;
                    var displayName             = AppSettingsReader.GetValue("EmailFromDisplayName", typeof(String)) as string;
                    var franchiseeConfiguration = _franchiseeConfigurationService.GetFranchiseeConfiguration();
                    var franchiseeName          = franchiseeConfiguration != null ? franchiseeConfiguration.Name : "";
                    var emailContent            = TemplateHelpper.FormatTemplateWithContentTemplate(
                        TemplateHelpper.ReadContentFromFile(TemplateConfigFile.RestorePassword, true),
                        new
                    {
                        img_src         = imgSrc,
                        full_name       = Framework.Utility.CaculatorHelper.GetFullName(user.FirstName, user.MiddleName, user.LastName),
                        web_link        = webLink,
                        user_name       = user.UserName,
                        url_change_pass = urlChangePass,
                        franchisee_Name = franchiseeName,
                        url_sign_in     = urlSignIn
                    });
                    // send email
                    _emailHandler.SendEmail(fromEmail, new[] { user.Email }, SystemMessageLookup.GetMessage("SubjectToSendEmailForCreateUser"),
                                            emailContent, true, displayName);
                    dtoBase.Id = 1;
                }
            }
            else
            {
                dtoBase.Id = 2;
            }
            return(Ok(dtoBase));
            //return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        public void PasswordHelperValidatePassword()
        {
            var hashedPassword = PasswordHelper.HashPassword("a", "a");

            PasswordHelper.ValidateHashPassword("a", "a", hashedPassword).Should().BeTrue();
        }
示例#25
0
    //private bool ValidateCaptcha()
    //{
    //    if (!(cvCaptchaValue.ValueToCompare == CaptchaValue.Text))
    //    {
    //        ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("UserRegistration", "EnterTheCorrectCapchaCode"), "", SageMessageType.Error);
    //        return false;
    //    }

    //    return true;
    //}

    private void RegisterUser()
    {
        try
        {
            if (string.IsNullOrEmpty(UserName.Text) || string.IsNullOrEmpty(FirstName.Text) || string.IsNullOrEmpty(LastName.Text) || string.IsNullOrEmpty(Email.Text))
            {
                ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("UserRegistration", "PleaseEnterAllRequiredFields"), "", SageMessageType.Alert);
                CheckIfSucccess = 0;
            }
            else
            {
                int UserRegistrationType = pagebase.GetSettingIntByKey(SageFrameSettingKeys.PortalUserRegistration);

                bool isUserActive = UserRegistrationType == 2 ? true : false;

                UserInfo objUser = new UserInfo();
                objUser.ApplicationName = Membership.ApplicationName;
                objUser.FirstName       = FirstName.Text;
                objUser.UserName        = UserName.Text;
                objUser.LastName        = LastName.Text;
                string Pwd, PasswordSalt;
                PasswordHelper.EnforcePasswordSecurity(_member.PasswordFormat, Password.Text, out Pwd, out PasswordSalt);
                objUser.Password         = Pwd;
                objUser.PasswordSalt     = PasswordSalt;
                objUser.Email            = Email.Text;
                objUser.SecurityQuestion = Question.Text;
                objUser.SecurityAnswer   = Answer.Text;
                objUser.IsApproved       = true;
                objUser.CurrentTimeUtc   = DateTime.Now;
                objUser.CreatedDate      = DateTime.Now;
                objUser.UniqueEmail      = 0;
                objUser.PasswordFormat   = _member.PasswordFormat;
                objUser.PortalID         = GetPortalID;
                objUser.AddedOn          = DateTime.Now;
                objUser.AddedBy          = GetUsername;
                objUser.UserID           = Guid.NewGuid();
                objUser.RoleNames        = SystemSetting.REGISTER_USER_ROLENAME;
                objUser.StoreID          = GetStoreID;
                objUser.CustomerID       = 0;

                UserCreationStatus status = new UserCreationStatus();
                CheckRegistrationType(UserRegistrationType, ref objUser);

                MembershipDataProvider.CreatePortalUser(objUser, out status, UserCreationMode.REGISTER);
                if (status == UserCreationStatus.DUPLICATE_USER)
                {
                    ShowMessage(SageMessageTitle.Notification.ToString(), UserName.Text.Trim() + " " + GetSageMessage("UserManagement", "NameAlreadyExists"), "", SageMessageType.Alert);
                    CheckIfSucccess = 0;
                }
                else if (status == UserCreationStatus.DUPLICATE_EMAIL)
                {
                    ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("UserManagement", "EmailAddressAlreadyIsInUse"), "", SageMessageType.Alert);
                    CheckIfSucccess = 0;
                }
                else if (status == UserCreationStatus.SUCCESS)
                {
                    if (chkIsSubscribeNewsLetter.Checked)
                    {
                        int?newID = 0;
                        ManageNewsLetterSubscription(Email.Text, ref newID);
                    }
                    ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("UserManagement", "UserCreatedSuccessfully"), "", SageMessageType.Success);
                    CheckIfSucccess = 1;
                    //  Page.ClientScript.RegisterStartupScript(this.GetType(), "disablepopup", " sucessMessage();", true);
                    ClearFormValue();
                }
            }
        }

        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
示例#26
0
 public IEnumerable <IEvent> On(RegisterAccount command)
 {
     yield return(new AccountRegistered(command.ID, command.Username, PasswordHelper.HashAndSalt(command.Password)));
 }
示例#27
0
 protected override async Task <bool> Authorize()
 {
     return(await Task.Run(() => PasswordHelper.TryPassword(_wallet.KeyManager, Password, out _)));
 }
示例#28
0
        public bool CompareOldpassword(string oldpassword, string username)
        {
            string oldhashpassword = PasswordHelper.EncodePasswordMd5(oldpassword);

            return(_db.Users.Any(p => p.Username == username && p.Password == oldhashpassword));
        }