sen

导航

学习笔记之 一个自定义的MembershipProvider类

Posted on 2009-11-13 21:31  sen  阅读(553)  评论(0编辑  收藏  举报

在用VS自带的登陆控件时,数据库是一件麻烦的事件,下面介绍一个用自己定义的数据库的方法

1,写一个自定义的MembershipProvider类,继承MembershipProvider 如下面的代码

2,在web.config 的<System.web>节点下加:

 <membership defaultProvider="CustomMembershipProvider">
      <providers>
        <add name="CustomMembershipProvider" type="myNameSpace.CustomMembershipProvider" requiresQuestionAndAnswer="false" connectionString="DatabaseConnectionString"/>
        //请注意这里指定了数库的连接的配置节点 ,这是为了在那个自定义类中运用
      </providers>
    </membership>

3,加入一个验证方式:

    <authentication mode="Forms">
      <forms name="WPFORMAUTH" loginUrl="~/Login.aspx" timeout="90"/> //loginUrl指定登陆页面和未验证返回的页面
    </authentication>

  public class CustomMembershipProvider : System.Web.Security.MembershipProvider
    {
        private string _connectionString;

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            string connStringName = config["connectionString"];//这里去得到那个在web.config节点中配置的数据库连接字符串
            this._connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[connStringName].ConnectionString;
            base.Initialize(name, config);
        }

        public override string ApplicationName
        {
            get
            {
                return null;
            }
            set
            {
                //throw new Exception("The method or operation is not implemented.");
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this._connectionString);

            try
            {
                conn.Open();
                string sql = "UPDATE Membership SET password=@newPassword WHERE username=@username AND password=@oldPassword";
                System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sql, conn);
                comm.Parameters.AddWithValue("@username", username);
                comm.Parameters.AddWithValue("@oldPassword", oldPassword);
                comm.Parameters.AddWithValue("@newPassword", newPassword);

                int result = comm.ExecuteNonQuery();
                if (result > 0)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();
            }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            return false;
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this._connectionString);

            try
            {
                conn.Open();
                string sql = "INSERT INTO Membership VALUES (@username, @password, @email, @passwordQuestion, @passwordAnswer)";
                System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sql, conn);
                comm.Parameters.AddWithValue("@username", username);
                comm.Parameters.AddWithValue("@password", password);
                comm.Parameters.AddWithValue("@email", email);
                comm.Parameters.AddWithValue("@passwordQuestion", passwordQuestion);
                comm.Parameters.AddWithValue("@passwordAnswer", passwordAnswer);
                comm.ExecuteNonQuery();
                conn.Close();

                status = MembershipCreateStatus.Success;
                MembershipUser user = new MembershipUser("CustomMembershipProvider",
                    username, null, email, passwordQuestion, null, true, false, DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);
                return user;
            }
            catch (Exception ex)
            {
                status = MembershipCreateStatus.UserRejected;
                return null;
            }
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            return false;
        }

        public override bool EnablePasswordReset
        {
            get
            {
                return false;
            }
        }

        public override bool EnablePasswordRetrieval
        {
            get
            {
                return false;
            }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            return null;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            return null;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            return null;
        }

        public override int GetNumberOfUsersOnline()
        {
            return 0;
        }

        public override string GetPassword(string username, string answer)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this._connectionString);

            try
            {
                conn.Open();
                string sql = "SELECT password FROM Membership WHERE username=@username";
                System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sql, conn);
                comm.Parameters.AddWithValue("@username", username);

                System.Data.SqlClient.SqlDataReader reader = comm.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    return reader.GetString(0);
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();
            }
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return null;
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this._connectionString);

            try
            {
                conn.Open();
                string sql = "SELECT username, password FROM Membership WHERE username=@username";
                System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sql, conn);
                comm.Parameters.AddWithValue("@username", username);

                System.Data.SqlClient.SqlDataReader reader = comm.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    MembershipUser user = new MembershipUser("CustomMembershipProvider",
                        reader.GetString(0), null, null, null, null, true, false,
                        DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);

                    return user;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();
            }
        }

        public override string GetUserNameByEmail(string email)
        {
            return null;
        }

        public override int MaxInvalidPasswordAttempts
        {
            get
            {
                return 0;
            }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get
            {
                return 0;
            }
        }

        public override int PasswordAttemptWindow
        {
            get
            {
                return 0;
            }
        }

        public override int MinRequiredPasswordLength
        {
            get
            {
                return 0;
            }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get
            {
                return MembershipPasswordFormat.Clear;
            }
        }

        public override string PasswordStrengthRegularExpression
        {
            get
            {
                return null;
            }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get
            {
                return false;
            }
        }

        public override bool RequiresUniqueEmail
        {
            get
            {
                return false;
            }
        }

        public override string ResetPassword(string username, string answer)
        {
            return null;
        }

        public override bool UnlockUser(string userName)
        {
            return false;
        }

        public override void UpdateUser(MembershipUser user)
        {

        }

        public override bool ValidateUser(string username, string password)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this._connectionString);

            try
            {

                conn.Open();
                string sql = "SELECT * FROM Membership WHERE username=@username AND password=@password";
                System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sql, conn);
                comm.Parameters.AddWithValue("@username", username);
                comm.Parameters.AddWithValue("@password", password);

                System.Data.SqlClient.SqlDataReader reader = comm.ExecuteReader();


                if (reader.HasRows)
                {
                    webpart.LoginUser.ib_Login = true;
                    webpart.LoginUser.name = username;
                    reader.Read();
                    string isFactroy = reader[6].ToString();
                    if (isFactroy == "1")
                        webpart.LoginUser.ib_factory = true;
                    else
                        webpart.LoginUser.ib_factory = false;

                    return true;
                }
                else
                {
                    webpart.LoginUser.ib_Login = true;
                    webpart.LoginUser.name = username;
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();
            }
        }
    }