3 // Permission is hereby granted, free of charge, to any person obtaining
4 // a copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to
8 // permit persons to whom the Software is furnished to do so, subject to
9 // the following conditions:
11 // The above copyright notice and this permission notice shall be
12 // included in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 // Copyright © 2006, 2007 Nauck IT KG http://www.nauck-it.de
25 // Daniel Nauck <d.nauck(at)nauck-it.de>
27 // Adapted to Sqlite by Marek Habersack <mhabersack@novell.com>
33 using System.Data.Common;
34 using System.Collections.Generic;
35 using System.Collections.Specialized;
37 using System.Security.Cryptography;
38 using System.Web.Hosting;
39 using System.Web.Configuration;
40 using System.Web.Security;
41 using System.Configuration;
42 using System.Configuration.Provider;
43 using System.Diagnostics;
45 using Mono.Data.Sqlite;
47 namespace System.Web.Security
49 internal class SqliteMembershipProvider : MembershipProvider
51 const string m_TableName = "Users";
52 string m_ConnectionString = string.Empty;
53 const int m_NewPasswordLength = 8;
54 bool machineKeyIsAutoGenerated;
56 // Used when determining encryption key values.
57 MachineKeySection m_MachineKey = null;
59 DbParameter AddParameter (DbCommand command, string parameterName, object parameterValue)
61 return AddParameter (command, parameterName, ParameterDirection.Input, parameterValue);
64 DbParameter AddParameter (DbCommand command, string parameterName, ParameterDirection direction, object parameterValue)
66 DbParameter dbp = command.CreateParameter ();
67 dbp.ParameterName = parameterName;
68 dbp.Value = parameterValue;
69 dbp.Direction = direction;
70 command.Parameters.Add (dbp);
75 /// System.Configuration.Provider.ProviderBase.Initialize Method.
77 public override void Initialize(string name, NameValueCollection config)
79 // Initialize values from web.config.
81 throw new ArgumentNullException("Config", Properties.Resources.ErrArgumentNull);
83 if (string.IsNullOrEmpty(name))
84 name = Properties.Resources.MembershipProviderDefaultName;
86 if (string.IsNullOrEmpty(config["description"]))
88 config.Remove("description");
89 config.Add("description", Properties.Resources.MembershipProviderDefaultDescription);
92 // Initialize the abstract base class.
93 base.Initialize(name, config);
95 m_ApplicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);
96 m_MaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
97 m_PasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
98 m_MinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1"));
99 m_MinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7"));
100 m_PasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
101 m_EnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
102 m_EnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true"));
103 m_RequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false"));
104 m_RequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true"));
106 // Get password encryption type.
107 string pwFormat = GetConfigValue(config["passwordFormat"], "Hashed");
111 m_PasswordFormat = MembershipPasswordFormat.Hashed;
114 m_PasswordFormat = MembershipPasswordFormat.Encrypted;
117 m_PasswordFormat = MembershipPasswordFormat.Clear;
120 throw new ProviderException(Properties.Resources.ErrPwFormatNotSupported);
123 // Get connection string.
124 string connStrName = config["connectionStringName"];
126 if (string.IsNullOrEmpty(connStrName))
128 throw new ArgumentOutOfRangeException("ConnectionStringName", Properties.Resources.ErrArgumentNullOrEmpty);
132 ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[connStrName];
134 if (ConnectionStringSettings == null || string.IsNullOrEmpty(ConnectionStringSettings.ConnectionString.Trim()))
136 throw new ProviderException(Properties.Resources.ErrConnectionStringNullOrEmpty);
139 m_ConnectionString = ConnectionStringSettings.ConnectionString;
142 // Get encryption and decryption key information from the configuration.
143 m_MachineKey = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey", null);
145 if (!m_PasswordFormat.Equals(MembershipPasswordFormat.Clear))
147 if (m_MachineKey == null)
148 throw new ArgumentNullException("system.web/machineKey", Properties.Resources.ErrArgumentNull);
150 if (m_MachineKey.ValidationKey.Contains("AutoGenerate")) {
151 machineKeyIsAutoGenerated = true;
152 if (m_PasswordFormat.Equals (MembershipPasswordFormat.Encrypted))
153 throw new ProviderException(Properties.Resources.ErrAutoGeneratedKeyNotSupported);
159 /// System.Web.Security.MembershipProvider properties.
161 #region System.Web.Security.MembershipProvider properties
162 string m_ApplicationName = string.Empty;
163 bool m_EnablePasswordReset = false;
164 bool m_EnablePasswordRetrieval = false;
165 bool m_RequiresQuestionAndAnswer = false;
166 bool m_RequiresUniqueEmail = false;
167 int m_MaxInvalidPasswordAttempts = 0;
168 int m_PasswordAttemptWindow = 0;
169 MembershipPasswordFormat m_PasswordFormat = MembershipPasswordFormat.Clear;
170 int m_MinRequiredNonAlphanumericCharacters = 0;
171 int m_MinRequiredPasswordLength = 0;
172 string m_PasswordStrengthRegularExpression = string.Empty;
174 public override string ApplicationName
176 get { return m_ApplicationName; }
177 set { m_ApplicationName = value; }
180 public override bool EnablePasswordReset
182 get { return m_EnablePasswordReset; }
185 public override bool EnablePasswordRetrieval
187 get { return m_EnablePasswordRetrieval; }
190 public override bool RequiresQuestionAndAnswer
192 get { return m_RequiresQuestionAndAnswer; }
195 public override bool RequiresUniqueEmail
197 get { return m_RequiresUniqueEmail; }
200 public override int MaxInvalidPasswordAttempts
202 get { return m_MaxInvalidPasswordAttempts; }
205 public override int PasswordAttemptWindow
207 get { return m_PasswordAttemptWindow; }
210 public override MembershipPasswordFormat PasswordFormat
212 get { return m_PasswordFormat; }
215 public override int MinRequiredNonAlphanumericCharacters
217 get { return m_MinRequiredNonAlphanumericCharacters; }
220 public override int MinRequiredPasswordLength
222 get { return m_MinRequiredPasswordLength; }
225 public override string PasswordStrengthRegularExpression
227 get { return m_PasswordStrengthRegularExpression; }
233 /// System.Web.Security.MembershipProvider methods.
235 #region System.Web.Security.MembershipProvider methods
238 /// MembershipProvider.ChangePassword
240 public override bool ChangePassword(string username, string oldPassword, string newPassword)
242 if (!ValidateUser(username, oldPassword))
245 ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);
247 OnValidatingPassword(args);
251 if (args.FailureInformation != null)
252 throw args.FailureInformation;
254 throw new MembershipPasswordException(Properties.Resources.ErrPasswordChangeCanceled);
257 int rowsAffected = 0;
259 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
261 using (SqliteCommand dbCommand = dbConn.CreateCommand())
263 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"Password\" = @Password, \"LastPasswordChangedDate\" = @LastPasswordChangedDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
265 AddParameter (dbCommand,"@Password", EncodePassword(newPassword));
266 AddParameter (dbCommand,"@LastPasswordChangedDate", DateTime.Now);
267 AddParameter (dbCommand,"@Username", username);
268 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
275 rowsAffected = dbCommand.ExecuteNonQuery();
277 catch (SqliteException e)
279 Trace.WriteLine(e.ToString());
280 throw new ProviderException(Properties.Resources.ErrOperationAborted);
290 if (rowsAffected > 0)
297 /// MembershipProvider.ChangePasswordQuestionAndAnswer
299 public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
301 if (!ValidateUser(username, password))
304 int rowsAffected = 0;
306 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
308 using (SqliteCommand dbCommand = dbConn.CreateCommand())
310 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"PasswordQuestion\" = @PasswordQuestion, \"PasswordAnswer\" = @PasswordAnswer WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
312 AddParameter (dbCommand,"@PasswordQuestion", newPasswordQuestion);
313 AddParameter (dbCommand,"@PasswordAnswer", EncodePassword(newPasswordAnswer));
314 AddParameter (dbCommand,"@Username", username);
315 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
322 rowsAffected = dbCommand.ExecuteNonQuery();
324 catch (SqliteException e)
326 Trace.WriteLine(e.ToString());
327 throw new ProviderException(Properties.Resources.ErrOperationAborted);
337 if (rowsAffected > 0)
344 /// MembershipProvider.CreateUser
346 public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved,
347 object providerUserKey, out MembershipCreateStatus status)
349 ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
351 OnValidatingPassword(args);
355 status = MembershipCreateStatus.InvalidPassword;
359 if (RequiresUniqueEmail && string.IsNullOrEmpty(email))
361 status = MembershipCreateStatus.InvalidEmail;
365 if (RequiresUniqueEmail && !string.IsNullOrEmpty(GetUserNameByEmail(email)))
367 status = MembershipCreateStatus.DuplicateEmail;
371 if (GetUser(username, false) == null)
373 DateTime createDate = DateTime.Now;
375 if (providerUserKey == null)
377 providerUserKey = Guid.NewGuid();
381 if (!(providerUserKey is Guid))
383 status = MembershipCreateStatus.InvalidProviderUserKey;
388 // Create user in database
389 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
391 using (SqliteCommand dbCommand = dbConn.CreateCommand())
393 dbCommand.CommandText = string.Format("INSERT INTO \"{0}\" (\"pId\", \"Username\", \"Password\", \"Email\", \"PasswordQuestion\", \"PasswordAnswer\", \"IsApproved\", \"CreationDate\", \"LastPasswordChangedDate\", \"LastActivityDate\", \"ApplicationName\", \"IsLockedOut\", \"LastLockedOutDate\", \"FailedPasswordAttemptCount\", \"FailedPasswordAttemptWindowStart\", \"FailedPasswordAnswerAttemptCount\", \"FailedPasswordAnswerAttemptWindowStart\") Values (@pId, @Username, @Password, @Email, @PasswordQuestion, @PasswordAnswer, @IsApproved, @CreationDate, @LastPasswordChangedDate, @LastActivityDate, @ApplicationName, @IsLockedOut, @LastLockedOutDate, @FailedPasswordAttemptCount, @FailedPasswordAttemptWindowStart, @FailedPasswordAnswerAttemptCount, @FailedPasswordAnswerAttemptWindowStart)", m_TableName);
395 AddParameter (dbCommand,"@pId", providerUserKey);
396 AddParameter (dbCommand,"@Username", username);
397 AddParameter (dbCommand,"@Password", EncodePassword(password));
398 AddParameter (dbCommand,"@Email", email);
399 AddParameter (dbCommand,"@PasswordQuestion", passwordQuestion);
400 AddParameter (dbCommand,"@PasswordAnswer", EncodePassword(passwordAnswer));
401 AddParameter (dbCommand,"@IsApproved", isApproved);
402 AddParameter (dbCommand,"@CreationDate", createDate);
403 AddParameter (dbCommand,"@LastPasswordChangedDate", createDate);
404 AddParameter (dbCommand,"@LastActivityDate", createDate);
405 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
406 AddParameter (dbCommand,"@IsLockedOut", false);
407 AddParameter (dbCommand,"@LastLockedOutDate", createDate);
408 AddParameter (dbCommand,"@FailedPasswordAttemptCount", 0);
409 AddParameter (dbCommand,"@FailedPasswordAttemptWindowStart", createDate);
410 AddParameter (dbCommand,"@FailedPasswordAnswerAttemptCount", 0);
411 AddParameter (dbCommand,"@FailedPasswordAnswerAttemptWindowStart", createDate);
418 if (dbCommand.ExecuteNonQuery() > 0)
420 status = MembershipCreateStatus.Success;
424 status = MembershipCreateStatus.UserRejected;
427 catch (SqliteException e)
429 status = MembershipCreateStatus.ProviderError;
430 Trace.WriteLine(e.ToString());
431 throw new ProviderException(Properties.Resources.ErrOperationAborted);
439 return GetUser(username, false);
445 status = MembershipCreateStatus.DuplicateUserName;
451 /// MembershipProvider.DeleteUser
453 public override bool DeleteUser(string username, bool deleteAllRelatedData)
455 int rowsAffected = 0;
457 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
459 using (SqliteCommand dbCommand = dbConn.CreateCommand())
461 dbCommand.CommandText = string.Format("DELETE FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
463 AddParameter (dbCommand,"@Username", username);
464 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
471 rowsAffected = dbCommand.ExecuteNonQuery();
473 if (deleteAllRelatedData)
475 // Process commands to delete all data for the user in the database.
478 catch (SqliteException e)
480 Trace.WriteLine(e.ToString());
481 throw new ProviderException(Properties.Resources.ErrOperationAborted);
491 if (rowsAffected > 0)
498 /// MembershipProvider.FindUsersByEmail
500 public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
503 MembershipUserCollection users = new MembershipUserCollection();
505 // replace permitted wildcard characters
506 emailToMatch = emailToMatch.Replace('*','%');
507 emailToMatch = emailToMatch.Replace('?', '_');
509 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
512 using (SqliteCommand dbCommand = dbConn.CreateCommand())
514 dbCommand.CommandText = string.Format("SELECT Count(*) FROM \"{0}\" WHERE \"Email\" LIKE @Email AND \"ApplicationName\" = @ApplicationName", m_TableName);
516 AddParameter (dbCommand,"@Email", emailToMatch);
517 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
524 Int32.TryParse(dbCommand.ExecuteScalar().ToString(), out totalRecords);
526 if (totalRecords <= 0) { return users; }
528 catch (SqliteException e)
530 Trace.WriteLine(e.ToString());
531 throw new ProviderException(Properties.Resources.ErrOperationAborted);
540 // Fetch user from database
541 using (SqliteCommand dbCommand = dbConn.CreateCommand())
543 dbCommand.CommandText = string.Format("SELECT \"pId\", \"Username\", \"Email\", \"PasswordQuestion\", \"Comment\", \"IsApproved\", \"IsLockedOut\", \"CreationDate\", \"LastLoginDate\", \"LastActivityDate\", \"LastPasswordChangedDate\", \"LastLockedOutDate\" FROM \"{0}\" WHERE \"Email\" LIKE @Email AND \"ApplicationName\" = @ApplicationName ORDER BY \"Username\" ASC LIMIT @MaxCount OFFSET @StartIndex", m_TableName);
545 AddParameter (dbCommand,"@Email", emailToMatch);
546 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
547 AddParameter (dbCommand,"@MaxCount", pageSize);
548 AddParameter (dbCommand,"@StartIndex", pageSize * pageIndex);
555 using (SqliteDataReader reader = dbCommand.ExecuteReader())
557 while (reader.Read())
559 MembershipUser u = GetUserFromReader(reader);
564 catch (SqliteException e)
566 Trace.WriteLine(e.ToString());
567 throw new ProviderException(Properties.Resources.ErrOperationAborted);
581 /// MembershipProvider.FindUsersByName
583 public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
586 MembershipUserCollection users = new MembershipUserCollection();
588 // replace permitted wildcard characters
589 usernameToMatch = usernameToMatch.Replace('*', '%');
590 usernameToMatch = usernameToMatch.Replace('?', '_');
592 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
595 using (SqliteCommand dbCommand = dbConn.CreateCommand())
597 dbCommand.CommandText = string.Format("SELECT Count(*) FROM \"{0}\" WHERE \"Username\" LIKE @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
599 AddParameter (dbCommand,"@Username", usernameToMatch);
600 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
607 Int32.TryParse(dbCommand.ExecuteScalar().ToString(), out totalRecords);
609 if (totalRecords <= 0) { return users; }
611 catch (SqliteException e)
613 Trace.WriteLine(e.ToString());
614 throw new ProviderException(Properties.Resources.ErrOperationAborted);
623 // Fetch user from database
624 using (SqliteCommand dbCommand = dbConn.CreateCommand())
626 dbCommand.CommandText = string.Format("SELECT \"pId\", \"Username\", \"Email\", \"PasswordQuestion\", \"Comment\", \"IsApproved\", \"IsLockedOut\", \"CreationDate\", \"LastLoginDate\", \"LastActivityDate\", \"LastPasswordChangedDate\", \"LastLockedOutDate\" FROM \"{0}\" WHERE \"Username\" LIKE @Username AND \"ApplicationName\" = @ApplicationName ORDER BY \"Username\" ASC LIMIT @MaxCount OFFSET @StartIndex", m_TableName);
628 AddParameter (dbCommand,"@Username", usernameToMatch);
629 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
630 AddParameter (dbCommand,"@MaxCount", pageSize);
631 AddParameter (dbCommand,"@StartIndex", pageSize * pageIndex);
638 using (SqliteDataReader reader = dbCommand.ExecuteReader())
640 while (reader.Read())
642 MembershipUser u = GetUserFromReader(reader);
647 catch (SqliteException e)
649 Trace.WriteLine(e.ToString());
650 throw new ProviderException(Properties.Resources.ErrOperationAborted);
664 /// MembershipProvider.GetAllUsers
666 public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
669 MembershipUserCollection users = new MembershipUserCollection();
671 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
674 using (SqliteCommand dbCommand = dbConn.CreateCommand())
676 dbCommand.CommandText = string.Format("SELECT Count(*) FROM \"{0}\" WHERE \"ApplicationName\" = @ApplicationName", m_TableName);
678 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
685 Int32.TryParse(dbCommand.ExecuteScalar().ToString(), out totalRecords);
687 if (totalRecords <= 0) { return users; }
689 catch (SqliteException e)
691 Trace.WriteLine(e.ToString());
701 // Fetch user from database
702 using (SqliteCommand dbCommand = dbConn.CreateCommand())
704 dbCommand.CommandText = string.Format("SELECT \"pId\", \"Username\", \"Email\", \"PasswordQuestion\", \"Comment\", \"IsApproved\", \"IsLockedOut\", \"CreationDate\", \"LastLoginDate\", \"LastActivityDate\", \"LastPasswordChangedDate\", \"LastLockedOutDate\" FROM \"{0}\" WHERE \"ApplicationName\" = @ApplicationName ORDER BY \"Username\" ASC LIMIT @MaxCount OFFSET @StartIndex", m_TableName);
706 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
707 AddParameter (dbCommand,"@MaxCount", pageSize);
708 AddParameter (dbCommand,"@StartIndex", pageSize * pageIndex);
715 using (SqliteDataReader reader = dbCommand.ExecuteReader())
717 while (reader.Read())
719 MembershipUser u = GetUserFromReader(reader);
724 catch (SqliteException e)
726 Trace.WriteLine(e.ToString());
727 throw new ProviderException(Properties.Resources.ErrOperationAborted);
741 /// MembershipProvider.GetNumberOfUsersOnline
743 public override int GetNumberOfUsersOnline()
747 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
749 using (SqliteCommand dbCommand = dbConn.CreateCommand())
751 TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0);
752 DateTime compareTime = DateTime.Now.Subtract(onlineSpan);
754 dbCommand.CommandText = string.Format("SELECT Count(*) FROM \"{0}\" WHERE \"LastActivityDate\" > @CompareTime AND \"ApplicationName\" = @ApplicationName", m_TableName);
756 AddParameter (dbCommand,"@CompareTime", compareTime);
757 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
764 numOnline = (int)dbCommand.ExecuteScalar();
766 catch (SqliteException e)
768 Trace.WriteLine(e.ToString());
769 throw new ProviderException(Properties.Resources.ErrOperationAborted);
783 /// MembershipProvider.GetPassword
785 public override string GetPassword(string username, string answer)
787 if (!EnablePasswordRetrieval)
789 throw new ProviderException(Properties.Resources.ErrPasswordRetrievalNotEnabled);
792 if (PasswordFormat == MembershipPasswordFormat.Hashed)
794 throw new ProviderException(Properties.Resources.ErrCantRetrieveHashedPw);
797 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
799 using (SqliteCommand dbCommand = dbConn.CreateCommand())
801 dbCommand.CommandText = string.Format("SELECT \"Password\", \"PasswordAnswer\", \"IsLockedOut\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
803 AddParameter (dbCommand,"@Username", username);
804 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
811 using (SqliteDataReader reader = dbCommand.ExecuteReader())
817 string password = reader.GetString(0);
818 string passwordAnswer = reader.GetString(1);
819 bool isLockedOut = reader.GetBoolean(2);
824 throw new MembershipPasswordException(Properties.Resources.ErrUserIsLoggedOut);
826 if (m_RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
828 UpdateFailureCount(username, FailureType.PasswordAnswer);
830 throw new MembershipPasswordException(Properties.Resources.ErrIncorrectPasswordAnswer);
833 if (m_PasswordFormat == MembershipPasswordFormat.Encrypted)
835 password = UnEncodePassword(password);
842 throw new MembershipPasswordException(Properties.Resources.ErrUserNotFound);
846 catch (SqliteException e)
848 Trace.WriteLine(e.ToString());
849 throw new ProviderException(Properties.Resources.ErrOperationAborted);
861 /// MembershipProvider.GetUser
863 public override MembershipUser GetUser(string username, bool userIsOnline)
865 MembershipUser u = null;
867 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
869 using (SqliteCommand dbCommand = dbConn.CreateCommand())
871 dbCommand.CommandText = string.Format("SELECT \"pId\", \"Username\", \"Email\", \"PasswordQuestion\", \"Comment\", \"IsApproved\", \"IsLockedOut\", \"CreationDate\", \"LastLoginDate\", \"LastActivityDate\", \"LastPasswordChangedDate\", \"LastLockedOutDate\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
873 AddParameter (dbCommand,"@Username", username);
874 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
881 using (SqliteDataReader reader = dbCommand.ExecuteReader())
886 u = GetUserFromReader(reader);
890 // Update user online status
891 using (SqliteCommand dbUpdateCommand = dbConn.CreateCommand())
893 dbUpdateCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"LastActivityDate\" = @LastActivityDate WHERE \"pId\" = @pId", m_TableName);
895 AddParameter (dbUpdateCommand, "@LastActivityDate", DateTime.Now);
896 AddParameter (dbUpdateCommand, "@pId", u.ProviderUserKey);
898 dbUpdateCommand.Prepare();
900 dbUpdateCommand.ExecuteNonQuery();
906 catch (SqliteException e)
908 Trace.WriteLine(e.ToString());
909 throw new ProviderException(Properties.Resources.ErrOperationAborted);
923 /// MembershipProvider.GetUser
925 public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
927 MembershipUser u = null;
929 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
931 using (SqliteCommand dbCommand = dbConn.CreateCommand())
933 dbCommand.CommandText = string.Format("SELECT \"pId\", \"Username\", \"Email\", \"PasswordQuestion\", \"Comment\", \"IsApproved\", \"IsLockedOut\", \"CreationDate\", \"LastLoginDate\", \"LastActivityDate\", \"LastPasswordChangedDate\", \"LastLockedOutDate\" FROM \"{0}\" WHERE \"pId\" = @pId", m_TableName);
935 AddParameter (dbCommand,"@pId", providerUserKey);
942 using (SqliteDataReader reader = dbCommand.ExecuteReader())
947 u = GetUserFromReader(reader);
951 // Update user online status
952 using (SqliteCommand dbUpdateCommand = dbConn.CreateCommand())
954 dbUpdateCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"LastActivityDate\" = @LastActivityDate WHERE \"pId\" = @pId", m_TableName);
956 AddParameter (dbUpdateCommand, "@LastActivityDate", DateTime.Now);
957 AddParameter (dbUpdateCommand, "@pId", u.ProviderUserKey);
959 dbUpdateCommand.Prepare();
961 dbUpdateCommand.ExecuteNonQuery();
967 catch (SqliteException e)
969 Trace.WriteLine(e.ToString());
970 throw new ProviderException(Properties.Resources.ErrOperationAborted);
984 /// MembershipProvider.GetUserNameByEmail
986 public override string GetUserNameByEmail(string email)
988 string username = string.Empty;
990 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
992 using (SqliteCommand dbCommand = dbConn.CreateCommand())
994 dbCommand.CommandText = string.Format("SELECT \"Username\" FROM \"{0}\" WHERE \"Email\" = @Email AND \"ApplicationName\" = @ApplicationName", m_TableName);
996 AddParameter (dbCommand,"@Email", email);
997 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1002 dbCommand.Prepare();
1004 username = (dbCommand.ExecuteScalar() as string) ?? string.Empty;
1006 catch (SqliteException e)
1008 Trace.WriteLine(e.ToString());
1009 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1023 /// MembershipProvider.ResetPassword
1025 public override string ResetPassword(string username, string answer)
1027 if (!m_EnablePasswordReset)
1029 throw new NotSupportedException(Properties.Resources.ErrPasswordResetNotEnabled);
1032 if (string.IsNullOrEmpty(answer) && m_RequiresQuestionAndAnswer)
1034 UpdateFailureCount(username, FailureType.PasswordAnswer);
1036 throw new ProviderException(Properties.Resources.ErrPasswordAnswerRequired);
1039 string newPassword = Membership.GeneratePassword(m_NewPasswordLength, m_MinRequiredNonAlphanumericCharacters);
1042 ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);
1044 OnValidatingPassword(args);
1048 if (args.FailureInformation != null)
1049 throw args.FailureInformation;
1051 throw new MembershipPasswordException(Properties.Resources.ErrPasswordResetCanceled);
1054 int rowsAffected = 0;
1056 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
1058 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1060 dbCommand.CommandText = string.Format("SELECT \"PasswordAnswer\", \"IsLockedOut\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1062 AddParameter (dbCommand,"@Username", username);
1063 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1067 string passwordAnswer = string.Empty;
1070 dbCommand.Prepare();
1072 using (SqliteDataReader reader = dbCommand.ExecuteReader())
1078 passwordAnswer = reader.GetString(0);
1079 bool isLockedOut = reader.GetBoolean(1);
1084 throw new MembershipPasswordException(Properties.Resources.ErrUserIsLoggedOut);
1086 if (m_RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
1088 UpdateFailureCount(username, FailureType.PasswordAnswer);
1090 throw new MembershipPasswordException(Properties.Resources.ErrIncorrectPasswordAnswer);
1095 throw new MembershipPasswordException(Properties.Resources.ErrUserNotFound);
1100 using (SqliteCommand dbUpdateCommand = dbConn.CreateCommand())
1102 dbUpdateCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"Password\" = @Password, \"LastPasswordChangedDate\" = @LastPasswordChangedDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsLockedOut\" = @IsLockedOut", m_TableName);
1104 AddParameter (dbUpdateCommand, "@Password", EncodePassword(newPassword));
1105 AddParameter (dbUpdateCommand, "@LastPasswordChangedDate", DateTime.Now);
1106 AddParameter (dbUpdateCommand, "@Username", username);
1107 AddParameter (dbUpdateCommand, "@ApplicationName", m_ApplicationName);
1108 AddParameter (dbUpdateCommand, "@IsLockedOut", false);
1110 dbUpdateCommand.Prepare();
1112 rowsAffected = dbUpdateCommand.ExecuteNonQuery();
1116 catch (SqliteException e)
1118 Trace.WriteLine(e.ToString());
1119 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1129 if (rowsAffected > 0)
1133 throw new MembershipPasswordException(Properties.Resources.ErrPasswordResetAborted);
1137 /// MembershipProvider.UnlockUser
1139 public override bool UnlockUser(string userName)
1141 int rowsAffected = 0;
1143 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
1145 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1147 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"IsLockedOut\" = @IsLockedOut, \"LastLockedOutDate\" = @LastLockedOutDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1149 AddParameter (dbCommand,"@IsLockedOut", false);
1150 AddParameter (dbCommand,"@LastLockedOutDate", DateTime.Now);
1151 AddParameter (dbCommand,"@Username", userName);
1152 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1157 dbCommand.Prepare();
1159 rowsAffected = dbCommand.ExecuteNonQuery();
1161 catch (SqliteException e)
1163 Trace.WriteLine(e.ToString());
1164 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1174 if (rowsAffected > 0)
1182 /// MembershipProvider.UpdateUser
1184 public override void UpdateUser(MembershipUser user)
1186 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
1188 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1190 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"Email\" = @Email, \"Comment\" = @Comment, \"IsApproved\" = @IsApproved WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1192 AddParameter (dbCommand,"@Email", user.Email);
1193 AddParameter (dbCommand,"@Comment", user.Comment);
1194 AddParameter (dbCommand,"@IsApproved", user.IsApproved);
1195 AddParameter (dbCommand,"@Username", user.UserName);
1196 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1201 dbCommand.Prepare();
1203 dbCommand.ExecuteNonQuery();
1205 catch (SqliteException e)
1207 Trace.WriteLine(e.ToString());
1208 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1220 /// MembershipProvider.ValidateUser
1222 public override bool ValidateUser(string username, string password)
1224 string dbPassword = string.Empty;
1225 bool dbIsApproved = false;
1227 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
1229 // Fetch user data from database
1230 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1232 dbCommand.CommandText = string.Format("SELECT \"Password\", \"IsApproved\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName AND \"IsLockedOut\" = @IsLockedOut", m_TableName);
1234 AddParameter (dbCommand,"@Username", username);
1235 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1236 AddParameter (dbCommand,"@IsLockedOut", false);
1241 dbCommand.Prepare();
1243 using (SqliteDataReader reader = dbCommand.ExecuteReader())
1248 dbPassword = reader.GetString(0);
1249 dbIsApproved = reader.GetBoolean(1);
1257 catch (SqliteException e)
1259 Trace.WriteLine(e.ToString());
1260 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1269 if (CheckPassword(password, dbPassword))
1273 // Update last login date
1274 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1276 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"LastLoginDate\" = @LastLoginDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1278 AddParameter (dbCommand,"@LastLoginDate", DateTime.Now);
1279 AddParameter (dbCommand,"@Username", username);
1280 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1285 dbCommand.Prepare();
1287 dbCommand.ExecuteNonQuery();
1291 catch (SqliteException e)
1293 Trace.WriteLine(e.ToString());
1294 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1310 #region private methods
1312 /// A helper function to retrieve config values from the configuration file.
1314 /// <param name="configValue"></param>
1315 /// <param name="defaultValue"></param>
1316 /// <returns></returns>
1317 string GetConfigValue(string configValue, string defaultValue)
1319 if (string.IsNullOrEmpty(configValue))
1320 return defaultValue;
1326 /// A helper function that takes the current row from the SqliteDataReader
1327 /// and hydrates a MembershipUser from the values. Called by the
1328 /// MembershipUser.GetUser implementation.
1330 /// <param name="reader">SqliteDataReader object</param>
1331 /// <returns>MembershipUser object</returns>
1332 MembershipUser GetUserFromReader(SqliteDataReader reader)
1334 object providerUserKey = reader.GetValue(0);
1335 string username = reader.GetString(1);
1336 string email = string.Empty;
1337 if (!reader.IsDBNull(2))
1338 email = reader.GetString(2);
1340 string passwordQuestion = string.Empty;
1341 if (!reader.IsDBNull(3))
1342 passwordQuestion = reader.GetString(3);
1344 string comment = string.Empty;
1345 if (!reader.IsDBNull(4))
1346 comment = reader.GetString(4);
1348 bool isApproved = reader.GetBoolean(5);
1349 bool isLockedOut = reader.GetBoolean(6);
1350 DateTime creationDate = reader.GetDateTime(7);
1352 DateTime lastLoginDate = new DateTime();
1353 if (!reader.IsDBNull(8))
1354 lastLoginDate = reader.GetDateTime(8);
1356 DateTime lastActivityDate = reader.GetDateTime(9);
1357 DateTime lastPasswordChangedDate = reader.GetDateTime(10);
1359 DateTime lastLockedOutDate = new DateTime();
1360 if (!reader.IsDBNull(11))
1361 lastLockedOutDate = reader.GetDateTime(11);
1363 MembershipUser u = new MembershipUser(this.Name,
1374 lastPasswordChangedDate,
1381 /// Compares password values based on the MembershipPasswordFormat.
1383 /// <param name="password"></param>
1384 /// <param name="dbpassword"></param>
1385 /// <returns></returns>
1386 bool CheckPassword(string password, string dbpassword)
1388 string pass1 = password;
1389 string pass2 = dbpassword;
1391 switch (PasswordFormat)
1393 case MembershipPasswordFormat.Encrypted:
1394 pass2 = UnEncodePassword(dbpassword);
1397 case MembershipPasswordFormat.Hashed:
1398 pass1 = EncodePassword(password);
1405 if (pass1.Equals(pass2))
1412 /// Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
1414 /// <param name="password"></param>
1415 /// <returns></returns>
1416 string EncodePassword(string password)
1418 if (string.IsNullOrEmpty(password))
1421 string encodedPassword = password;
1423 switch (PasswordFormat)
1425 case MembershipPasswordFormat.Clear:
1428 case MembershipPasswordFormat.Encrypted:
1429 encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
1432 case MembershipPasswordFormat.Hashed:
1433 HMACSHA1 hash = new HMACSHA1();
1434 if (machineKeyIsAutoGenerated)
1435 hash.Key = MachineKeySection.Config.GetValidationKey ();
1437 hash.Key = HexToByte(m_MachineKey.ValidationKey);
1438 encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
1442 throw new ProviderException(Properties.Resources.ErrPwFormatNotSupported);
1445 return encodedPassword;
1449 /// Decrypts or leaves the password clear based on the PasswordFormat.
1451 /// <param name="encodedPassword"></param>
1452 /// <returns></returns>
1453 string UnEncodePassword(string encodedPassword)
1455 string password = encodedPassword;
1457 switch (PasswordFormat)
1459 case MembershipPasswordFormat.Clear:
1462 case MembershipPasswordFormat.Encrypted:
1463 password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
1466 case MembershipPasswordFormat.Hashed:
1467 throw new ProviderException(Properties.Resources.ErrCantDecodeHashedPw);
1470 throw new ProviderException(Properties.Resources.ErrPwFormatNotSupported);
1477 /// Converts a hexadecimal string to a byte array. Used to convert encryption
1478 /// key values from the configuration.
1480 /// <param name="hexString"></param>
1481 /// <returns></returns>
1482 byte[] HexToByte(string hexString)
1484 byte[] returnBytes = new byte[hexString.Length / 2];
1485 for (int i = 0; i < returnBytes.Length; i++)
1486 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
1492 /// A helper method that performs the checks and updates associated with
1493 /// password failure tracking.
1495 /// <param name="username"></param>
1496 /// <param name="failType"></param>
1497 void UpdateFailureCount(string username, FailureType failType)
1499 DateTime windowStart = new DateTime();
1500 int failureCount = 0;
1502 using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
1504 // Fetch user data from database
1505 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1507 dbCommand.CommandText = string.Format("SELECT \"FailedPasswordAttemptCount\", \"FailedPasswordAttemptWindowStart\", \"FailedPasswordAnswerAttemptCount\", \"FailedPasswordAnswerAttemptWindowStart\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1509 AddParameter (dbCommand,"@Username", username);
1510 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1515 dbCommand.Prepare();
1517 using (SqliteDataReader reader = dbCommand.ExecuteReader())
1523 if (failType.Equals(FailureType.Password))
1525 failureCount = reader.GetInt32(0);
1526 windowStart = reader.GetDateTime(1);
1528 else if (failType.Equals(FailureType.PasswordAnswer))
1530 failureCount = reader.GetInt32(2);
1531 windowStart = reader.GetDateTime(3);
1536 catch (SqliteException e)
1538 Trace.WriteLine(e.ToString());
1539 throw new ProviderException(Properties.Resources.ErrOperationAborted);
1548 // Calculate failture count and update database
1549 using (SqliteCommand dbCommand = dbConn.CreateCommand())
1551 DateTime windowEnd = windowStart.AddMinutes(m_PasswordAttemptWindow);
1555 if (failureCount == 0 || DateTime.Now > windowEnd)
1557 // First password failure or outside of PasswordAttemptWindow.
1558 // Start a new password failure count from 1 and a new window starting now.
1560 if (failType.Equals(FailureType.Password))
1562 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAttemptCount\" = @Count, \"FailedPasswordAttemptWindowStart\" = @WindowStart WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1564 else if (failType.Equals(FailureType.PasswordAnswer))
1566 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAnswerAttemptCount\" = @Count, \"FailedPasswordAnswerAttemptWindowStart\" = @WindowStart WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1569 AddParameter (dbCommand,"@Count", 1);
1570 AddParameter (dbCommand,"@WindowStart", DateTime.Now);
1571 AddParameter (dbCommand,"@Username", username);
1572 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1574 if (dbCommand.ExecuteNonQuery() < 0)
1575 throw new ProviderException(Properties.Resources.ErrCantUpdateFailtureCountAndWindowStart);
1581 if (failureCount >= m_MaxInvalidPasswordAttempts)
1583 // Password attempts have exceeded the failure threshold. Lock out
1585 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"IsLockedOut\" = @IsLockedOut, \"LastLockedOutDate\" = @LastLockedOutDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1587 AddParameter (dbCommand,"@IsLockedOut", true);
1588 AddParameter (dbCommand,"@LastLockedOutDate", DateTime.Now);
1589 AddParameter (dbCommand,"@Username", username);
1590 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1592 if (dbCommand.ExecuteNonQuery() < 0)
1593 throw new ProviderException(string.Format(Properties.Resources.ErrCantLogoutUser, username));
1597 // Password attempts have not exceeded the failure threshold. Update
1598 // the failure counts. Leave the window the same.
1599 if (failType.Equals(FailureType.Password))
1601 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAttemptCount\" = @Count WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1603 else if (failType.Equals(FailureType.PasswordAnswer))
1605 dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAnswerAttemptCount\" = @Count WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
1608 AddParameter (dbCommand,"@Count", failureCount);
1609 AddParameter (dbCommand,"@Username", username);
1610 AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);
1612 if (dbCommand.ExecuteNonQuery() < 0)
1613 throw new ProviderException(Properties.Resources.ErrCantUpdateFailtureCount);
1617 catch (SqliteException e)
1619 Trace.WriteLine(e.ToString());
1620 throw new ProviderException(Properties.Resources.ErrOperationAborted);