public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            ParameterUtility.CheckParameter(ref username, true, true, true, 0x100, "username");
            ParameterUtility.CheckParameter(ref oldPassword, true, true, false, 0x80, "oldPassword");
            ParameterUtility.CheckParameter(ref newPassword, true, true, false, 0x80, "newPassword");

            if(!this.CheckPassword(username, oldPassword, false))
                return false;

            if(newPassword.Length < this.MinRequiredPasswordLength)
                throw new ArgumentException("Password is shorter than the minimum " + this.MinRequiredPasswordLength, "newPassword");

            int numNonAlphanumericCharacters = newPassword.Where((t, i) => !char.IsLetterOrDigit(newPassword, i)).Count();
            if(numNonAlphanumericCharacters < this.MinRequiredNonAlphanumericCharacters)
            {
                throw new ArgumentException(
                    SR.Password_need_more_non_alpha_numeric_chars_1.WithParameters(this.MinRequiredNonAlphanumericCharacters), "newPassword");
            }

            if(this.PasswordStrengthRegularExpression.Length > 0 && !Regex.IsMatch(newPassword, this.PasswordStrengthRegularExpression))
                throw new ArgumentException(SR.Password_does_not_match_regular_expression.WithParameters(), "newPassword");

            var e = new ValidatePasswordEventArgs(username, newPassword, false);
            this.OnValidatingPassword(e);
            if(e.Cancel)
            {
                if(e.FailureInformation != null)
                    throw e.FailureInformation;
                throw new ArgumentException(SR.Membership_Custom_Password_Validation_Failure.WithParameters(), "newPassword");
            }

            return this.ChangePasswordSafe(username, oldPassword, newPassword);
        }
 protected virtual void OnValidatingPassword(ValidatePasswordEventArgs e)
 {
     if (this._EventHandler != null)
     {
         this._EventHandler(this, e);
     }
 }
        public MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status, string name, string surname, string telephone, string country)
        {
            var args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            var user = GetUser(username, true);

            if (user == null)
            {
                var userObj = new User { Username = username, Password = Assets.Encrypt(password), Email = email, Name = name, Surname = surname, Telephone = telephone };

                new UserDa(databasecontext).Add(userObj);

                status = MembershipCreateStatus.Success;

                return GetUser(username, true);
            }
            status = MembershipCreateStatus.DuplicateUserName;

            return null;
        }
