2
0

SqlMembershipProvider.cs 56 KB

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