SqlMembershipProvider.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. //
  2. // System.Web.Security.SqlMembershipProvider
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. // Lluis Sanchez Gual ([email protected])
  7. // Chris Toshok ([email protected])
  8. //
  9. // (C) 2003 Ben Maurer
  10. // Copyright (c) 2005,2006 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. #if NET_2_0
  32. using System.Collections;
  33. using System.Collections.Specialized;
  34. using System.Configuration;
  35. using System.Configuration.Provider;
  36. using System.Data;
  37. using System.Data.Common;
  38. using System.Text;
  39. using System.Web.Configuration;
  40. using System.Security.Cryptography;
  41. namespace System.Web.Security {
  42. public class SqlMembershipProvider : MembershipProvider {
  43. const int SALT_BYTES = 16;
  44. /* can this be done just by setting the datetime fields to 0? */
  45. DateTime DefaultDateTime = new DateTime (1754,1,1).ToUniversalTime();
  46. bool enablePasswordReset;
  47. bool enablePasswordRetrieval;
  48. int maxInvalidPasswordAttempts;
  49. MembershipPasswordFormat passwordFormat;
  50. bool requiresQuestionAndAnswer;
  51. bool requiresUniqueEmail;
  52. int minRequiredNonAlphanumericCharacters;
  53. int minRequiredPasswordLength;
  54. int passwordAttemptWindow;
  55. string passwordStrengthRegularExpression;
  56. TimeSpan userIsOnlineTimeWindow;
  57. ConnectionStringSettings connectionString;
  58. DbProviderFactory factory;
  59. DbConnection connection;
  60. string applicationName;
  61. static object lockobj = new object();
  62. void InitConnection ()
  63. {
  64. if (connection == null) {
  65. lock (lockobj) {
  66. if (connection != null)
  67. return;
  68. factory = ProvidersHelper.GetDbProviderFactory (connectionString.ProviderName);
  69. connection = factory.CreateConnection();
  70. connection.ConnectionString = connectionString.ConnectionString;
  71. connection.Open ();
  72. }
  73. }
  74. }
  75. void AddParameter (DbCommand command, string parameterName, string parameterValue)
  76. {
  77. DbParameter dbp = command.CreateParameter ();
  78. dbp.ParameterName = parameterName;
  79. dbp.Value = parameterValue;
  80. dbp.Direction = ParameterDirection.Input;
  81. command.Parameters.Add (dbp);
  82. }
  83. void CheckParam (string pName, string p, int length)
  84. {
  85. if (p == null)
  86. throw new ArgumentNullException (pName);
  87. if (p.Length == 0 || p.Length > length || p.IndexOf (",") != -1)
  88. throw new ArgumentException (String.Format ("invalid format for {0}", pName));
  89. }
  90. SymmetricAlgorithm GetAlg (out byte[] decryptionKey)
  91. {
  92. MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection ("system.web/machineKey");
  93. if (section.DecryptionKey.StartsWith ("AutoGenerate"))
  94. throw new ProviderException ("You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords.");
  95. string alg_type = section.Decryption;
  96. if (alg_type == "Auto")
  97. alg_type = "AES";
  98. SymmetricAlgorithm alg = null;
  99. if (alg_type == "AES")
  100. alg = Rijndael.Create ();
  101. else if (alg_type == "3DES")
  102. alg = TripleDES.Create ();
  103. else
  104. throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", alg_type));
  105. decryptionKey = section.DecryptionKey192Bits;
  106. return alg;
  107. }
  108. protected override byte[] DecryptPassword (byte[] encodedPassword)
  109. {
  110. byte[] decryptionKey;
  111. using (SymmetricAlgorithm alg = GetAlg (out decryptionKey)) {
  112. alg.Key = decryptionKey;
  113. using (ICryptoTransform decryptor = alg.CreateDecryptor ()) {
  114. byte[] buf = decryptor.TransformFinalBlock (encodedPassword, 0, encodedPassword.Length);
  115. byte[] rv = new byte[buf.Length - SALT_BYTES];
  116. Array.Copy (buf, 16, rv, 0, buf.Length - 16);
  117. return rv;
  118. }
  119. }
  120. }
  121. protected override byte[] EncryptPassword (byte[] password)
  122. {
  123. byte[] decryptionKey;
  124. byte[] iv = new byte[SALT_BYTES];
  125. Array.Copy (password, 0, iv, 0, SALT_BYTES);
  126. Array.Clear (password, 0, SALT_BYTES);
  127. using (SymmetricAlgorithm alg = GetAlg (out decryptionKey)) {
  128. using (ICryptoTransform encryptor = alg.CreateEncryptor (decryptionKey, iv)) {
  129. return encryptor.TransformFinalBlock (password, 0, password.Length);
  130. }
  131. }
  132. }
  133. public override bool ChangePassword (string username, string oldPwd, string newPwd)
  134. {
  135. if (username != null) username = username.Trim ();
  136. if (oldPwd != null) oldPwd = oldPwd.Trim ();
  137. if (newPwd != null) newPwd = newPwd.Trim ();
  138. CheckParam ("username", username, 256);
  139. CheckParam ("oldPwd", oldPwd, 128);
  140. CheckParam ("newPwd", newPwd, 128);
  141. MembershipUser user = GetUser (username, false);
  142. if (user == null) throw new ProviderException ("could not find user in membership database");
  143. if (user.IsLockedOut) throw new MembershipPasswordException ("user is currently locked out");
  144. InitConnection();
  145. DbTransaction trans = connection.BeginTransaction ();
  146. string commandText;
  147. DbCommand command;
  148. try {
  149. MembershipPasswordFormat passwordFormat;
  150. string db_salt;
  151. bool valid = ValidateUsingPassword (trans, username, oldPwd, out passwordFormat, out db_salt);
  152. if (valid) {
  153. EmitValidatingPassword (username, newPwd, false);
  154. string db_password = EncodePassword (newPwd, passwordFormat, db_salt);
  155. DateTime now = DateTime.Now.ToUniversalTime ();
  156. commandText = @"
  157. UPDATE m
  158. SET Password = @Password,
  159. FailedPasswordAttemptCount = 0,
  160. FailedPasswordAttemptWindowStart = @DefaultDateTime,
  161. LastPasswordChangedDate = @Now
  162. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  163. WHERE m.ApplicationId = a.ApplicationId
  164. AND u.ApplicationId = a.ApplicationId
  165. AND m.UserId = u.UserId
  166. AND u.LoweredUserName = LOWER(@UserName)
  167. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  168. command = factory.CreateCommand ();
  169. command.Transaction = trans;
  170. command.CommandText = commandText;
  171. command.Connection = connection;
  172. command.CommandType = CommandType.Text;
  173. AddParameter (command, "UserName", user.UserName);
  174. AddParameter (command, "Now", now.ToString ());
  175. AddParameter (command, "Password", db_password);
  176. AddParameter (command, "ApplicationName", ApplicationName);
  177. AddParameter (command, "DefaultDateTime", DefaultDateTime.ToString());
  178. if (1 != (int)command.ExecuteNonQuery ())
  179. throw new ProviderException ("failed to update Membership table");
  180. }
  181. trans.Commit ();
  182. return valid;
  183. }
  184. catch (ProviderException) {
  185. trans.Rollback ();
  186. throw;
  187. }
  188. catch (Exception e) {
  189. trans.Rollback ();
  190. throw new ProviderException ("error changing password", e);
  191. }
  192. }
  193. public override bool ChangePasswordQuestionAndAnswer (string username, string password, string newPwdQuestion, string newPwdAnswer)
  194. {
  195. if (username != null) username = username.Trim ();
  196. if (newPwdQuestion != null) newPwdQuestion = newPwdQuestion.Trim ();
  197. if (newPwdAnswer != null) newPwdAnswer = newPwdAnswer.Trim ();
  198. CheckParam ("username", username, 256);
  199. if (RequiresQuestionAndAnswer)
  200. CheckParam ("newPwdQuestion", newPwdQuestion, 128);
  201. if (RequiresQuestionAndAnswer)
  202. CheckParam ("newPwdAnswer", newPwdAnswer, 128);
  203. MembershipUser user = GetUser (username, false);
  204. if (user == null) throw new ProviderException ("could not find user in membership database");
  205. if (user.IsLockedOut) throw new MembershipPasswordException ("user is currently locked out");
  206. InitConnection();
  207. DbTransaction trans = connection.BeginTransaction ();
  208. string commandText;
  209. DbCommand command;
  210. try {
  211. MembershipPasswordFormat passwordFormat;
  212. string db_salt;
  213. bool valid = ValidateUsingPassword (trans, username, password, out passwordFormat, out db_salt);
  214. if (valid) {
  215. string db_passwordAnswer = EncodePassword (newPwdAnswer, passwordFormat, db_salt);
  216. commandText = @"
  217. UPDATE m
  218. SET PasswordQuestion = @PasswordQuestion,
  219. PasswordAnswer = @PasswordAnswer,
  220. FailedPasswordAttemptCount = 0,
  221. FailedPasswordAttemptWindowStart = @DefaultDateTime,
  222. FailedPasswordAnswerAttemptCount = 0,
  223. FailedPasswordAnswerAttemptWindowStart = @DefaultDateTime
  224. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  225. WHERE m.ApplicationId = a.ApplicationId
  226. AND u.ApplicationId = a.ApplicationId
  227. AND m.UserId = u.UserId
  228. AND u.LoweredUserName = LOWER(@UserName)
  229. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  230. command = factory.CreateCommand ();
  231. command.Transaction = trans;
  232. command.CommandText = commandText;
  233. command.Connection = connection;
  234. command.CommandType = CommandType.Text;
  235. AddParameter (command, "UserName", user.UserName);
  236. AddParameter (command, "PasswordQuestion", newPwdQuestion);
  237. AddParameter (command, "PasswordAnswer", db_passwordAnswer);
  238. AddParameter (command, "ApplicationName", ApplicationName);
  239. AddParameter (command, "DefaultDateTime", DefaultDateTime.ToString());
  240. if (1 != (int)command.ExecuteNonQuery ())
  241. throw new ProviderException ("failed to update Membership table");
  242. }
  243. trans.Commit ();
  244. return valid;
  245. }
  246. catch (ProviderException) {
  247. trans.Rollback ();
  248. throw;
  249. }
  250. catch (Exception e) {
  251. trans.Rollback ();
  252. throw new ProviderException ("error changing password question and answer", e);
  253. }
  254. }
  255. public override MembershipUser CreateUser (string username,
  256. string password,
  257. string email,
  258. string pwdQuestion,
  259. string pwdAnswer,
  260. bool isApproved,
  261. object providerUserKey,
  262. out MembershipCreateStatus status)
  263. {
  264. if (username != null) username = username.Trim ();
  265. if (password != null) password = password.Trim ();
  266. if (email != null) email = email.Trim ();
  267. if (pwdQuestion != null) pwdQuestion = pwdQuestion.Trim ();
  268. if (pwdAnswer != null) pwdAnswer = pwdAnswer.Trim ();
  269. /* some initial validation */
  270. if (username == null || username.Length == 0 || username.Length > 256 || username.IndexOf (",") != -1) {
  271. status = MembershipCreateStatus.InvalidUserName;
  272. return null;
  273. }
  274. if (password == null || password.Length == 0 || password.Length > 128) {
  275. status = MembershipCreateStatus.InvalidPassword;
  276. return null;
  277. }
  278. if (RequiresUniqueEmail && (email == null || email.Length == 0)) {
  279. status = MembershipCreateStatus.InvalidEmail;
  280. return null;
  281. }
  282. if (RequiresQuestionAndAnswer &&
  283. (pwdQuestion == null ||
  284. pwdQuestion.Length == 0 || pwdQuestion.Length > 256)) {
  285. status = MembershipCreateStatus.InvalidQuestion;
  286. return null;
  287. }
  288. if (RequiresQuestionAndAnswer &&
  289. (pwdAnswer == null ||
  290. pwdAnswer.Length == 0 || pwdAnswer.Length > 128)) {
  291. status = MembershipCreateStatus.InvalidAnswer;
  292. return null;
  293. }
  294. if (providerUserKey != null && ! (providerUserKey is Guid)) {
  295. status = MembershipCreateStatus.InvalidProviderUserKey;
  296. return null;
  297. }
  298. /* encode our password/answer using the
  299. * "passwordFormat" configuration option */
  300. string passwordSalt = "";
  301. RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  302. byte[] salt = new byte[SALT_BYTES];
  303. rng.GetBytes (salt);
  304. passwordSalt = Convert.ToBase64String (salt);
  305. password = EncodePassword (password, PasswordFormat, passwordSalt);
  306. if (RequiresQuestionAndAnswer)
  307. pwdAnswer = EncodePassword (pwdAnswer, PasswordFormat, passwordSalt);
  308. /* make sure the hashed/encrypted password and
  309. * answer are still under 128 characters. */
  310. if (password.Length > 128) {
  311. status = MembershipCreateStatus.InvalidPassword;
  312. return null;
  313. }
  314. if (RequiresQuestionAndAnswer) {
  315. if (pwdAnswer.Length > 128) {
  316. status = MembershipCreateStatus.InvalidAnswer;
  317. return null;
  318. }
  319. }
  320. InitConnection();
  321. DbTransaction trans = connection.BeginTransaction ();
  322. string commandText;
  323. DbCommand command;
  324. try {
  325. Guid applicationId;
  326. Guid userId;
  327. /* get the application id since it seems that inside transactions we
  328. can't insert using subqueries.. */
  329. commandText = @"
  330. SELECT ApplicationId
  331. FROM dbo.aspnet_Applications
  332. WHERE dbo.aspnet_Applications.LoweredApplicationName = LOWER(@ApplicationName)
  333. ";
  334. command = factory.CreateCommand ();
  335. command.Transaction = trans;
  336. command.CommandText = commandText;
  337. command.Connection = connection;
  338. command.CommandType = CommandType.Text;
  339. AddParameter (command, "ApplicationName", ApplicationName);
  340. DbDataReader reader = command.ExecuteReader ();
  341. reader.Read ();
  342. applicationId = reader.GetGuid (0);
  343. reader.Close ();
  344. /* check for unique username, email and
  345. * provider user key, if applicable */
  346. commandText = @"
  347. SELECT COUNT(*)
  348. FROM dbo.aspnet_Users u, dbo.aspnet_Applications a
  349. WHERE u.LoweredUserName = LOWER(@UserName)
  350. AND u.ApplicationId = a.ApplicationId
  351. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  352. command = factory.CreateCommand ();
  353. command.Transaction = trans;
  354. command.CommandText = commandText;
  355. command.Connection = connection;
  356. command.CommandType = CommandType.Text;
  357. AddParameter (command, "UserName", username);
  358. AddParameter (command, "ApplicationName", ApplicationName);
  359. if (0 != (int)command.ExecuteScalar()) {
  360. status = MembershipCreateStatus.DuplicateUserName;
  361. trans.Rollback ();
  362. return null;
  363. }
  364. if (requiresUniqueEmail) {
  365. commandText = @"
  366. SELECT COUNT(*)
  367. FROM dbo.aspnet_Membership, dbo.aspnet_Applications
  368. WHERE dbo.aspnet_Membership.Email = @Email
  369. AND dbo.aspnet_Membership.ApplicationId = dbo.aspnet_Applications.ApplicationId
  370. AND dbo.aspnet_Applications.LoweredApplicationName = LOWER(@ApplicationName)";
  371. command = factory.CreateCommand ();
  372. command.Transaction = trans;
  373. command.CommandText = commandText;
  374. command.Connection = connection;
  375. command.CommandType = CommandType.Text;
  376. AddParameter (command, "Email", email);
  377. AddParameter (command, "ApplicationName", ApplicationName);
  378. if (0 != (int)command.ExecuteScalar()) {
  379. status = MembershipCreateStatus.DuplicateEmail;
  380. trans.Rollback ();
  381. return null;
  382. }
  383. }
  384. if (providerUserKey != null) {
  385. commandText = @"
  386. SELECT COUNT(*)
  387. FROM dbo.aspnet_Membership, dbo.aspnet_Applications
  388. WHERE dbo.aspnet_Membership.UserId = @ProviderUserKey
  389. AND dbo.aspnet_Membership.ApplicationId = dbo.aspnet_Applications.ApplicationId
  390. AND dbo.aspnet_Applications.LoweredApplicationName = LOWER(@ApplicationName)";
  391. command = factory.CreateCommand ();
  392. command.Transaction = trans;
  393. command.CommandText = commandText;
  394. command.Connection = connection;
  395. command.CommandType = CommandType.Text;
  396. AddParameter (command, "Email", email);
  397. AddParameter (command, "ApplicationName", ApplicationName);
  398. if (0 != (int)command.ExecuteScalar()) {
  399. status = MembershipCreateStatus.DuplicateProviderUserKey;
  400. trans.Rollback ();
  401. return null;
  402. }
  403. }
  404. /* first into the Users table */
  405. commandText = @"
  406. INSERT into dbo.aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, LastActivityDate)
  407. VALUES (@ApplicationId, NEWID(), @UserName, LOWER(@UserName), GETDATE())
  408. ";
  409. command = factory.CreateCommand ();
  410. command.Transaction = trans;
  411. command.CommandText = commandText;
  412. command.Connection = connection;
  413. command.CommandType = CommandType.Text;
  414. AddParameter (command, "UserName", username);
  415. AddParameter (command, "ApplicationId", applicationId.ToString());
  416. if (command.ExecuteNonQuery() != 1) {
  417. status = MembershipCreateStatus.UserRejected; /* XXX */
  418. trans.Rollback ();
  419. return null;
  420. }
  421. /* then get the newly created userid */
  422. commandText = @"
  423. SELECT UserId
  424. FROM dbo.aspnet_Users
  425. WHERE dbo.aspnet_Users.LoweredUserName = LOWER(@UserName)
  426. ";
  427. command = factory.CreateCommand ();
  428. command.Transaction = trans;
  429. command.CommandText = commandText;
  430. command.Connection = connection;
  431. command.CommandType = CommandType.Text;
  432. AddParameter (command, "UserName", username);
  433. reader = command.ExecuteReader ();
  434. reader.Read ();
  435. userId = reader.GetGuid (0);
  436. reader.Close ();
  437. /* then insert into the Membership table */
  438. commandText = String.Format (@"
  439. INSERT into dbo.aspnet_Membership
  440. VALUES (@ApplicationId,
  441. @UserId,
  442. @Password, @PasswordFormat, @PasswordSalt,
  443. NULL,
  444. {0}, {1},
  445. {2}, {3},
  446. 0, 0,
  447. GETDATE(), GETDATE(), @DefaultDateTime,
  448. @DefaultDateTime,
  449. 0, @DefaultDateTime, 0, @DefaultDateTime, NULL)",
  450. email == null ? "NULL" : "@Email",
  451. email == null ? "NULL" : "LOWER(@Email)",
  452. pwdQuestion == null ? "NULL" : "@PasswordQuestion",
  453. pwdAnswer == null ? "NULL" : "@PasswordAnswer");
  454. command = factory.CreateCommand ();
  455. command.Transaction = trans;
  456. command.CommandText = commandText;
  457. command.Connection = connection;
  458. command.CommandType = CommandType.Text;
  459. AddParameter (command, "ApplicationId", applicationId.ToString());
  460. AddParameter (command, "UserId", userId.ToString());
  461. if (email != null)
  462. AddParameter (command, "Email", email);
  463. AddParameter (command, "Password", password);
  464. AddParameter (command, "PasswordFormat", ((int)PasswordFormat).ToString());
  465. AddParameter (command, "PasswordSalt", passwordSalt);
  466. if (pwdQuestion != null)
  467. AddParameter (command, "PasswordQuestion", pwdQuestion);
  468. if (pwdAnswer != null)
  469. AddParameter (command, "PasswordAnswer", pwdAnswer);
  470. AddParameter (command, "DefaultDateTime", DefaultDateTime.ToString());
  471. if (command.ExecuteNonQuery() != 1) {
  472. status = MembershipCreateStatus.UserRejected; /* XXX */
  473. return null;
  474. }
  475. trans.Commit ();
  476. status = MembershipCreateStatus.Success;
  477. return GetUser (username, false);
  478. }
  479. catch {
  480. status = MembershipCreateStatus.ProviderError;
  481. trans.Rollback ();
  482. return null;
  483. }
  484. }
  485. [MonoTODO]
  486. public override bool DeleteUser (string username, bool deleteAllRelatedData)
  487. {
  488. CheckParam ("username", username, 256);
  489. if (deleteAllRelatedData) {
  490. /* delete everything from the
  491. * following features as well:
  492. *
  493. * Roles
  494. * Profile
  495. * WebParts Personalization
  496. */
  497. }
  498. DbTransaction trans = connection.BeginTransaction ();
  499. DbCommand command;
  500. string commandText;
  501. InitConnection();
  502. try {
  503. /* delete from the Membership table */
  504. commandText = @"
  505. DELETE dbo.aspnet_Membership
  506. FROM dbo.aspnet_Membership, dbo.aspnet_Users, dbo.aspnet_Applications
  507. WHERE dbo.aspnet_Membership.UserId = dbo.aspnet_Users.UserId
  508. AND dbo.aspnet_Membership.ApplicationId = dbo.aspnet_Applications.ApplicationId
  509. AND dbo.aspnet_Users.LoweredUserName = LOWER (@UserName)
  510. AND dbo.aspnet_Users.ApplicationId = dbo.aspnet_Applications.ApplicationId
  511. AND dbo.aspnet_Applications.LoweredApplicationName = LOWER(@ApplicationName)";
  512. command = factory.CreateCommand ();
  513. command.Transaction = trans;
  514. command.CommandText = commandText;
  515. command.Connection = connection;
  516. command.CommandType = CommandType.Text;
  517. AddParameter (command, "UserName", username);
  518. AddParameter (command, "ApplicationName", ApplicationName);
  519. if (1 != command.ExecuteNonQuery())
  520. throw new ProviderException ("failed to delete from Membership table");
  521. /* delete from the User table */
  522. commandText = @"
  523. DELETE dbo.aspnet_Users
  524. FROM dbo.aspnet_Users, dbo.aspnet_Applications
  525. WHERE dbo.aspnet_Users.LoweredUserName = LOWER (@UserName)
  526. AND dbo.aspnet_Users.ApplicationId = dbo.aspnet_Applications.ApplicationId
  527. AND dbo.aspnet_Applications.LoweredApplicationName = LOWER(@ApplicationName)";
  528. command = factory.CreateCommand ();
  529. command.Transaction = trans;
  530. command.CommandText = commandText;
  531. command.Connection = connection;
  532. command.CommandType = CommandType.Text;
  533. AddParameter (command, "UserName", username);
  534. AddParameter (command, "ApplicationName", ApplicationName);
  535. if (1 != command.ExecuteNonQuery())
  536. throw new ProviderException ("failed to delete from User table");
  537. trans.Commit ();
  538. return true;
  539. }
  540. catch {
  541. trans.Rollback ();
  542. return false;
  543. }
  544. }
  545. public virtual string GeneratePassword ()
  546. {
  547. return Membership.GeneratePassword (minRequiredPasswordLength, minRequiredNonAlphanumericCharacters);
  548. }
  549. public override MembershipUserCollection FindUsersByEmail (string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
  550. {
  551. CheckParam ("emailToMatch", emailToMatch, 256);
  552. if (pageIndex < 0)
  553. throw new ArgumentException ("pageIndex must be >= 0");
  554. if (pageSize < 0)
  555. throw new ArgumentException ("pageSize must be >= 0");
  556. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  557. throw new ArgumentException ("pageIndex and pageSize are too large");
  558. string commandText;
  559. InitConnection();
  560. commandText = @"
  561. SELECT u.UserName, m.UserId, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
  562. m.IsLockedOut, m.CreateDate, m.LastLoginDate, u.LastActivityDate,
  563. m.LastPasswordChangedDate, m.LastLockoutDate
  564. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  565. WHERE m.ApplicationId = a.ApplicationId
  566. AND u.ApplicationId = a.ApplicationId
  567. AND m.UserId = u.UserId
  568. AND m.Email LIKE @Email
  569. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  570. DbCommand command = factory.CreateCommand ();
  571. command.CommandText = commandText;
  572. command.Connection = connection;
  573. command.CommandType = CommandType.Text;
  574. AddParameter (command, "Email", emailToMatch);
  575. AddParameter (command, "ApplicationName", ApplicationName);
  576. MembershipUserCollection c = BuildMembershipUserCollection (command, pageIndex, pageSize, out totalRecords);
  577. return c;
  578. }
  579. public override MembershipUserCollection FindUsersByName (string nameToMatch, int pageIndex, int pageSize, out int totalRecords)
  580. {
  581. CheckParam ("nameToMatch", nameToMatch, 256);
  582. if (pageIndex < 0)
  583. throw new ArgumentException ("pageIndex must be >= 0");
  584. if (pageSize < 0)
  585. throw new ArgumentException ("pageSize must be >= 0");
  586. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  587. throw new ArgumentException ("pageIndex and pageSize are too large");
  588. string commandText;
  589. InitConnection();
  590. commandText = @"
  591. SELECT u.UserName, m.UserId, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
  592. m.IsLockedOut, m.CreateDate, m.LastLoginDate, u.LastActivityDate,
  593. m.LastPasswordChangedDate, m.LastLockoutDate
  594. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  595. WHERE m.ApplicationId = a.ApplicationId
  596. AND u.ApplicationId = a.ApplicationId
  597. AND m.UserId = u.UserId
  598. AND u.UserName LIKE @UserName
  599. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  600. DbCommand command = factory.CreateCommand ();
  601. command.CommandText = commandText;
  602. command.Connection = connection;
  603. command.CommandType = CommandType.Text;
  604. AddParameter (command, "UserName", nameToMatch);
  605. AddParameter (command, "ApplicationName", ApplicationName);
  606. MembershipUserCollection c = BuildMembershipUserCollection (command, pageIndex, pageSize, out totalRecords);
  607. return c;
  608. }
  609. public override MembershipUserCollection GetAllUsers (int pageIndex, int pageSize, out int totalRecords)
  610. {
  611. if (pageIndex < 0)
  612. throw new ArgumentException ("pageIndex must be >= 0");
  613. if (pageSize < 0)
  614. throw new ArgumentException ("pageSize must be >= 0");
  615. if (pageIndex * pageSize + pageSize - 1 > Int32.MaxValue)
  616. throw new ArgumentException ("pageIndex and pageSize are too large");
  617. string commandText;
  618. InitConnection();
  619. commandText = @"
  620. SELECT u.UserName, m.UserId, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
  621. m.IsLockedOut, m.CreateDate, m.LastLoginDate, u.LastActivityDate,
  622. m.LastPasswordChangedDate, m.LastLockoutDate
  623. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  624. WHERE m.ApplicationId = a.ApplicationId
  625. AND u.ApplicationId = a.ApplicationId
  626. AND m.UserId = u.UserId
  627. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  628. DbCommand command = factory.CreateCommand ();
  629. command.CommandText = commandText;
  630. command.Connection = connection;
  631. command.CommandType = CommandType.Text;
  632. AddParameter (command, "ApplicationName", ApplicationName);
  633. MembershipUserCollection c = BuildMembershipUserCollection (command, pageIndex, pageSize, out totalRecords);
  634. return c;
  635. }
  636. MembershipUserCollection BuildMembershipUserCollection (DbCommand command, int pageIndex, int pageSize, out int totalRecords)
  637. {
  638. DbDataReader reader = null;
  639. try {
  640. int num_read = 0;
  641. int num_added = 0;
  642. int num_to_skip = pageIndex * pageSize;
  643. MembershipUserCollection users = new MembershipUserCollection ();
  644. reader = command.ExecuteReader ();
  645. while (reader.Read()) {
  646. if (num_read >= num_to_skip) {
  647. if (num_added < pageSize) {
  648. users.Add (GetUserFromReader (reader));
  649. num_added ++;
  650. }
  651. num_read ++;
  652. }
  653. }
  654. totalRecords = num_read;
  655. return users;
  656. }
  657. catch {
  658. totalRecords = 0;
  659. return null; /* should we let the exception through? */
  660. }
  661. finally {
  662. if (reader != null)
  663. reader.Close();
  664. }
  665. }
  666. public override int GetNumberOfUsersOnline ()
  667. {
  668. string commandText;
  669. InitConnection();
  670. DateTime now = DateTime.Now.ToUniversalTime ();
  671. commandText = String.Format (@"
  672. SELECT COUNT (*)
  673. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  674. WHERE m.ApplicationId = a.ApplicationId
  675. AND u.ApplicationId = a.ApplicationId
  676. AND m.UserId = u.UserId
  677. AND DATEADD(minute,{0},u.LastActivityDate) >= @Now
  678. AND a.LoweredApplicationName = LOWER(@ApplicationName)",
  679. userIsOnlineTimeWindow.Minutes);
  680. DbCommand command = factory.CreateCommand ();
  681. command.CommandText = commandText;
  682. command.Connection = connection;
  683. command.CommandType = CommandType.Text;
  684. AddParameter (command, "Now", now.ToString ());
  685. AddParameter (command, "ApplicationName", ApplicationName);
  686. return (int)command.ExecuteScalar ();
  687. }
  688. public override string GetPassword (string username, string answer)
  689. {
  690. if (!enablePasswordRetrieval)
  691. throw new NotSupportedException ("this provider has not been configured to allow the retrieval of passwords");
  692. CheckParam ("username", username, 256);
  693. if (RequiresQuestionAndAnswer)
  694. CheckParam ("answer", answer, 128);
  695. MembershipUser user = GetUser (username, false);
  696. if (user == null) throw new ProviderException ("could not find user in membership database");
  697. if (user.IsLockedOut) throw new MembershipPasswordException ("user is currently locked out");
  698. InitConnection();
  699. DbTransaction trans = connection.BeginTransaction ();
  700. try {
  701. MembershipPasswordFormat passwordFormat;
  702. string salt;
  703. string password = null;
  704. if (ValidateUsingPasswordAnswer (trans, username, answer,
  705. out passwordFormat, out salt)) {
  706. /* if the validation succeeds:
  707. set LastLoginDate to DateTime.Now
  708. set FailedPasswordAnswerAttemptCount to 0
  709. set FailedPasswordAnswerAttemptWindowStart to DefaultDateTime
  710. */
  711. string commandText = @"
  712. SELECT m.Password
  713. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  714. WHERE m.ApplicationId = a.ApplicationId
  715. AND u.ApplicationId = a.ApplicationId
  716. AND m.UserId = u.UserId
  717. AND u.LoweredUserName = LOWER(@UserName)
  718. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  719. DbCommand command = factory.CreateCommand ();
  720. command.Transaction = trans;
  721. command.CommandText = commandText;
  722. command.Connection = connection;
  723. command.CommandType = CommandType.Text;
  724. AddParameter (command, "UserName", username);
  725. AddParameter (command, "ApplicationName", ApplicationName);
  726. DbDataReader reader = command.ExecuteReader ();
  727. reader.Read ();
  728. password = reader.GetString (0);
  729. reader.Close();
  730. password = DecodePassword (password, passwordFormat);
  731. }
  732. else {
  733. throw new MembershipPasswordException ("The password-answer supplied is wrong.");
  734. }
  735. trans.Commit ();
  736. return password;
  737. }
  738. catch (MembershipPasswordException) {
  739. trans.Commit ();
  740. throw;
  741. }
  742. catch {
  743. trans.Rollback ();
  744. throw;
  745. }
  746. }
  747. MembershipUser GetUserFromReader (DbDataReader reader)
  748. {
  749. return new MembershipUser (this.Name, /* XXX is this right? */
  750. reader.GetString (0), /* name */
  751. reader.GetGuid (1), /* providerUserKey */
  752. reader.IsDBNull (2) ? null : reader.GetString (2), /* email */
  753. reader.IsDBNull (3) ? null : reader.GetString (3), /* passwordQuestion */
  754. reader.IsDBNull (4) ? null : reader.GetString (4), /* comment */
  755. reader.GetBoolean (5), /* isApproved */
  756. reader.GetBoolean (6), /* isLockedOut */
  757. reader.GetDateTime (7).ToLocalTime (), /* creationDate */
  758. reader.GetDateTime (8).ToLocalTime (), /* lastLoginDate */
  759. reader.GetDateTime (9).ToLocalTime (), /* lastActivityDate */
  760. reader.GetDateTime (10).ToLocalTime (), /* lastPasswordChangedDate */
  761. reader.GetDateTime (11).ToLocalTime () /* lastLockoutDate */);
  762. }
  763. MembershipUser BuildMembershipUser (DbCommand query, bool userIsOnline)
  764. {
  765. DbDataReader reader = null;
  766. try {
  767. reader = query.ExecuteReader ();
  768. if (!reader.Read ())
  769. return null;
  770. MembershipUser user = GetUserFromReader (reader);
  771. if (user != null && userIsOnline) {
  772. string commandText;
  773. DbCommand command;
  774. commandText = @"
  775. UPDATE dbo.aspnet_Users u, dbo.aspnet_Application a
  776. SET u.LastActivityDate = GETDATE()
  777. WHERE u.ApplicationId = a.ApplicationId
  778. AND u.UserName = @UserName
  779. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  780. command = factory.CreateCommand ();
  781. command.CommandText = commandText;
  782. command.Connection = connection;
  783. command.CommandType = CommandType.Text;
  784. AddParameter (command, "UserName", user.UserName);
  785. AddParameter (command, "ApplicationName", ApplicationName);
  786. command.ExecuteNonQuery();
  787. }
  788. return user;
  789. }
  790. catch {
  791. return null; /* should we let the exception through? */
  792. }
  793. finally {
  794. if (reader != null)
  795. reader.Close ();
  796. }
  797. }
  798. [MonoTODO]
  799. public override MembershipUser GetUser (string username, bool userIsOnline)
  800. {
  801. CheckParam ("username", username, 256);
  802. string commandText;
  803. DbCommand command;
  804. InitConnection();
  805. commandText = @"
  806. SELECT u.UserName, m.UserId, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
  807. m.IsLockedOut, m.CreateDate, m.LastLoginDate, u.LastActivityDate,
  808. m.LastPasswordChangedDate, m.LastLockoutDate
  809. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  810. WHERE m.ApplicationId = a.ApplicationId
  811. AND u.ApplicationId = a.ApplicationId
  812. AND m.UserId = u.UserId
  813. AND u.UserName = @UserName
  814. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  815. command = factory.CreateCommand ();
  816. command.CommandText = commandText;
  817. command.Connection = connection;
  818. command.CommandType = CommandType.Text;
  819. AddParameter (command, "UserName", username);
  820. AddParameter (command, "ApplicationName", ApplicationName);
  821. MembershipUser u = BuildMembershipUser (command, userIsOnline);
  822. return u;
  823. }
  824. [MonoTODO]
  825. public override MembershipUser GetUser (object providerUserKey, bool userIsOnline)
  826. {
  827. string commandText;
  828. DbCommand command;
  829. InitConnection();
  830. commandText = @"
  831. SELECT u.UserName, m.UserId, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
  832. m.IsLockedOut, m.CreateDate, m.LastLoginDate, u.LastActivityDate,
  833. m.LastPasswordChangedDate, m.LastLockoutDate
  834. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  835. WHERE m.ApplicationId = a.ApplicationId
  836. AND u.ApplicationId = a.ApplicationId
  837. AND m.UserId = u.UserId
  838. AND u.UserId = @UserKey
  839. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  840. command = factory.CreateCommand ();
  841. command.CommandText = commandText;
  842. command.Connection = connection;
  843. command.CommandType = CommandType.Text;
  844. AddParameter (command, "UserKey", providerUserKey.ToString());
  845. AddParameter (command, "ApplicationName", ApplicationName);
  846. MembershipUser u = BuildMembershipUser (command, userIsOnline);
  847. return u;
  848. }
  849. [MonoTODO]
  850. public override string GetUserNameByEmail (string email)
  851. {
  852. CheckParam ("email", email, 256);
  853. string commandText;
  854. DbCommand command;
  855. InitConnection();
  856. commandText = @"
  857. SELECT u.UserName
  858. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  859. WHERE m.ApplicationId = a.ApplicationId
  860. AND u.ApplicationId = a.ApplicationId
  861. AND m.UserId = u.UserId
  862. AND m.Email = @Email
  863. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  864. command = factory.CreateCommand ();
  865. command.CommandText = commandText;
  866. command.Connection = connection;
  867. command.CommandType = CommandType.Text;
  868. AddParameter (command, "Email", email);
  869. AddParameter (command, "ApplicationName", ApplicationName);
  870. try {
  871. DbDataReader reader = command.ExecuteReader ();
  872. string rv = null;
  873. while (reader.Read())
  874. rv = reader.GetString(0);
  875. reader.Close();
  876. return rv;
  877. }
  878. catch {
  879. return null; /* should we allow the exception through? */
  880. }
  881. }
  882. bool GetBoolConfigValue (NameValueCollection config, string name, bool def)
  883. {
  884. bool rv = def;
  885. string val = config[name];
  886. if (val != null) {
  887. try { rv = Boolean.Parse (val); }
  888. catch (Exception e) {
  889. throw new ProviderException (String.Format ("{0} must be true or false", name), e); }
  890. }
  891. return rv;
  892. }
  893. int GetIntConfigValue (NameValueCollection config, string name, int def)
  894. {
  895. int rv = def;
  896. string val = config[name];
  897. if (val != null) {
  898. try { rv = Int32.Parse (val); }
  899. catch (Exception e) {
  900. throw new ProviderException (String.Format ("{0} must be an integer", name), e); }
  901. }
  902. return rv;
  903. }
  904. int GetEnumConfigValue (NameValueCollection config, string name, Type enumType, int def)
  905. {
  906. int rv = def;
  907. string val = config[name];
  908. if (val != null) {
  909. try { rv = (int)Enum.Parse (enumType, val); }
  910. catch (Exception e) {
  911. throw new ProviderException (String.Format ("{0} must be one of the following values: {1}", name, String.Join (",", Enum.GetNames (enumType))), e); }
  912. }
  913. return rv;
  914. }
  915. string GetStringConfigValue (NameValueCollection config, string name, string def)
  916. {
  917. string rv = def;
  918. string val = config[name];
  919. if (val != null)
  920. rv = val;
  921. return rv;
  922. }
  923. void EmitValidatingPassword (string username, string password, bool isNewUser)
  924. {
  925. ValidatePasswordEventArgs args = new ValidatePasswordEventArgs (username, password, isNewUser);
  926. OnValidatingPassword (args);
  927. /* if we're canceled.. */
  928. if (args.Cancel) {
  929. if (args.FailureInformation == null)
  930. throw new ProviderException ("Password validation canceled");
  931. else
  932. throw args.FailureInformation;
  933. }
  934. }
  935. public override void Initialize (string name, NameValueCollection config)
  936. {
  937. if (config == null)
  938. throw new ArgumentNullException ("config");
  939. base.Initialize (name, config);
  940. applicationName = GetStringConfigValue (config, "applicationName", "/");
  941. enablePasswordReset = GetBoolConfigValue (config, "enablePasswordReset", true);
  942. enablePasswordRetrieval = GetBoolConfigValue (config, "enablePasswordRetrieval", false);
  943. requiresQuestionAndAnswer = GetBoolConfigValue (config, "requiresQuestionAndAnswer", true);
  944. requiresUniqueEmail = GetBoolConfigValue (config, "requiresUniqueEmail", false);
  945. passwordFormat = (MembershipPasswordFormat)GetEnumConfigValue (config, "passwordFormat", typeof (MembershipPasswordFormat),
  946. (int)MembershipPasswordFormat.Hashed);
  947. maxInvalidPasswordAttempts = GetIntConfigValue (config, "maxInvalidPasswordAttempts", 5);
  948. minRequiredPasswordLength = GetIntConfigValue (config, "minRequiredPasswordLength", 7);
  949. minRequiredNonAlphanumericCharacters = GetIntConfigValue (config, "minRequiredNonAlphanumericCharacters", 1);
  950. passwordAttemptWindow = GetIntConfigValue (config, "passwordAttemptWindow", 10);
  951. passwordStrengthRegularExpression = GetStringConfigValue (config, "passwordStrengthRegularExpression", "");
  952. MembershipSection section = (MembershipSection)WebConfigurationManager.GetSection ("system.web/membership");
  953. userIsOnlineTimeWindow = section.UserIsOnlineTimeWindow;
  954. /* we can't support password retrieval with hashed passwords */
  955. if (passwordFormat == MembershipPasswordFormat.Hashed && enablePasswordRetrieval)
  956. throw new ProviderException ("password retrieval cannot be used with hashed passwords");
  957. string connectionStringName = config["connectionStringName"];
  958. if (applicationName.Length > 256)
  959. throw new ProviderException ("The ApplicationName attribute must be 256 characters long or less.");
  960. if (connectionStringName == null || connectionStringName.Length == 0)
  961. throw new ProviderException ("The ConnectionStringName attribute must be present and non-zero length.");
  962. connectionString = WebConfigurationManager.ConnectionStrings[connectionStringName];
  963. }
  964. public override string ResetPassword (string username, string answer)
  965. {
  966. if (!enablePasswordReset)
  967. throw new NotSupportedException ("this provider has not been configured to allow the resetting of passwords");
  968. CheckParam ("username", username, 256);
  969. if (RequiresQuestionAndAnswer)
  970. CheckParam ("answer", answer, 128);
  971. MembershipUser user = GetUser (username, false);
  972. if (user == null) throw new ProviderException ("could not find user in membership database");
  973. if (user.IsLockedOut) throw new MembershipPasswordException ("user is currently locked out");
  974. InitConnection();
  975. string commandText;
  976. DbCommand command;
  977. DbTransaction trans = connection.BeginTransaction ();
  978. try {
  979. MembershipPasswordFormat db_passwordFormat;
  980. string db_salt;
  981. string newPassword = null;
  982. if (ValidateUsingPasswordAnswer (trans, user.UserName, answer, out db_passwordFormat, out db_salt)) {
  983. newPassword = GeneratePassword ();
  984. string db_password;
  985. EmitValidatingPassword (username, newPassword, false);
  986. /* otherwise update the user's password in the db */
  987. db_password = EncodePassword (newPassword, db_passwordFormat, db_salt);
  988. commandText = @"
  989. UPDATE m
  990. SET Password = @Password,
  991. FailedPasswordAnswerAttemptCount = 0,
  992. FailedPasswordAnswerAttemptWindowStart = @DefaultDateTime
  993. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  994. WHERE m.ApplicationId = a.ApplicationId
  995. AND u.ApplicationId = a.ApplicationId
  996. AND m.UserId = u.UserId
  997. AND u.LoweredUserName = LOWER(@UserName)
  998. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  999. command = factory.CreateCommand ();
  1000. command.Transaction = trans;
  1001. command.CommandText = commandText;
  1002. command.Connection = connection;
  1003. command.CommandType = CommandType.Text;
  1004. AddParameter (command, "UserName", user.UserName);
  1005. AddParameter (command, "Password", db_password);
  1006. AddParameter (command, "ApplicationName", ApplicationName);
  1007. AddParameter (command, "DefaultDateTime", DefaultDateTime.ToString());
  1008. if (1 != (int)command.ExecuteNonQuery ())
  1009. throw new ProviderException ("failed to update Membership table");
  1010. trans.Commit ();
  1011. }
  1012. else {
  1013. throw new MembershipPasswordException ("The password-answer supplied is wrong.");
  1014. }
  1015. return newPassword;
  1016. }
  1017. catch (MembershipPasswordException) {
  1018. trans.Commit ();
  1019. throw;
  1020. }
  1021. catch (ProviderException) {
  1022. trans.Rollback ();
  1023. throw;
  1024. }
  1025. catch (Exception e) {
  1026. trans.Rollback ();
  1027. throw new ProviderException ("Failed to reset password", e);
  1028. }
  1029. }
  1030. public override void UpdateUser (MembershipUser user)
  1031. {
  1032. if (user == null) throw new ArgumentNullException ("user");
  1033. if (user.UserName == null) throw new ArgumentNullException ("user.UserName");
  1034. if (RequiresUniqueEmail && user.Email == null) throw new ArgumentNullException ("user.Email");
  1035. CheckParam ("user.UserName", user.UserName, 256);
  1036. if (user.Email.Length > 256 || (RequiresUniqueEmail && user.Email.Length == 0))
  1037. throw new ArgumentException ("invalid format for user.Email");
  1038. DbTransaction trans = connection.BeginTransaction ();
  1039. string commandText;
  1040. DbCommand command;
  1041. InitConnection();
  1042. try {
  1043. DateTime now = DateTime.Now.ToUniversalTime ();
  1044. commandText = String.Format (@"
  1045. UPDATE m
  1046. SET Email = {0},
  1047. Comment = {1},
  1048. IsApproved = @IsApproved,
  1049. LastLoginDate = @Now
  1050. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  1051. WHERE m.ApplicationId = a.ApplicationId
  1052. AND u.ApplicationId = a.ApplicationId
  1053. AND m.UserId = u.UserId
  1054. AND u.LoweredUserName = LOWER(@UserName)
  1055. AND a.LoweredApplicationName = LOWER(@ApplicationName)",
  1056. user.Email == null ? "NULL" : "@Email",
  1057. user.Comment == null ? "NULL" : "@Comment");
  1058. command = factory.CreateCommand ();
  1059. command.Transaction = trans;
  1060. command.CommandText = commandText;
  1061. command.Connection = connection;
  1062. command.CommandType = CommandType.Text;
  1063. if (user.Email != null)
  1064. AddParameter (command, "Email", user.Email);
  1065. if (user.Comment != null)
  1066. AddParameter (command, "Comment", user.Comment);
  1067. AddParameter (command, "IsApproved", user.IsApproved.ToString());
  1068. AddParameter (command, "UserName", user.UserName);
  1069. AddParameter (command, "ApplicationName", ApplicationName);
  1070. AddParameter (command, "Now", now.ToString ());
  1071. if (0 == command.ExecuteNonQuery())
  1072. throw new ProviderException ("failed to membership table");
  1073. commandText = @"
  1074. UPDATE dbo.aspnet_Users
  1075. SET LastActivityDate = @Now
  1076. FROM dbo.aspnet_Users u, dbo.aspnet_Applications a
  1077. WHERE a.ApplicationId = a.ApplicationId
  1078. AND u.LoweredUserName = LOWER(@UserName)
  1079. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1080. command = factory.CreateCommand ();
  1081. command.Transaction = trans;
  1082. command.CommandText = commandText;
  1083. command.Connection = connection;
  1084. command.CommandType = CommandType.Text;
  1085. AddParameter (command, "UserName", user.UserName);
  1086. AddParameter (command, "ApplicationName", ApplicationName);
  1087. AddParameter (command, "Now", now.ToString ());
  1088. if (0 == command.ExecuteNonQuery())
  1089. throw new ProviderException ("failed to user table");
  1090. trans.Commit ();
  1091. }
  1092. catch (ProviderException) {
  1093. trans.Rollback ();
  1094. throw;
  1095. }
  1096. catch (Exception e) {
  1097. trans.Rollback ();
  1098. throw new ProviderException ("failed to update user", e);
  1099. }
  1100. }
  1101. public override bool ValidateUser (string username, string password)
  1102. {
  1103. MembershipUser user = GetUser (username, false);
  1104. /* if the user is locked out, return false immediately */
  1105. if (user.IsLockedOut)
  1106. return false;
  1107. /* if the user is not yet approved, return false */
  1108. if (!user.IsApproved)
  1109. return false;
  1110. EmitValidatingPassword (username, password, false);
  1111. InitConnection();
  1112. DbTransaction trans = connection.BeginTransaction ();
  1113. string commandText;
  1114. DbCommand command;
  1115. try {
  1116. MembershipPasswordFormat passwordFormat;
  1117. string salt;
  1118. bool valid = ValidateUsingPassword (trans, username, password, out passwordFormat, out salt);
  1119. if (valid) {
  1120. DateTime now = DateTime.Now.ToUniversalTime ();
  1121. /* if the validation succeeds:
  1122. set LastLoginDate to DateTime.Now
  1123. set FailedPasswordAttemptCount to 0
  1124. set FailedPasswordAttemptWindow to DefaultDateTime
  1125. set FailedPasswordAnswerAttemptCount to 0
  1126. set FailedPasswordAnswerAttemptWindowStart to DefaultDateTime
  1127. */
  1128. commandText = @"
  1129. UPDATE dbo.aspnet_Membership
  1130. SET LastLoginDate = @Now,
  1131. FailedPasswordAttemptCount = 0,
  1132. FailedPasswordAttemptWindowStart = @DefaultDateTime,
  1133. FailedPasswordAnswerAttemptCount = 0,
  1134. FailedPasswordAnswerAttemptWindowStart = @DefaultDateTime
  1135. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  1136. WHERE m.ApplicationId = a.ApplicationId
  1137. AND u.ApplicationId = a.ApplicationId
  1138. AND m.UserId = u.UserId
  1139. AND u.LoweredUserName = LOWER(@UserName)
  1140. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1141. command = factory.CreateCommand ();
  1142. command.Transaction = trans;
  1143. command.CommandText = commandText;
  1144. command.Connection = connection;
  1145. command.CommandType = CommandType.Text;
  1146. AddParameter (command, "UserName", user.UserName);
  1147. AddParameter (command, "ApplicationName", ApplicationName);
  1148. AddParameter (command, "Now", now.ToString ());
  1149. AddParameter (command, "DefaultDateTime", DefaultDateTime.ToString());
  1150. if (1 != (int)command.ExecuteNonQuery ())
  1151. throw new ProviderException ("failed to update Membership table");
  1152. commandText = @"
  1153. UPDATE dbo.aspnet_Users
  1154. SET LastActivityDate = @Now
  1155. FROM dbo.aspnet_Applications a, dbo.aspnet_Users u
  1156. WHERE u.ApplicationId = a.ApplicationId
  1157. AND u.LoweredUserName = LOWER(@UserName)
  1158. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1159. command = factory.CreateCommand ();
  1160. command.Transaction = trans;
  1161. command.CommandText = commandText;
  1162. command.Connection = connection;
  1163. command.CommandType = CommandType.Text;
  1164. AddParameter (command, "UserName", user.UserName);
  1165. AddParameter (command, "ApplicationName", ApplicationName);
  1166. AddParameter (command, "Now", now.ToString ());
  1167. if (1 != (int)command.ExecuteNonQuery ())
  1168. throw new ProviderException ("failed to update User table");
  1169. }
  1170. trans.Commit ();
  1171. return valid;
  1172. }
  1173. catch {
  1174. trans.Rollback ();
  1175. throw;
  1176. }
  1177. }
  1178. public override bool UnlockUser (string userName)
  1179. {
  1180. CheckParam ("userName", userName, 256);
  1181. string commandText = @"
  1182. UPDATE dbo.aspnet_Membership
  1183. SET IsLockedOut = 0,
  1184. LastLockoutDate = @DefaultDateTime,
  1185. FailedPasswordAttemptCount = 0,
  1186. FailedPasswordAttemptWindowStart = @DefaultDateTime,
  1187. FailedPasswordAnswerAttemptCount = 0,
  1188. FailedPasswordAnswerAttemptWindowStart = @DefaultDateTime
  1189. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  1190. WHERE m.UserId = u.UserId
  1191. AND m.ApplicationId = a.ApplicationId
  1192. AND u.ApplicationId = a.ApplicationId
  1193. AND u.LoweredUserName = LOWER (@UserName)
  1194. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1195. InitConnection();
  1196. DbCommand command = factory.CreateCommand ();
  1197. command.CommandText = commandText;
  1198. command.Connection = connection;
  1199. command.CommandType = CommandType.Text;
  1200. AddParameter (command, "UserName", userName);
  1201. AddParameter (command, "ApplicationName", ApplicationName);
  1202. AddParameter (command, "DefaultDateTime", DefaultDateTime.ToString());
  1203. return command.ExecuteNonQuery() == 1;
  1204. }
  1205. void IncrementFailureAndMaybeLockout (DbTransaction trans, string username,
  1206. string failureCountAttribute, string failureWindowAttribute)
  1207. {
  1208. DateTime now = DateTime.Now;
  1209. /* if validation fails:
  1210. if (FailedPasswordAttemptWindowStart - DateTime.Now < PasswordAttemptWindow)
  1211. increment FailedPasswordAttemptCount
  1212. FailedPasswordAttemptWindowStart = DateTime.Now
  1213. if (FailedPasswordAttemptCount > MaxInvalidPasswordAttempts)
  1214. set IsLockedOut = true.
  1215. set LastLockoutDate = DateTime.Now
  1216. */
  1217. string commandText = String.Format (@"
  1218. SELECT m.{0}, m.{1}
  1219. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  1220. WHERE m.ApplicationId = a.ApplicationId
  1221. AND u.ApplicationId = a.ApplicationId
  1222. AND m.UserId = u.UserId
  1223. AND u.LoweredUserName = LOWER(@UserName)
  1224. AND a.LoweredApplicationName = LOWER(@ApplicationName)",
  1225. failureCountAttribute, failureWindowAttribute);
  1226. DbCommand command = factory.CreateCommand ();
  1227. command.Transaction = trans;
  1228. command.CommandText = commandText;
  1229. command.Connection = connection;
  1230. command.CommandType = CommandType.Text;
  1231. AddParameter (command, "UserName", username);
  1232. AddParameter (command, "ApplicationName", ApplicationName);
  1233. DateTime db_FailedWindowStart;
  1234. int db_FailedCount;
  1235. DbDataReader reader = command.ExecuteReader ();
  1236. reader.Read ();
  1237. db_FailedCount = reader.GetInt32 (0);
  1238. db_FailedWindowStart = reader.GetDateTime (1).ToLocalTime ();
  1239. reader.Close();
  1240. TimeSpan diff = now.Subtract (db_FailedWindowStart);
  1241. if ((db_FailedWindowStart == DefaultDateTime.ToLocalTime ())
  1242. || diff.Minutes < PasswordAttemptWindow)
  1243. db_FailedCount ++;
  1244. if (db_FailedCount > MaxInvalidPasswordAttempts) {
  1245. /* lock the user out */
  1246. commandText = @"
  1247. UPDATE dbo.aspnet_Membership
  1248. SET IsLockedOut = 1,
  1249. LastLockoutDate = @LastLockoutDate
  1250. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  1251. WHERE m.ApplicationId = a.ApplicationId
  1252. AND u.ApplicationId = a.ApplicationId
  1253. AND m.UserId = u.UserId
  1254. AND u.LoweredUserName = LOWER(@UserName)
  1255. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1256. command = factory.CreateCommand ();
  1257. command.Transaction = trans;
  1258. command.CommandText = commandText;
  1259. command.Connection = connection;
  1260. command.CommandType = CommandType.Text;
  1261. AddParameter (command, "UserName", username);
  1262. AddParameter (command, "ApplicationName", ApplicationName);
  1263. AddParameter (command, "LastLockoutDate", now.ToUniversalTime().ToString ());
  1264. }
  1265. else {
  1266. /* just store back the updated window start and count */
  1267. commandText = String.Format (@"
  1268. UPDATE dbo.aspnet_Membership
  1269. SET {0} = @{0},
  1270. {1} = @{1}
  1271. FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
  1272. WHERE m.ApplicationId = a.ApplicationId
  1273. AND u.ApplicationId = a.ApplicationId
  1274. AND m.UserId = u.UserId
  1275. AND u.LoweredUserName = LOWER(@UserName)
  1276. AND a.LoweredApplicationName = LOWER(@ApplicationName)",
  1277. failureCountAttribute, failureWindowAttribute);
  1278. command = factory.CreateCommand ();
  1279. command.Transaction = trans;
  1280. command.CommandText = commandText;
  1281. command.Connection = connection;
  1282. command.CommandType = CommandType.Text;
  1283. AddParameter (command, "UserName", username);
  1284. AddParameter (command, "ApplicationName", ApplicationName);
  1285. AddParameter (command, failureCountAttribute, db_FailedCount.ToString());
  1286. AddParameter (command, failureWindowAttribute, now.ToUniversalTime().ToString ());
  1287. }
  1288. if (1 != (int)command.ExecuteNonQuery ())
  1289. throw new ProviderException ("failed to update Membership table");
  1290. }
  1291. bool ValidateUsingPassword (DbTransaction trans, string username, string password,
  1292. out MembershipPasswordFormat passwordFormat,
  1293. out string salt)
  1294. {
  1295. string commandText = @"
  1296. SELECT m.Password, m.PasswordFormat, m.PasswordSalt
  1297. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  1298. WHERE m.ApplicationId = a.ApplicationId
  1299. AND u.ApplicationId = a.ApplicationId
  1300. AND m.UserId = u.UserId
  1301. AND u.LoweredUserName = LOWER(@UserName)
  1302. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1303. DbCommand command = factory.CreateCommand ();
  1304. command.Transaction = trans;
  1305. command.CommandText = commandText;
  1306. command.Connection = connection;
  1307. command.CommandType = CommandType.Text;
  1308. AddParameter (command, "UserName", username);
  1309. AddParameter (command, "ApplicationName", ApplicationName);
  1310. string db_password;
  1311. DbDataReader reader = command.ExecuteReader ();
  1312. reader.Read ();
  1313. db_password = reader.GetString (0);
  1314. passwordFormat = (MembershipPasswordFormat)reader.GetInt32 (1);
  1315. salt = reader.GetString (2);
  1316. reader.Close();
  1317. /* do the actual validation */
  1318. password = EncodePassword (password, passwordFormat, salt);
  1319. bool valid = (password == db_password);
  1320. if (!valid)
  1321. IncrementFailureAndMaybeLockout (trans, username,
  1322. "FailedPasswordAttemptCount", "FailedPasswordAttemptWindowStart");
  1323. return valid;
  1324. }
  1325. bool ValidateUsingPasswordAnswer (DbTransaction trans, string username, string answer,
  1326. out MembershipPasswordFormat passwordFormat,
  1327. out string salt)
  1328. {
  1329. string commandText = @"
  1330. SELECT m.PasswordAnswer, m.PasswordFormat, m.PasswordSalt
  1331. FROM dbo.aspnet_Membership m, dbo.aspnet_Applications a, dbo.aspnet_Users u
  1332. WHERE m.ApplicationId = a.ApplicationId
  1333. AND u.ApplicationId = a.ApplicationId
  1334. AND m.UserId = u.UserId
  1335. AND u.LoweredUserName = LOWER(@UserName)
  1336. AND a.LoweredApplicationName = LOWER(@ApplicationName)";
  1337. DbCommand command = factory.CreateCommand ();
  1338. command.Transaction = trans;
  1339. command.CommandText = commandText;
  1340. command.Connection = connection;
  1341. command.CommandType = CommandType.Text;
  1342. AddParameter (command, "UserName", username);
  1343. AddParameter (command, "ApplicationName", ApplicationName);
  1344. string db_answer;
  1345. DbDataReader reader = command.ExecuteReader ();
  1346. reader.Read ();
  1347. db_answer = reader.GetString (0);
  1348. passwordFormat = (MembershipPasswordFormat)reader.GetInt32 (1);
  1349. salt = reader.GetString (2);
  1350. reader.Close();
  1351. /* do the actual password answer check */
  1352. answer = EncodePassword (answer, passwordFormat, salt);
  1353. if (answer.Length > 128)
  1354. throw new ArgumentException (String.Format ("password answer hashed to longer than 128 characters"));
  1355. bool valid = (answer == db_answer);
  1356. if (!valid)
  1357. IncrementFailureAndMaybeLockout (trans, username,
  1358. "FailedPasswordAnswerAttemptCount",
  1359. "FailedPasswordAnswerAttemptWindowStart");
  1360. return valid;
  1361. }
  1362. [MonoTODO]
  1363. public override string ApplicationName {
  1364. get { return applicationName; }
  1365. set { applicationName = value; }
  1366. }
  1367. public override bool EnablePasswordReset {
  1368. get { return enablePasswordReset; }
  1369. }
  1370. public override bool EnablePasswordRetrieval {
  1371. get { return enablePasswordRetrieval; }
  1372. }
  1373. public override MembershipPasswordFormat PasswordFormat {
  1374. get { return passwordFormat; }
  1375. }
  1376. public override bool RequiresQuestionAndAnswer {
  1377. get { return requiresQuestionAndAnswer; }
  1378. }
  1379. public override bool RequiresUniqueEmail {
  1380. get { return requiresUniqueEmail; }
  1381. }
  1382. public override int MaxInvalidPasswordAttempts {
  1383. get { return maxInvalidPasswordAttempts; }
  1384. }
  1385. public override int MinRequiredNonAlphanumericCharacters {
  1386. get { return minRequiredNonAlphanumericCharacters; }
  1387. }
  1388. public override int MinRequiredPasswordLength {
  1389. get { return minRequiredPasswordLength; }
  1390. }
  1391. public override int PasswordAttemptWindow {
  1392. get { return passwordAttemptWindow; }
  1393. }
  1394. public override string PasswordStrengthRegularExpression {
  1395. get { return passwordStrengthRegularExpression; }
  1396. }
  1397. }
  1398. }
  1399. #endif