Ejemplo n.º 4
0
 public override bool ChangePassword(string username, string oldPassword, string newPassword)
 {
     var vpea = new ValidatePasswordEventArgs(username, newPassword, false);
     OnValidatingPassword(vpea);
     if (vpea.Cancel)
     {
         return false;
     }
     User a = (from x in _Context.Users
                   where string.Compare(username, x.Name, StringComparison.OrdinalIgnoreCase) == 0
                   select x).SingleOrDefault();
     if (a == null)
     {
         return false;
     }
     if (!a.Password.Equals(oldPassword, StringComparison.Ordinal))
     {
         a.InvalidPasswordAttempts++;
         _Context.SaveChanges();
         return false;
     }
     a.Password = newPassword;
     a.LastActivityDate = new DateTime?(DateTime.UtcNow);
     a.LastPasswordChangedDate = new DateTime?(DateTime.UtcNow);
     _Context.SaveChanges();
     return true;
 }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            MembershipUser u = GetUser(username, false);
            if (u == null)
            {
                DBAuthRepository _user = new DBAuthRepository();
                _user.CreateUser(username, password, email);
                status = MembershipCreateStatus.Success;

                return GetUser(username, false);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }
            return null;
        }
        /// <summary>
        /// Processes a request to update the password for a membership user.
        /// </summary>
        /// <param name="username">The user to update the password for.</param>
        /// <param name="oldPassword">The current password for the specified user.</param>
        /// <param name="newPassword">The new password for the specified user.</param>
        /// <returns>
        /// true if the password was updated successfully; otherwise, false.
        /// </returns>
        /// <remarks>
        /// During installation the application will not be configured, if this is the case and the 'default' password 
        /// is stored in the database then we will validate the user - this will allow for an admin password reset if required
        /// </remarks>
        protected override bool PerformChangePassword(string username, string oldPassword, string newPassword)
        {


            if (ApplicationContext.Current.IsConfigured == false && oldPassword == "default"
                || ValidateUser(username, oldPassword))
            {
                var args = new ValidatePasswordEventArgs(username, newPassword, false);
                OnValidatingPassword(args);

                if (args.Cancel)
                {
                    if (args.FailureInformation != null)
                        throw args.FailureInformation;
                    throw new MembershipPasswordException("Change password canceled due to password validation failure.");
                }

                var user = new User(username);
                //encrypt/hash the new one
                string salt;
                var encodedPassword = EncryptOrHashNewPassword(newPassword, out salt);

                //Yes, it's true, this actually makes a db call to set the password
                user.Password = FormatPasswordForStorage(encodedPassword, salt);
                //call this just for fun.
                user.Save();

                return true;    
            }

            return false;

        }
        public OnlineStoreMembershipUser CreateUser(string username,
           string password,
           string email,
           string passwordQuestion,
           string passwordAnswer,
           bool isApproved,
           object providerUserKey,
           string contact,
           string phoneNumber,
           AddressDto contactAddress,
           AddressDto deliveryAddress,
           out MembershipCreateStatus status)
        {
            var args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }
            if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }
            var user = GetUser(username, true) as OnlineStoreMembershipUser;
            if (user == null)
            {
                using (var proxy = new UserServiceClient())
                {
                    List<UserDto> userDtos = new List<UserDto>
                    {
                        new UserDto
                        {
                            UserName = username,
                            Password = password,
                            Contact = contact,
                            LastLogonDate = null,
                            RegisteredDate = DateTime.Now,
                            Email = email,
                            IsDisabled = false,
                            PhoneNumber = phoneNumber,
                            ContactAddress = contactAddress,
                            DeliveryAddress = deliveryAddress
                        }
                    };

                    proxy.CreateUsers(userDtos.ToArray());
                }

                status = MembershipCreateStatus.Success;
                return GetUser(username, true) as OnlineStoreMembershipUser;
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }
        }
        public override bool ChangePassword(string email, string oldPwd, string newPwd)
        {
            if (!ValidateUser(email, oldPwd))
                return false;

            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(email, newPwd, true);

            OnValidatingPassword(args);

            var salt = GetSaltBytesByEmail(email);

            if (args.Cancel) {
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
            }

            if(salt == null) {
                throw new MembershipPasswordException(string.Format("Can not find salt by given email {0}.", email));
            }

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[_connectionString].ConnectionString);
            SqlCommand cmd = new SqlCommand("UPDATE [dbo].[Users] " +
                    " SET HashedPassword = @HashedPassword, LastPasswordChangedAt = @LastPasswordChangedAt" +
                    " WHERE email = @Email", conn);

            cmd.Parameters.AddWithValue("@HashedPassword", EncodePassword(newPwd, salt));
            cmd.Parameters.AddWithValue("@LastPasswordChangedAt", DateTime.Now);
            cmd.Parameters.AddWithValue("@Email",  email);

            int rowsAffected = 0;

            try
            {
                conn.Open();

                rowsAffected = cmd.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }

            if (rowsAffected > 0)
            {
                return true;
            }

            return false;
        }
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            SecUtility.CheckParameter(ref username, true, true, true, 0x100, "username");
            SecUtility.CheckParameter(ref oldPassword, true, true, false, 0x80, "oldPassword");
            SecUtility.CheckParameter(ref newPassword, true, true, false, 0x80, "newPassword");

            if (!CheckPassword(username, oldPassword, false))
            {
                return false;
            }
            if (newPassword.Length < MinRequiredPasswordLength)
            {
                throw new ArgumentException("Password is shorter than the minimum " + MinRequiredPasswordLength,
                                            "newPassword");
            }
            int num3 = 0;
            for (int i = 0; i < newPassword.Length; i++)
            {
                if (!char.IsLetterOrDigit(newPassword, i))
                {
                    num3++;
                }
            }
            if (num3 < MinRequiredNonAlphanumericCharacters)
            {
                throw new ArgumentException(
                    SR.Password_need_more_non_alpha_numeric_chars_1.WithParameters(MinRequiredNonAlphanumericCharacters),
                    "newPassword");
            }
            if ((PasswordStrengthRegularExpression.Length > 0) &&
                !Regex.IsMatch(newPassword, PasswordStrengthRegularExpression))
            {
                throw new ArgumentException(SR.Password_does_not_match_regular_expression.WithParameters(),
                                            "newPassword");
            }
            var e = new ValidatePasswordEventArgs(username, newPassword, false);
            OnValidatingPassword(e);
            if (e.Cancel)
            {
                if (e.FailureInformation != null)
                {
                    throw e.FailureInformation;
                }
                throw new ArgumentException(SR.Membership_Custom_Password_Validation_Failure.WithParameters(),
                                            "newPassword");
            }

            return CheckedChangePassword(username, oldPassword, newPassword);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Adds a new membership user to the data source.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.
        /// </returns>
        /// <param name="username">The user name for the new user. </param><param name="password">The password for the new user. </param><param name="email">The e-mail address for the new user.</param><param name="passwordQuestion">The password question for the new user.</param><param name="passwordAnswer">The password answer for the new user</param><param name="isApproved">Whether or not the new user is approved to be validated.</param><param name="providerUserKey">The unique identifier from the membership data source for the user.</param><param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"/> enumeration value indicating whether the user was created successfully.</param>
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            var args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            var userRepository = InstanceFactory.CreateUserInstance();
            var user = userRepository.GetUserNameByEmail(email);
            var userName = (user != null && user.UserName != string.Empty) ? user.UserName : string.Empty;

            if (RequiresUniqueEmail && userName != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            var duplicateUser = userRepository.GetUserObjByUserName(username);

            if (user != null && duplicateUser == null && user.UserName == string.Empty)
            {
                var randomCode = RandomStringGenerator.RandomString();

                var userObj = new UserEntity
                                  {
                                      UserID = user.UserID,
                                      UserDisplayName = user.UserDisplayName,
                                      UserName = username,
                                      UserCode = TripleDES.EncryptString(randomCode),
                                      Password = PasswordHelper.GenerateHashedPassword(password, randomCode),
                                      UserEmailAddress = email,
                                      UserActiveStatus = 1
                                  };

                userRepository.UpdateProfile(userObj);

                status = MembershipCreateStatus.Success;

                return GetUser(username, true);
            }
            status = MembershipCreateStatus.DuplicateUserName;

            return null;
        }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion,
            string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args =
           new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            MembershipUser user = GetUser(username, true);

            if (user == null)
            {
                var userObj = new AppUser();
                userObj.Username = username;
                userObj.Password = GetMD5Hash(password);
                userObj.Email = email;
                userObj.DateCreated = DateTime.UtcNow;
                userObj.LastActivityDate = DateTime.UtcNow;

                entities.AppUsers.Add(userObj);
                entities.SaveChanges();

                status = MembershipCreateStatus.Success;

                return GetUser(username, true);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }

            return null;
        }
