| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713 |
- //
- // $Id: PgRoleProvider.cs 12 2007-10-17 17:22:43Z dna $
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
- // Copyright © 2006, 2007 Nauck IT KG http://www.nauck-it.de
- //
- // Author:
- // Daniel Nauck <d.nauck(at)nauck-it.de>
- //
- // Adapted to Sqlite by Marek Habersack <[email protected]>
- //
- #if NET_2_0
- using System;
- using System.Data;
- using System.Data.Common;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Diagnostics;
- using System.Text;
- using System.Configuration;
- using System.Configuration.Provider;
- using System.Web.Hosting;
- using System.Web.Security;
- using Mono.Data.Sqlite;
- namespace System.Web.Security
- {
- internal class SqliteRoleProvider : RoleProvider
- {
- private const string m_RolesTableName = "Roles";
- private const string m_UserInRolesTableName = "UsersInRoles";
- private string m_ConnectionString = string.Empty;
- DbParameter AddParameter (DbCommand command, string parameterName)
- {
- return AddParameter (command, parameterName, null);
- }
-
- DbParameter AddParameter (DbCommand command, string parameterName, object parameterValue)
- {
- return AddParameter (command, parameterName, ParameterDirection.Input, parameterValue);
- }
- DbParameter AddParameter (DbCommand command, string parameterName, ParameterDirection direction, object parameterValue)
- {
- DbParameter dbp = command.CreateParameter ();
- dbp.ParameterName = parameterName;
- dbp.Value = parameterValue;
- dbp.Direction = direction;
- command.Parameters.Add (dbp);
- return dbp;
- }
- DbParameter AddParameter (DbCommand command, string parameterName, ParameterDirection direction, DbType type, object parameterValue)
- {
- DbParameter dbp = command.CreateParameter ();
- dbp.ParameterName = parameterName;
- dbp.Value = parameterValue;
- dbp.Direction = direction;
- dbp.DbType = type;
- command.Parameters.Add (dbp);
- return dbp;
- }
-
- /// <summary>
- /// System.Configuration.Provider.ProviderBase.Initialize Method
- /// </summary>
- public override void Initialize(string name, NameValueCollection config)
- {
- // Initialize values from web.config.
- if (config == null)
- throw new ArgumentNullException("Config", Properties.Resources.ErrArgumentNull);
- if (string.IsNullOrEmpty(name))
- name = Properties.Resources.RoleProviderDefaultName;
- if (string.IsNullOrEmpty(config["description"]))
- {
- config.Remove("description");
- config.Add("description", Properties.Resources.RoleProviderDefaultDescription);
- }
- // Initialize the abstract base class.
- base.Initialize(name, config);
- m_ApplicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);
- // Get connection string.
- string connStrName = config["connectionStringName"];
- if (string.IsNullOrEmpty(connStrName))
- {
- throw new ArgumentOutOfRangeException("ConnectionStringName", Properties.Resources.ErrArgumentNullOrEmpty);
- }
- else
- {
- ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[connStrName];
- if (ConnectionStringSettings == null || string.IsNullOrEmpty(ConnectionStringSettings.ConnectionString.Trim()))
- {
- throw new ProviderException(Properties.Resources.ErrConnectionStringNullOrEmpty);
- }
- m_ConnectionString = ConnectionStringSettings.ConnectionString;
- }
- }
- /// <summary>
- /// System.Web.Security.RoleProvider properties.
- /// </summary>
- #region System.Web.Security.RoleProvider properties
- private string m_ApplicationName = string.Empty;
- public override string ApplicationName
- {
- get { return m_ApplicationName; }
- set { m_ApplicationName = value; }
- }
- #endregion
- /// <summary>
- /// System.Web.Security.RoleProvider methods.
- /// </summary>
- #region System.Web.Security.RoleProvider methods
- /// <summary>
- /// RoleProvider.AddUsersToRoles
- /// </summary>
- public override void AddUsersToRoles(string[] userNames, string[] roleNames)
- {
- foreach (string rolename in roleNames)
- {
- if (!RoleExists(rolename))
- {
- throw new ProviderException(string.Format(Properties.Resources.ErrRoleNotExist, rolename));
- }
- }
- foreach (string username in userNames)
- {
- foreach (string rolename in roleNames)
- {
- if (IsUserInRole(username, rolename))
- {
- throw new ProviderException(string.Format(Properties.Resources.ErrUserAlreadyInRole, username, rolename));
- }
- }
- }
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("INSERT INTO \"{0}\" (\"Username\", \"Rolename\", \"ApplicationName\") Values (@Username, @Rolename, @ApplicationName)", m_UserInRolesTableName);
- AddParameter (dbCommand, "@Username");
- AddParameter (dbCommand, "@Rolename");
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- SqliteTransaction dbTrans = null;
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (dbTrans = dbConn.BeginTransaction())
- {
- foreach (string username in userNames)
- {
- foreach (string rolename in roleNames)
- {
- dbCommand.Parameters["@Username"].Value = username;
- dbCommand.Parameters["@Rolename"].Value = rolename;
- dbCommand.ExecuteNonQuery();
- }
- }
- // Attempt to commit the transaction
- dbTrans.Commit();
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- try
- {
- // Attempt to roll back the transaction
- Trace.WriteLine(Properties.Resources.LogRollbackAttempt);
- dbTrans.Rollback();
- }
- catch (SqliteException re)
- {
- // Rollback failed
- Trace.WriteLine(Properties.Resources.ErrRollbackFailed);
- Trace.WriteLine(re.ToString());
- }
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- }
- /// <summary>
- /// RoleProvider.CreateRole
- /// </summary>
- public override void CreateRole(string roleName)
- {
- if (RoleExists(roleName))
- {
- throw new ProviderException(string.Format(Properties.Resources.ErrRoleAlreadyExist, roleName));
- }
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("INSERT INTO \"{0}\" (\"Rolename\", \"ApplicationName\") Values (@Rolename, @ApplicationName)", m_RolesTableName);
- AddParameter (dbCommand, "@Rolename", roleName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- dbCommand.ExecuteNonQuery();
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- }
- /// <summary>
- /// RoleProvider.DeleteRole
- /// </summary>
- public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
- {
- if (!RoleExists(roleName))
- {
- throw new ProviderException(string.Format(Properties.Resources.ErrRoleNotExist, roleName));
- }
- if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0)
- {
- throw new ProviderException(Properties.Resources.ErrCantDeletePopulatedRole);
- }
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("DELETE FROM \"{0}\" WHERE \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName", m_RolesTableName);
- AddParameter (dbCommand, "@Rolename", roleName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- SqliteTransaction dbTrans = null;
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (dbTrans = dbConn.BeginTransaction())
- {
- dbCommand.ExecuteNonQuery();
- // Attempt to commit the transaction
- dbTrans.Commit();
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- try
- {
- // Attempt to roll back the transaction
- Trace.WriteLine(Properties.Resources.LogRollbackAttempt);
- dbTrans.Rollback();
- }
- catch (SqliteException re)
- {
- // Rollback failed
- Trace.WriteLine(Properties.Resources.ErrRollbackFailed);
- Trace.WriteLine(re.ToString());
- }
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return true;
- }
- /// <summary>
- /// RoleProvider.FindUsersInRole
- /// </summary>
- public override string[] FindUsersInRole(string roleName, string usernameToMatch)
- {
- List<string> userList = new List<string>();
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("SELECT \"Username\" FROM \"{0}\" WHERE \"Username\" LIKE @Username AND \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName ORDER BY \"Username\" ASC", m_UserInRolesTableName);
- AddParameter (dbCommand, "@Username", usernameToMatch);
- AddParameter (dbCommand, "@Rolename", roleName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (SqliteDataReader reader = dbCommand.ExecuteReader())
- {
- if (reader.HasRows)
- {
- while (reader.Read())
- {
- userList.Add(reader.GetString(0));
- }
- }
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return userList.ToArray();
- }
- /// <summary>
- /// RoleProvider.GetAllRoles
- /// </summary>
- public override string[] GetAllRoles()
- {
- List<string> rolesList = new List<string>();
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("SELECT \"Rolename\" FROM \"{0}\" WHERE \"ApplicationName\" = @ApplicationName ORDER BY \"Rolename\" ASC", m_RolesTableName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (SqliteDataReader reader = dbCommand.ExecuteReader())
- {
- while (reader.Read())
- {
- rolesList.Add(reader.GetString(0));
- }
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return rolesList.ToArray();
- }
- /// <summary>
- /// RoleProvider.GetRolesForUser
- /// </summary>
- public override string[] GetRolesForUser(string username)
- {
- List<string> rolesList = new List<string>();
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("SELECT \"Rolename\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName ORDER BY \"Rolename\" ASC", m_UserInRolesTableName);
- AddParameter (dbCommand, "@Username", username);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (SqliteDataReader reader = dbCommand.ExecuteReader())
- {
- if (reader.HasRows)
- {
- while (reader.Read())
- {
- rolesList.Add(reader.GetString(0));
- }
- }
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return rolesList.ToArray();
- }
- /// <summary>
- /// RoleProvider.GetUsersInRole
- /// </summary>
- public override string[] GetUsersInRole(string roleName)
- {
- List<string> userList = new List<string>();
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("SELECT \"Username\" FROM \"{0}\" WHERE \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName ORDER BY \"Username\" ASC", m_UserInRolesTableName);
- AddParameter (dbCommand, "@Rolename", roleName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (SqliteDataReader reader = dbCommand.ExecuteReader())
- {
- if (reader.HasRows)
- {
- while (reader.Read())
- {
- userList.Add(reader.GetString(0));
- }
- }
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return userList.ToArray();
- }
- /// <summary>
- /// RoleProvider.IsUserInRole
- /// </summary>
- public override bool IsUserInRole(string userName, string roleName)
- {
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("SELECT COUNT(*) FROM \"{0}\" WHERE \"Username\" = @Username AND \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName", m_UserInRolesTableName);
- AddParameter (dbCommand, "@Username", userName);
- AddParameter (dbCommand, "@Rolename", roleName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- int numRecs = 0;
- Int32.TryParse(dbCommand.ExecuteScalar().ToString(), out numRecs);
- if (numRecs > 0)
- return true;
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return false;
- }
- /// <summary>
- /// RoleProvider.RemoveUsersFromRoles
- /// </summary>
- public override void RemoveUsersFromRoles(string[] userNames, string[] roleNames)
- {
- foreach (string rolename in roleNames)
- {
- if (!RoleExists(rolename))
- {
- throw new ProviderException(string.Format(Properties.Resources.ErrRoleNotExist, rolename));
- }
- }
- foreach (string username in userNames)
- {
- foreach (string rolename in roleNames)
- {
- if (!IsUserInRole(username, rolename))
- {
- throw new ProviderException(string.Format(Properties.Resources.ErrUserIsNotInRole, username, rolename));
- }
- }
- }
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("DELETE FROM \"{0}\" WHERE \"Username\" = @Username AND \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName", m_UserInRolesTableName);
- AddParameter (dbCommand, "@Username");
- AddParameter (dbCommand, "@Rolename");
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- SqliteTransaction dbTrans = null;
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- using (dbTrans = dbConn.BeginTransaction())
- {
- foreach (string username in userNames)
- {
- foreach (string rolename in roleNames)
- {
- dbCommand.Parameters["@Username"].Value = username;
- dbCommand.Parameters["@Rolename"].Value = rolename;
- dbCommand.ExecuteNonQuery();
- }
- }
- // Attempt to commit the transaction
- dbTrans.Commit();
- }
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- try
- {
- // Attempt to roll back the transaction
- Trace.WriteLine(Properties.Resources.LogRollbackAttempt);
- dbTrans.Rollback();
- }
- catch (SqliteException re)
- {
- // Rollback failed
- Trace.WriteLine(Properties.Resources.ErrRollbackFailed);
- Trace.WriteLine(re.ToString());
- }
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- }
- /// <summary>
- /// RoleProvider.RoleExists
- /// </summary>
- public override bool RoleExists(string roleName)
- {
- using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
- {
- using (SqliteCommand dbCommand = dbConn.CreateCommand())
- {
- dbCommand.CommandText = string.Format("SELECT COUNT(*) FROM \"{0}\" WHERE \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName", m_RolesTableName);
- AddParameter (dbCommand, "@Rolename", roleName);
- AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
- try
- {
- dbConn.Open();
- dbCommand.Prepare();
- int numRecs = 0;
- Int32.TryParse(dbCommand.ExecuteScalar().ToString(), out numRecs);
- if (numRecs > 0)
- return true;
- }
- catch (SqliteException e)
- {
- Trace.WriteLine(e.ToString());
- throw new ProviderException(Properties.Resources.ErrOperationAborted);
- }
- finally
- {
- if (dbConn != null)
- dbConn.Close();
- }
- }
- }
- return false;
- }
- #endregion
- #region private methods
- /// <summary>
- /// A helper function to retrieve config values from the configuration file.
- /// </summary>
- /// <param name="configValue"></param>
- /// <param name="defaultValue"></param>
- /// <returns></returns>
- private string GetConfigValue(string configValue, string defaultValue)
- {
- if (string.IsNullOrEmpty(configValue))
- return defaultValue;
- return configValue;
- }
- #endregion
- }
- }
- #endif
|