SQL Server User Store for FSCAuth

Well, I finally got around to writing a UserStore utilizing SQL Server. I did it without an ORM.. which is annoying at best, but regardless, I'd say it gets the job done and is sorta easy to extend for your own UserData class. SQL doesn't play well with inheritance though. It's quite difficult to write an easy to extend data class without using an ORM

Anyway, here is the code:

namespace Earlz.FSCAuth.Extensions
{
    public class SqlServerUserStore : IUserStore
    {
        private static SqlServerUserStore instance;
        private SqlServerUserStore() {}

        public static SqlServerUserStore Instance
        {
          get 
          {
             if (instance == null)
             {
                instance = new SqlServerUserStore();
             }
             return instance;
          }
        }
        /// <summary>
        /// Will get a user by username or email address
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        virtual public UserData GetUserByName(string name)
        {
            using (var con=GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.CommandText="select * from users left join Groups on"+
                    " groups.UserID=users.ID where username=@name or "+
                    " emailaddress=@name";
                cmd.Connection = con;
                cmd.Parameters.Add(new SqlParameter("@name", name));
                return ReaderToUserData(cmd.ExecuteReader());
            }
        }

        virtual public bool UpdateUserByID(UserData user)
        {
            var old = GetUserByName(user.Username);
            if (old == null)
            {
                return false;
            }
            using (var con = GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText="";
                if (old.Groups.TrueForAll(x => user.Groups.Contains(x)))
                {
                    //update groups as well.
                    //we're just going to do it messy and drop all groups
                    //and add them back in.
                    cmd.CommandText = "delete from groups where userid=@userid;";
                    foreach (var g in user.Groups)
                    {
                        cmd.CommandText += "insert into groups (name,userid)"+
                        " values('" + g.Replace("'", "''") + "',@userid);";
                    }
                }
                cmd.CommandText += "update users set emailaddress=@email, username=@username,"+
                " salt=@salt, passwordhash=@password ";
                cmd.CommandText += "where id=@userid;";
                cmd.Parameters.Add(new SqlParameter("@userid", user.UniqueID));
                cmd.Parameters.Add(new SqlParameter("@email",user.EmailAddress ?? ""));
                cmd.Parameters.Add(new SqlParameter("@username",user.Username));
                cmd.Parameters.Add(new SqlParameter("@salt",user.Salt));
                cmd.Parameters.Add(new SqlParameter("@password",user.PasswordHash));
                if (cmd.ExecuteNonQuery() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

        }

        virtual public bool AddUser(UserData user)
        {
            using(var con=GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = "declare @userid as integer;";
                cmd.CommandText += "insert into users (username,emailaddress,passwordhash,salt)"+
                " values (@username,@email,@password,@salt);";
                cmd.CommandText += "set @userid=scope_identity();";
                foreach (var g in user.Groups)
                {
                    cmd.CommandText += "insert into groups (name,userid) values "+
                    "('" + g.Replace("'", "''") + "',@userid);";
                }
                cmd.CommandText += "select @userid;";
                cmd.Parameters.Add(new SqlParameter("@email",user.EmailAddress ?? ""));
                cmd.Parameters.Add(new SqlParameter("@username",user.Username));
                cmd.Parameters.Add(new SqlParameter("@salt",user.Salt ?? ""));
                cmd.Parameters.Add(new SqlParameter("@password", user.PasswordHash ?? ""));
                try
                {
                    user.UniqueID = ((int)cmd.ExecuteScalar()).ToString();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        virtual public bool DeleteUserByID(UserData user)
        {
            using (var con = GetConnection())
            {
                con.Open();
                var cmd = new SqlCommand();
                cmd.CommandText = "delete from groups where userid=@userid; delete from users where id=@userid";
                cmd.Connection = con;
                cmd.Parameters.Add(new SqlParameter("@userid", int.Parse(user.UniqueID)));
                if (cmd.ExecuteNonQuery() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        virtual protected UserData ReaderToUserData(IDataReader rdr)
        {
            if (!rdr.Read())
            {
                return null;
            }
            var u = new UserData();
            u.EmailAddress = rdr["EmailAddress"] as string;
            u.PasswordHash = rdr["PasswordHash"] as string;
            u.Salt = rdr["Salt"] as string;
            u.UniqueID = ((int)rdr[0]).ToString(); //user.id
            u.Username = rdr["Username"] as string;
            u.Groups=new List<string>();
            if (rdr["Name"] != null && !(rdr["Name"] is DBNull))
            {
                u.Groups.Add(rdr["Name"] as string);
                while(rdr.Read()){
                    u.Groups.Add(rdr["Name"] as string);
                }
            }
            rdr.Close();
            return u;

        }
        protected virtual SqlConnection GetConnection()
        {
            string s=ConfigurationManager.ConnectionStrings["fscauth"].ConnectionString;
            var con = new SqlConnection(s);
            return con;
        }
    }
}

Also, BSD licensed again:

Copyright (c) 2011 Jordan "Earlz/hckr83" Earls http://lastyearswishes.com All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Posted: 6/12/2011 9:57:37 PM

Comments

Posting comments is currently disabled(probably due to spam)