Ejemplo n.º 12
0
        private static void OnValidatePassword(object sender, ValidatePasswordEventArgs args)
        {
            // Cancel if the password is F0rb!dden
            if (args.Password == "F0rb!dden")
            {
                args.Cancel = true;
                args.FailureInformation = new MembershipPasswordException("The password 'F0rb!dden' is not allowed!");
            }

            // Regex validation or any other type of validation could be done here :)
            // An example regex implementation is commented out below:

            // System.Text.RegularExpressions.Regex r =
            //  new System.Text.RegularExpressions.Regex(...);

            // if (!r.IsMatch(args.Password))
            // {
            //     args.FailureInformation =
            //       new Exception(...);
            //     args.Cancel = true;
            // }
        }
        //
        // MembershipProvider.ResetPassword
        //
        public override string ResetPassword(string username, string answer)
        {
            if (!EnablePasswordReset)
            {
                throw new NotSupportedException("Password reset is not enabled.");
            }

            if (answer == null && RequiresQuestionAndAnswer)
            {
                UpdateFailureCount(username, "passwordAnswer");

                throw new ProviderException("Password answer required for password reset.");
            }

            string newPassword =
              System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters);

            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, newPassword, true);

            OnValidatingPassword(args);

            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Reset password canceled due to password validation failure.");

            hMailServerNetRemote.IAccount account = GetAccount(username);

            if (account == null)
                throw new ProviderException("Can't find user");

            account.Password = newPassword;
            account.Save();

            return newPassword;
        }
        //
        // System.Web.Security.MembershipProvider methods.
        //
        //
        // MembershipProvider.ChangePassword
        //
        public override bool ChangePassword(string username, string oldPwd, string newPwd)
        {
            if (!ValidateUser(username, oldPwd))
                return false;

            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, newPwd, true);

            OnValidatingPassword(args);

            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Change password canceled due to new password validation failure.");

            string[] sp = username.Split(new Char[] { '@' });

            if (sp.Length != 2)
                return false;

            hMailServerNetRemote.IApplication app = RemoteActivation.GetRemotehMailServerApplication();
            hMailServerNetRemote.IDomain domain = app.Domains.ItemByName(sp[1]);
            hMailServerNetRemote.IAccount account = domain.Accounts[username];
            account.Password = newPwd;
            account.Save();

            return true;
        }
        /// <summary>
        /// Adds a new membership user to the data source.
        /// </summary>
        /// <param name="username">The user name for the new user.</param>
        /// <param name="password">The password for the new user.</param>
        /// <param name="email">The e-mail address for the new user.</param>
        /// <param name="passwordQuestion">The password question for the new user.</param>
        /// <param name="passwordAnswer">The password answer for the new user</param>
        /// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
        /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
        /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"/> enumeration value indicating whether the user was created successfully.</param>
        /// <returns>
        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.
        /// </returns>
        public override MembershipUser CreateUser(string username,
            string password,
            string email,
            string passwordQuestion,
            string passwordAnswer,
            bool isApproved,
            object providerUserKey,
            out MembershipCreateStatus status)
        {
            MiniProfiler profiler = MiniProfiler.Current;
            MethodBase currentMethod = MethodBase.GetCurrentMethod();
            using (profiler.Step(String.Format("{0} : {1}", currentMethod.DeclaringType.Name, currentMethod.Name)))
            {

                ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, password, true);

                OnValidatingPassword(args);

                if (args.Cancel)
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return null;
                }

                if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return null;
                }

                MembershipUser u = GetUser(username, false);

                if (u == null)
                {
                    DateTime createDate = DateTime.Now;

                    if (providerUserKey == null)
                    {
                        providerUserKey = Guid.NewGuid();
                    }
                    else
                    {
                        if (!(providerUserKey is Guid))
                        {
                            status = MembershipCreateStatus.InvalidProviderUserKey;
                            return null;
                        }
                    }

                    MongoServer server = MongoServer.Create(connectionString); // connect to the mongoDB url.
                    MongoDatabase ProviderDB = server.GetDatabase(pMongoProviderDatabaseName, SafeMode.True);

                    //Build a query to find the user id and then update with new password.
                    MongoCollection<BsonDocument> users = ProviderDB.GetCollection(pmongoProviderMembershipCollectionName);

                    bool bSuccess = false;

                    try
                    {
                        BsonDocument user = new BsonDocument()
                            .Add("PKID", providerUserKey.ToString())
                            .Add("Username", username)
                            .Add("UsernameLowerCase", username.ToLower())
                            .Add("Password", EncodePassword(password))
                            .Add("Email", email)
                            .Add("EmailLowerCase", email.ToLower())
                            .Add("PasswordQuestion", passwordQuestion)
                            .Add("PasswordAnswer", EncodePassword(passwordAnswer))
                            .Add("IsApproved", isApproved)
                            .Add("Comment", "")
                            .Add("CreationDate", createDate)
                            .Add("LastPasswordChangedDate", createDate)
                            .Add("LastLoginDate", createDate)
                            .Add("LastActivityDate", createDate)
                            .Add("ApplicationName", pApplicationName)
                            .Add("ApplicationNameLowerCase", pApplicationName.ToLower())
                            .Add("IsLockedOut", false)
                            .Add("LastLockedOutDate", createDate)
                            .Add("FailedPasswordAttemptCount", 0)
                            .Add("FailedPasswordAttemptWindowStart", createDate)
                            .Add("FailedPasswordAnswerAttemptCount", createDate)
                            .Add("FailedPasswordAnswerAttemptWindowStart", createDate);

                        bSuccess = users.Save(user).Ok;

                        if (bSuccess)
                        {
                            status = MembershipCreateStatus.Success;
                        }
                        else
                        {
                            status = MembershipCreateStatus.UserRejected;
                        }
                    }
                    catch (ApplicationException e)
                    {
                        if (WriteExceptionsToEventLog)
                        {
                            WriteToEventLog(e, "CreateUser");
                        }

                        status = MembershipCreateStatus.ProviderError;
                    }
                    finally
                    {
                    }

                    return GetUser(username, false);
                }
                else
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                }

            }

            return null;
        }
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////

        public override string ResetPassword( string username, string passwordAnswer )
        {
            if ( !EnablePasswordReset )
            {
                throw new NotSupportedException( SR.GetString(SR.Not_configured_to_support_password_resets)  );
            }

            SecUtility.CheckParameter( ref username, true, true, true, 256, "username" );

            string salt;
            int passwordFormat;
            string passwdFromDB;
            int status;
            int failedPasswordAttemptCount;
            int failedPasswordAnswerAttemptCount;
            bool isApproved;
            DateTime lastLoginDate, lastActivityDate;

            GetPasswordWithFormat(username, false, out status, out passwdFromDB, out passwordFormat, out salt, out failedPasswordAttemptCount,
                                  out failedPasswordAnswerAttemptCount, out isApproved, out lastLoginDate, out lastActivityDate);
            if (status != 0)
            {
                if (IsStatusDueToBadPassword(status))
                {
                    throw new MembershipPasswordException(GetExceptionText(status));
                }
                else
                {
                    throw new ProviderException(GetExceptionText(status));
                }
            }

            string encodedPasswordAnswer;
            if( passwordAnswer != null )
            {
                passwordAnswer = passwordAnswer.Trim();
            }
            if (!string.IsNullOrEmpty(passwordAnswer))
                encodedPasswordAnswer = EncodePassword(passwordAnswer.ToLower(CultureInfo.InvariantCulture), passwordFormat, salt);
            else
                encodedPasswordAnswer = passwordAnswer;
            SecUtility.CheckParameter(ref encodedPasswordAnswer, RequiresQuestionAndAnswer, RequiresQuestionAndAnswer, false, 128, "passwordAnswer");
            string newPassword  = GeneratePassword();

            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs( username, newPassword, false );
            OnValidatingPassword( e );

            if( e.Cancel )
            {
                if( e.FailureInformation != null )
                {
                    throw e.FailureInformation;
                }
                else
                {
                    throw new ProviderException( SR.GetString(SR.Membership_Custom_Password_Validation_Failure)  );
                }
            }


            try
            {
                SqlConnectionHolder holder = null;
                try {
                    holder = SqlConnectionHelper.GetConnection( _sqlConnectionString, true );
                    CheckSchemaVersion( holder.Connection );

                    SqlCommand    cmd     = new SqlCommand("dbo.aspnet_Membership_ResetPassword", holder.Connection);
                    string        errText;

                    cmd.CommandTimeout = CommandTimeout;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(CreateInputParam("@ApplicationName", SqlDbType.NVarChar, ApplicationName));
                    cmd.Parameters.Add(CreateInputParam("@UserName", SqlDbType.NVarChar, username));
                    cmd.Parameters.Add(CreateInputParam("@NewPassword", SqlDbType.NVarChar, EncodePassword(newPassword, (int) passwordFormat, salt)));
                    cmd.Parameters.Add(CreateInputParam("@MaxInvalidPasswordAttempts", SqlDbType.Int, MaxInvalidPasswordAttempts ) );
                    cmd.Parameters.Add(CreateInputParam("@PasswordAttemptWindow", SqlDbType.Int, PasswordAttemptWindow ) );
                    cmd.Parameters.Add(CreateInputParam("@PasswordSalt", SqlDbType.NVarChar, salt));
                    cmd.Parameters.Add(CreateInputParam("@PasswordFormat", SqlDbType.Int, (int)passwordFormat));
                    cmd.Parameters.Add(CreateInputParam("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow));
                    if (RequiresQuestionAndAnswer) {
                        cmd.Parameters.Add(CreateInputParam("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer));
                    }

                    SqlParameter p = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    p.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add(p);

                    cmd.ExecuteNonQuery();

                    status = ( ( p.Value != null ) ? ( ( int )p.Value ) : -1 );

                    if ( status != 0 )
                    {
                        errText = GetExceptionText( status );

                        if ( IsStatusDueToBadPassword( status ) )
                        {
                            throw new MembershipPasswordException( errText );
                        }
                        else
                        {
                            throw new ProviderException( errText );
                        }
                    }

                    return newPassword;
                }
                finally
                {
                    if( holder != null )
                    {
                        holder.Close();
                        holder = null;
                    }
                }
            } catch {
                throw;
            }
        }
Ejemplo n.º 17
0
 protected virtual new void OnValidatingPassword(ValidatePasswordEventArgs e)
 {
     Contract.Requires(e != null);
 }
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////

        public override MembershipUser CreateUser( string username,
                                                   string password,
                                                   string email,
                                                   string passwordQuestion,
                                                   string passwordAnswer,
                                                   bool   isApproved,
                                                   object providerUserKey,
                                                   out    MembershipCreateStatus status )
        {
            if( !SecUtility.ValidateParameter(ref password, true, true, false, 128))
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            string salt = GenerateSalt();
            string pass = EncodePassword(password, (int)_PasswordFormat, salt);
            if ( pass.Length > 128 )
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            string encodedPasswordAnswer;
            if( passwordAnswer != null )
            {
                passwordAnswer = passwordAnswer.Trim();
            }

            if (!string.IsNullOrEmpty(passwordAnswer)) {
                if( passwordAnswer.Length > 128 )
                {
                    status = MembershipCreateStatus.InvalidAnswer;
                    return null;
                }
                encodedPasswordAnswer = EncodePassword(passwordAnswer.ToLower(CultureInfo.InvariantCulture), (int)_PasswordFormat, salt);
            }
            else
                encodedPasswordAnswer = passwordAnswer;
            if (!SecUtility.ValidateParameter(ref encodedPasswordAnswer, RequiresQuestionAndAnswer, true, false, 128))
            {
                status = MembershipCreateStatus.InvalidAnswer;
                return null;
            }

            if( !SecUtility.ValidateParameter( ref username,true, true, true, 256))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return null;
            }

            if( !SecUtility.ValidateParameter( ref email,
                                               RequiresUniqueEmail,
                                               RequiresUniqueEmail,
                                               false,
                                               256 ) )
            {
                status = MembershipCreateStatus.InvalidEmail;
                return null;
            }

            if( !SecUtility.ValidateParameter( ref passwordQuestion, RequiresQuestionAndAnswer, true, false, 256))
            {
                status = MembershipCreateStatus.InvalidQuestion;
                return null;
            }

            if( providerUserKey != null )
            {
                if( !( providerUserKey is Guid ) )
                {
                    status = MembershipCreateStatus.InvalidProviderUserKey;
                    return null;
                }
            }

            if( password.Length < MinRequiredPasswordLength )
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            int count = 0;

            for( int i = 0; i < password.Length; i++ )
            {
                if( !char.IsLetterOrDigit( password, i ) )
                {
                    count++;
                }
            }

            if( count < MinRequiredNonAlphanumericCharacters )
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if( PasswordStrengthRegularExpression.Length > 0 )
            {
                if( !RegexUtil.IsMatch( password, PasswordStrengthRegularExpression, RegexOptions.None, _passwordStrengthRegexTimeout ) )
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return null;
                }
            }

            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs( username, password, true );
            OnValidatingPassword( e );

            if( e.Cancel )
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            try
            {
                SqlConnectionHolder holder = null;
                try {
                    holder = SqlConnectionHelper.GetConnection( _sqlConnectionString, true );
                    CheckSchemaVersion( holder.Connection );

                    DateTime    dt  = RoundToSeconds(DateTime.UtcNow);
                    SqlCommand  cmd = new SqlCommand("dbo.aspnet_Membership_CreateUser", holder.Connection);

                    cmd.CommandTimeout = CommandTimeout;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(CreateInputParam("@ApplicationName", SqlDbType.NVarChar, ApplicationName));
                    cmd.Parameters.Add(CreateInputParam("@UserName", SqlDbType.NVarChar, username));
                    cmd.Parameters.Add(CreateInputParam("@Password", SqlDbType.NVarChar, pass));
                    cmd.Parameters.Add(CreateInputParam("@PasswordSalt", SqlDbType.NVarChar, salt));
                    cmd.Parameters.Add(CreateInputParam("@Email", SqlDbType.NVarChar, email));
                    cmd.Parameters.Add(CreateInputParam("@PasswordQuestion", SqlDbType.NVarChar, passwordQuestion));
                    cmd.Parameters.Add(CreateInputParam("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer));
                    cmd.Parameters.Add(CreateInputParam("@IsApproved", SqlDbType.Bit, isApproved));
                    cmd.Parameters.Add(CreateInputParam("@UniqueEmail", SqlDbType.Int, RequiresUniqueEmail ? 1 : 0));
                    cmd.Parameters.Add(CreateInputParam("@PasswordFormat", SqlDbType.Int, (int)PasswordFormat));
                    cmd.Parameters.Add(CreateInputParam("@CurrentTimeUtc", SqlDbType.DateTime, dt));
                    SqlParameter p = CreateInputParam("@UserId", SqlDbType.UniqueIdentifier, providerUserKey);
                    p.Direction= ParameterDirection.InputOutput;
                    cmd.Parameters.Add( p );

                    p = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    p.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add(p);

                    try {
                        cmd.ExecuteNonQuery();
                    } catch(SqlException  sqlEx) {
                        if (sqlEx.Number == 2627 || sqlEx.Number == 2601  || sqlEx.Number == 2512) {
                            status = MembershipCreateStatus.DuplicateUserName;
                            return null;
                        }
                        throw;
                    }
                    int iStatus = ((p.Value!=null) ? ((int) p.Value) : -1);
                    if (iStatus < 0 || iStatus > (int) MembershipCreateStatus.ProviderError)
                        iStatus = (int) MembershipCreateStatus.ProviderError;
                    status = (MembershipCreateStatus) iStatus;
                    if (iStatus != 0) // !success
                        return null;

                    providerUserKey = new Guid( cmd.Parameters[ "@UserId" ].Value.ToString() );
                    dt = dt.ToLocalTime();
                    return new MembershipUser( this.Name,
                                               username,
                                               providerUserKey,
                                               email,
                                               passwordQuestion,
                                               null,
                                               isApproved,
                                               false,
                                               dt,
                                               dt,
                                               dt,
                                               dt,
                                               new DateTime( 1754, 1, 1 ) );
                }
                finally
                {
                    if( holder != null )
                    {
                        holder.Close();
                        holder = null;
                    }
                }
            } catch {
                throw;
            }
        }
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            SecUtility.CheckParameter( ref username, true, true, true, 256, "username" );
            SecUtility.CheckParameter( ref oldPassword, true, true, false, 128, "oldPassword" );
            SecUtility.CheckParameter( ref newPassword, true, true, false, 128, "newPassword" );

            string salt = null;
            int passwordFormat;
            //string passwdFromDB;
            int status;
            //int failedPasswordAttemptCount;
            //int failedPasswordAnswerAttemptCount;
            //bool isApproved;

            if (!CheckPassword( username, oldPassword, false, false, out salt, out passwordFormat))
            {
               return false;
            }

            if( newPassword.Length < MinRequiredPasswordLength )
            {
                throw new ArgumentException(SR.GetString(SR.Password_too_short,
                              "newPassword",
                              MinRequiredPasswordLength.ToString(CultureInfo.InvariantCulture)));
            }

            int count = 0;

            for( int i = 0; i < newPassword.Length; i++ )
            {
                if( !char.IsLetterOrDigit( newPassword, i ) )
                {
                    count++;
                }
            }

            if( count < MinRequiredNonAlphanumericCharacters )
            {
                throw new ArgumentException(SR.GetString(SR.Password_need_more_non_alpha_numeric_chars,
                              "newPassword",
                              MinRequiredNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture)));
            }

            if( PasswordStrengthRegularExpression.Length > 0 )
            {
                if( !RegexUtil.IsMatch( newPassword, PasswordStrengthRegularExpression, RegexOptions.None, _passwordStrengthRegexTimeout ) )
                {
                    throw new ArgumentException(SR.GetString(SR.Password_does_not_match_regular_expression,
                                                             "newPassword"));
                }
            }

            string pass = EncodePassword(newPassword, (int)passwordFormat, salt);
            if ( pass.Length > 128 )
            {
                throw new ArgumentException(SR.GetString(SR.Membership_password_too_long), "newPassword");
            }

            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs( username, newPassword, false );
            OnValidatingPassword( e );

            if( e.Cancel )
            {
                if( e.FailureInformation != null )
                {
                    throw e.FailureInformation;
                }
                else
                {
                    throw new ArgumentException( SR.GetString(SR.Membership_Custom_Password_Validation_Failure) , "newPassword");
                }
            }


            try {
                SqlConnectionHolder holder = null;
                try {
                    holder = SqlConnectionHelper.GetConnection( _sqlConnectionString, true );
                    CheckSchemaVersion( holder.Connection );

                    SqlCommand  cmd = new SqlCommand( "dbo.aspnet_Membership_SetPassword", holder.Connection );

                    cmd.CommandTimeout = CommandTimeout;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(CreateInputParam("@ApplicationName", SqlDbType.NVarChar, ApplicationName));
                    cmd.Parameters.Add(CreateInputParam("@UserName", SqlDbType.NVarChar, username));
                    cmd.Parameters.Add(CreateInputParam("@NewPassword", SqlDbType.NVarChar, pass));
                    cmd.Parameters.Add(CreateInputParam("@PasswordSalt", SqlDbType.NVarChar, salt));
                    cmd.Parameters.Add(CreateInputParam("@PasswordFormat", SqlDbType.Int, passwordFormat));
                    cmd.Parameters.Add(CreateInputParam("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow));

                    SqlParameter p = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    p.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add(p);

                    cmd.ExecuteNonQuery();

                    status =  ( ( p.Value != null ) ? ( ( int )p.Value ) : -1 );

                    if ( status != 0 )
                    {
                        string errText = GetExceptionText( status );

                        if ( IsStatusDueToBadPassword( status ) )
                        {
                            throw new MembershipPasswordException( errText );
                        }
                        else
                        {
                            throw new ProviderException( errText );
                        }
                    }

                    return true;
                }
                finally
                {
                    if( holder != null )
                    {
                        holder.Close();
                        holder = null;
                    }
                }
            } catch {
                throw;
            }
        }
 protected virtual new void OnValidatingPassword(ValidatePasswordEventArgs e)
 {
 }
		public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
		{
			//Thread Safety
			DbContext DataContext = (DbContext)Activator.CreateInstance(CFMembershipSettings.DataContext);
			DbSet Users = DataContext.Set(CFMembershipSettings.UserType);

			status = MembershipCreateStatus.Success;

			MembershipUser user = null;

			if (string.IsNullOrEmpty(username) || string.IsNullOrWhiteSpace(username))
				throw new ArgumentNullException("username");
			if (string.IsNullOrEmpty(password) || string.IsNullOrWhiteSpace(password))
				throw new ArgumentNullException("password");
			if (string.IsNullOrEmpty(email) || string.IsNullOrWhiteSpace(email))
				throw new ArgumentNullException("email");

			if (RequiresQuestionAndAnswer)
			{
				if (string.IsNullOrEmpty(passwordQuestion) || string.IsNullOrWhiteSpace(passwordQuestion))
					throw new ArgumentNullException("passwordQuestion");
				if (string.IsNullOrEmpty(passwordAnswer) || string.IsNullOrWhiteSpace(passwordAnswer))
					throw new ArgumentNullException("passwordAnswer");
			}

			if (username.Length > 100)
				status = MembershipCreateStatus.InvalidUserName;

			if (!this.CheckPasswordPolicy(password))
				status = MembershipCreateStatus.InvalidPassword;

			var args = new ValidatePasswordEventArgs(username, password, true);
			OnValidatingPassword(args);
			if (args.Cancel)
			{
				if (args.FailureInformation != null) throw args.FailureInformation;
				status = MembershipCreateStatus.InvalidPassword;
			}

			if (!Regex.IsMatch(email, EmailRegularExpression))
				status = MembershipCreateStatus.InvalidEmail;

			if (UseEmailAsUsername)
				username = email;

			if (RequiresUniqueEmail && GetUserNameByEmail(email).Trim().Length > 0)
				status = MembershipCreateStatus.DuplicateEmail;

			if (GetUser(username, false) != null)
				status = MembershipCreateStatus.DuplicateUserName;

			if (providerUserKey != null && GetUser(providerUserKey, false) != null)
				status = MembershipCreateStatus.DuplicateProviderUserKey;

			if (status == MembershipCreateStatus.Success)
			{
				byte[] passwordSalt, passwordHash;
				Guid guid;

				HashPassword(password, out passwordSalt, out passwordHash);

				dynamic usr = Activator.CreateInstance(CFMembershipSettings.UserType);

				if (CFMembershipSettings.ProviderKeyType == typeof(Guid) && providerUserKey != null && Guid.TryParse(providerUserKey.ToString(), out guid))
					usr.UserId = (Guid)providerUserKey;

				//If using SqlServeCE or the UserId is missing the DatabaseGenerated attribute
				//automatically generate keys via code, otherwise allow the server to generate them.
				if (CFMembershipSettings.ProviderKeyType == typeof(Guid) && providerUserKey == null)
				{
					var info = (CFMembershipSettings.UserType).GetProperty("UserId").GetCustomAttributesData()
						.SingleOrDefault(item => item.Constructor.ReflectedType.Name == "DatabaseGeneratedAttribute");

					if (info == null)
						usr.UserId = Guid.NewGuid(); 
				}

				usr.Username = username;
				usr.PasswordHash = passwordHash;
				usr.PasswordSalt = passwordSalt;
				usr.PasswordQuestion = passwordQuestion;
				usr.PasswordAnswer = passwordAnswer;
				usr.DateLastPasswordChange = DateTime.Now;
				usr.DateCreated = DateTime.Now;
				usr.DateLastActivity = null;
				usr.DateLastLogin = null;
				usr.Email = email;
				usr.Comment = null;
				usr.IsApproved = isApproved;

				try
				{
					Users.Add(usr);
				}
				catch (Exception)
				{
					status = MembershipCreateStatus.UserRejected;
				}
				try
				{
					DataContext.SaveChanges();
				}
				catch (Exception)
				{
					status = MembershipCreateStatus.ProviderError;
				}

				user = GetUser(usr.UserId, false);
				
			}

			DataContext.Dispose();
			
			return user;
		}
Ejemplo n.º 22
0
        public override string ResetPassword(string username, string answer)
        {
            username = Util.GetUserName(username);
            if (!EnablePasswordReset)
                throw new NotSupportedException("Password reset is not enabled.");

            var Db = GetDb();
            var user = Db.Users.SingleOrDefault(u => u.Username == username);
            if (user == null)
                throw new MembershipPasswordException("The supplied user name is not found.");

            if (answer == null && RequiresQuestionAndAnswer)
            {
                UpdateFailureCount(Db, user, "passwordAnswer");
                throw new ProviderException("Password answer required for password reset.");
            }
            string newPassword =
              Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters);

            var args = new ValidatePasswordEventArgs(username, newPassword, true);

            OnValidatingPassword(args);

            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Reset password canceled due to password validation failure.");

            if (user.IsLockedOut)
                throw new MembershipPasswordException("The supplied user is locked out.");

            if (RequiresQuestionAndAnswer && !CheckPassword(answer, user.PasswordAnswer))
            {
                UpdateFailureCount(Db, user, "passwordAnswer");
                throw new MembershipPasswordException("Incorrect password answer.");
            }
            user.Password = EncodePassword(newPassword);
            user.LastPasswordChangedDate = Util.Now;
            Db.SubmitChanges();
            return newPassword;
        }
        //
        // MembershipProvider.CreateUser
        //
        public override MembershipUser CreateUser(string username,
            string password,
            string email,
            string passwordQuestion,
            string passwordAnswer,
            bool isApproved,
            object providerUserKey,
            out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            throw new ProviderException("User creation not allowed.");
        }
Ejemplo n.º 24
0
        public override MembershipUser CreateUser(string username,
                 string password,
                 string email,
                 string passwordQuestion,
                 string passwordAnswer,
                 bool isApproved,
                 object providerUserKey,
                 out MembershipCreateStatus status)
        {
            username = Util.GetUserName(username);
            var args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }
            if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }
            var Db = GetDb();
            var u = GetUser(username, false);
            if (u == null)
            {
                int? pid = null;
                Person per = null;
                if (providerUserKey != null && providerUserKey is int)
                    per = Db.People.SingleOrDefault(p => p.PeopleId == (int)providerUserKey);
                else
                    per = Db.People.SingleOrDefault(p => p.EmailAddress == email);

                if (per != null)
                    pid = per.PeopleId;

                var createDate = Util.Now;
                var user = new User
                {
                    PeopleId = pid,
                    Username = username,
                    //EmailAddress = email,
                    Password = EncodePassword(password),
                    PasswordQuestion = passwordQuestion,
                    PasswordAnswer = EncodePassword(passwordAnswer),
                    IsApproved = isApproved,
                    Comment = "",
                    CreationDate = createDate,
                    LastPasswordChangedDate = createDate,
                    LastActivityDate = createDate,
                    IsLockedOut = false,
                    LastLockedOutDate = createDate,
                    FailedPasswordAttemptCount = 0,
                    FailedPasswordAttemptWindowStart = createDate,
                    FailedPasswordAnswerAttemptCount = 0,
                    FailedPasswordAnswerAttemptWindowStart = createDate,
                };
                Db.Users.InsertOnSubmit(user);
                Db.SubmitChanges();
                status = MembershipCreateStatus.Success;
                return GetUser(username, false);
            }
            else
                status = MembershipCreateStatus.DuplicateUserName;
            return null;
        }
Ejemplo n.º 25
0
 public User NewUser(
         string username,
         string password,
         string email,
         bool isApproved,
         int? PeopleId)
 {
     username = Util.GetUserName(username);
     var args = new ValidatePasswordEventArgs(username, password, true);
     OnValidatingPassword(args);
     if (args.Cancel)
         return null;
     var u = GetUser(username, false);
     if (u == null)
         return MakeNewUser(username, EncodePassword(password), email, isApproved, PeopleId);
     return null;
 }
 private void IridioMembershipProvider_ValidatingPassword(object sender, ValidatePasswordEventArgs e)
 {
     //Enforce our criteria
       var errorMessage = "";
       if (String.IsNullOrEmpty(e.Password))
       {
     errorMessage += "[Password missing]";
     e.Cancel = true;
     return;
       }
       var pwChar = e.Password.ToCharArray();
       //Check Length
       if (e.Password.Length < MinRequiredPasswordLength)
       {
     errorMessage += String.Format("[Minimum length: {0}]", MinRequiredPasswordLength);
     e.Cancel = true;
       }
       //Check Strength
       if (PasswordStrengthRegularExpression != string.Empty)
       {
     Regex r = new Regex(PasswordStrengthRegularExpression);
     if (!r.IsMatch(e.Password))
     {
       errorMessage += "[Insufficient Password Strength]";
       e.Cancel = true;
     }
       }
       //Check Non-alpha characters
       int iNumNonAlpha = 0;
       foreach (char c in pwChar)
       {
     if (!char.IsLetterOrDigit(c)) iNumNonAlpha++;
       }
       if (iNumNonAlpha < MinRequiredNonAlphanumericCharacters)
       {
     errorMessage += "[Insufficient Non-Alpha Characters]";
     e.Cancel = true;
       }
       e.FailureInformation = new MembershipPasswordException(errorMessage);
 }
Ejemplo n.º 27
0
        public override bool ChangePassword(string username, string oldPwd, string newPwd)
        {
            username = Util.GetUserName(username);
            if (!ValidateUser(username, oldPwd))
                return false;
            var args = new ValidatePasswordEventArgs(username, newPwd, true);

            OnValidatingPassword(args);
            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Change password canceled due to new password validation failure.");

            if (!AdminOverride)
            {
                if (newPwd.Length < MinRequiredPasswordLength)
                    throw new ArgumentException("Password must contain at least {0} chars".Fmt(MinRequiredPasswordLength));
                if (MembershipService.RequireSpecialCharacter)
                    if (newPwd.All(char.IsLetterOrDigit))
                        throw new ArgumentException("Password needs at least 1 non-alphanumeric chars");
                if (MembershipService.RequireOneNumber)
                    if (!newPwd.Any(char.IsDigit))
                        throw new ArgumentException("Password needs at least 1 number");
                if (MembershipService.RequireOneUpper)
                    if (!newPwd.Any(char.IsUpper))
                        throw new ArgumentException("Password needs at least 1 uppercase letter");
            }

            var Db = GetDb();
            var user = Db.Users.Single(u => u.Username == username);
            user.Password = EncodePassword(newPwd);
            user.MustChangePassword = false;
            user.LastPasswordChangedDate = Util.Now;
            Db.SubmitChanges();
            return true;
        }
 public override string ResetPassword(string username, string answer)
 {
     if (!EnablePasswordReset)
     throw new NotSupportedException("Password reset is not enabled.");
       if (answer == null && RequiresQuestionAndAnswer)
       {
     UpdateFailureCount(username, UpdateFailures.PasswordAnswer);
     throw new ProviderException("Password answer required for password reset.");
       }
       string newPassword = Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters);
       ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);
       OnValidatingPassword(args);
       if (args.Cancel)
     if (args.FailureInformation != null)
       throw args.FailureInformation;
     else
       throw new MembershipPasswordException("Reset password canceled due to password validation failure.");
       bool result = false;
       string passwordAnswer = "";
       try
       {
     var ut = repository.GetUserByName(username, pApplicationName);
     if (ut != null)
     {
       if (ut.IsLockedOut)
     throw new MembershipPasswordException("The supplied user is locked out.");
       passwordAnswer = ut.PasswordAnswer;
       if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
       {
     UpdateFailureCount(username, UpdateFailures.PasswordAnswer);
     throw new MembershipPasswordException("Incorrect password answer.");
       }
       serviceBus.Send(new ResetUserPassword(ut.Id, EncodePassword(newPassword), DateTime.Now));
       result = true;
     }
     else
       throw new MembershipPasswordException("The supplied user name is not found.");
       }
       catch (Exception e)
       {
     if (WriteExceptionsToEventLog)
       WriteToEventLog(e, "ResetPassword");
     throw;
       }
       if (result)
     return newPassword;
       else
     throw new MembershipPasswordException("User not found, or user is locked out. Password not Reset.");
 }
        public IridioMembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer,
      bool isApproved, out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
              OnValidatingPassword(args);
              if (args.Cancel)
              {
            status = MembershipCreateStatus.InvalidPassword;
            return null;
              }

              if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
              {
            status = MembershipCreateStatus.DuplicateEmail;
            return null;
              }

              MembershipUser user = GetUser(username, false);
              if (user == null)
              {
            try
            {
              //ComGuid to prevent fragmentation on clustered PK with Guids
              var userId = CombGuid.GetNewCombGuid();
              serviceBus.Send(new CreateUser(userId, username, EncodePassword(password), email, isApproved, pApplicationName));
              if ((passwordQuestion != null) && (passwordAnswer != null))
            serviceBus.Send(new ChangeUserPasswordQuestionAndAnswer(userId, passwordQuestion, EncodePassword(passwordAnswer)));
              status = MembershipCreateStatus.Success;
              return (IridioMembershipUser)GetUser(username, false);
            }
            catch (Exception e)
            {
              if (WriteExceptionsToEventLog)
            WriteToEventLog(e, "CreateUser");
              status = MembershipCreateStatus.ProviderError;
            }
              }
              else
              {
            status = MembershipCreateStatus.DuplicateUserName;
              }
              return null;
        }
 public bool ChangePassword(string username, string newPwd)
 {
     ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPwd, true);
       OnValidatingPassword(args);
       if (args.Cancel)
     if (args.FailureInformation != null)
       throw args.FailureInformation;
     else
       throw new MembershipPasswordException("Change password cancelled due to an error during the validation of the password");
       bool result = false;
       try
       {
     var user = repository.GetUserByName(username, pApplicationName);
     if (user != null)
     {
       serviceBus.Send(new ChangeUserPassword(user.Id, EncodePassword(newPwd), DateTime.Now));
       result = true;
     }
       }
       catch (Exception e)
       {
     if (WriteExceptionsToEventLog)
       WriteToEventLog(e, "ChangePassword");
     throw;
       }
       return result;
 }
        /// <summary>
        /// This function is for creating a new user.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="email">Ignored</param>
        /// <param name="passwordQuestion">Ignored</param>
        /// <param name="passwordAnswer">Ignored</param>
        /// <param name="isApproved">Ignored</param>
        /// <param name="providerUserKey">Ignored</param>
        /// <param name="status">
        /// <para>
        /// Can return InvalidUserName, DuplicateUserName, InvalidPassword or Success
        /// </para>
        /// </param>
        /// <returns>User object when <paramref name="status"/> = Success; null otherwise. </returns>
        /// <remarks>
        /// <para>
        /// The user is always created with an expired password. The default profile is assigned to the user. CONNECT THROUGH rights are given to the proxy user.
        /// </para>
        /// <para>
        /// The logged in user must have the rights to crete User. Following is the script.
        /// </para>
        /// <code>
        /// <![CDATA[
        /// GRANT CREATE USER TO <user-name> 
        /// ]]>
        /// </code>
        /// </remarks>
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer,
            bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("password");
            }
            var e = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(e);
            if (e.Cancel)
            {
                // App decided to cancel user creation
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (HttpContext.Current == null || string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
            {
                throw new MembershipCreateUserException("You must be logged in with proper credentials to create a user");
            }

            EnsureDefaultProfile();
            //var builder = new OracleConnectionStringBuilder(_connectionString);

            using (var db = new OracleDatastore(HttpContext.Current.Trace))
            {
                db.CreateConnection(_connectionString, HttpContext.Current.User.Identity.Name);
                try
                {
                    var sqlQuery = string.Format("CREATE USER {0} IDENTIFIED BY \"{1}\" PROFILE {2} PASSWORD EXPIRE", username, password, _visibleProfiles[0]);
                    db.ExecuteNonQuery(sqlQuery, null);
                    foreach (var proxy in _proxyUsers)
                    {
                        sqlQuery = string.Format("ALTER USER {0} GRANT CONNECT THROUGH {1}", username, proxy);
                        db.ExecuteNonQuery(sqlQuery, null);
                    }
                    status = MembershipCreateStatus.Success;
                    // GetUser gets too much information, so we are using FindUserByName.
                    //return GetUser(username, false);
                    int totalRecords;
                    return FindUsersByName(username, 0, 100, out totalRecords).Cast<MembershipUser>().First();
                }
                catch (OracleDataStoreException ex)
                {
                    switch (ex.OracleErrorNumber)
                    {
                        case 1935:
                        //1935: missing user or role name (comes when passing null username). Not expected as we are already checking the passed user.
                        case 922:
                            //922: Missing or invalid option (comes when password contains special chars or whitespace)
                            throw new MembershipCreateUserException("User name or password is invalid", ex);

                        case 1031:
                            //1031: insufficient privileges
                            throw new MembershipCreateUserException("You do not have sufficient privileges for creating users.", ex);

                        case 1920:
                            //1920: user name 'user-name' conflicts with another user
                            throw new MembershipCreateUserException(string.Format("User {0} already exists", username));
                        case 28003:
                            // ORA-28003: password verification for the specified password failed
                            throw new MembershipCreateUserException(ex.Message, ex);

                        default:
                            throw;
                    }
                }
            }
        }
Ejemplo n.º 32
-1
        /// <summary>
        /// The password change will succeed only if the old password is valid.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns>true if password successfully changed. false if the old password is invalid</returns>
        /// <remarks>
        /// Any data base exception encountered will be propagated to the caller.
        /// Sharad 15 Feb 2012: Supported voluntary changes of passwords. Earlier only expired passwords could be changed.
        /// Sharad 21 Feb 2012: Raising ValidatingPassword event
        /// </remarks>
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username");
            }
            if (string.IsNullOrWhiteSpace(oldPassword))
            {
                throw new ArgumentNullException("oldPassword");
            }
            if (string.IsNullOrWhiteSpace(newPassword))
            {
                throw new ArgumentNullException("newPassword");
            }
            var e = new ValidatePasswordEventArgs(username, newPassword, true);
            OnValidatingPassword(e);
            if (e.Cancel)
            {
                // App decided to cancel user creation
                return false;
            }
            var builder = new OracleConnectionStringBuilder(_connectionString)
                              {
                                  UserID = username,
                                  Password = oldPassword,
                                  Pooling = false,
                                  ProxyUserId = string.Empty,
                                  ProxyPassword = string.Empty
                              };
            // Try to login as passed user with old password to ensure that the old password is valid
            using (var db = new OracleDatastore(HttpContext.Current.Trace))
            {
                var msg = string.Format("Opening connection to {0} for user {1}",
                                          builder.DataSource, builder.UserID);
                Trace.WriteLine(msg, "OracleMembershipProvider");
                db.CreateConnection(builder.ConnectionString, builder.UserID);
                Trace.WriteLine(msg, "Opening connection with old password");
                try
                {
                    db.Connection.Open();
                }
                catch (OracleException ex)
                {
                    switch (ex.Number)
                    {
                        case 1017:
                            // Invalid user name password
                            Trace.TraceWarning("Invalid password specified for user {0}", username);
                            return false;

                        case 28001:
                            // If we are using ODP.NET, we can change the password now
                            // This will only work if the user's password has expired
                            Trace.WriteLine(msg, "Password expired error oracle exception encountered");
                            db.Connection.OpenWithNewPassword(newPassword);
                            return true;

                        default:
                            throw;
                    }
                }

                // If we get here, the old password was valid. Now we will change the password
                //REPLACE is used to remove exception ORA-28221
                Trace.WriteLine(msg, "Executing ALTER USER with new password");
                var query = string.Format("ALTER USER {0} IDENTIFIED BY \"{1}\" REPLACE \"{2}\"", username, newPassword, oldPassword);
                db.ExecuteNonQuery(query, null);

            }
            return true;
        }