PageRenderTime 29ms CodeModel.GetById 2ms app.highlight 20ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/DotNetSlave.BusinessLogic/Providers/DbMembershipProvider.cs

#
C# | 829 lines | 516 code | 99 blank | 214 comment | 66 complexity | eb7e5b12ae0e1c364389d58228e709d5 MD5 | raw file
  1namespace BlogEngine.Core.Providers
  2{
  3    using System;
  4    using System.Collections.Specialized;
  5    using System.Configuration;
  6    using System.Configuration.Provider;
  7    using System.Data;
  8    using System.Data.Common;
  9    using System.Web.Security;
 10
 11    /// <summary>
 12    /// Generic Db Membership Provider
 13    /// </summary>
 14    public class DbMembershipProvider : MembershipProvider
 15    {
 16        #region Constants and Fields
 17
 18        /// <summary>
 19        /// The application name.
 20        /// </summary>
 21        private string applicationName;
 22
 23        /// <summary>
 24        /// The conn string name.
 25        /// </summary>
 26        private string connStringName;
 27
 28        /// <summary>
 29        /// The parm prefix.
 30        /// </summary>
 31        private string parmPrefix;
 32
 33        /// <summary>
 34        /// The password format.
 35        /// </summary>
 36        private MembershipPasswordFormat passwordFormat;
 37
 38        /// <summary>
 39        /// The table prefix.
 40        /// </summary>
 41        private string tablePrefix;
 42
 43        #endregion
 44
 45        #region Properties
 46
 47        /// <summary>
 48        ///     Returns the application name as set in the web.config
 49        ///     otherwise returns BlogEngine.  Set will throw an error.
 50        /// </summary>
 51        public override string ApplicationName
 52        {
 53            get
 54            {
 55                return this.applicationName;
 56            }
 57
 58            set
 59            {
 60                throw new NotSupportedException();
 61            }
 62        }
 63
 64        /// <summary>
 65        ///     Hardcoded to false
 66        /// </summary>
 67        public override bool EnablePasswordReset
 68        {
 69            get
 70            {
 71                return false;
 72            }
 73        }
 74
 75        /// <summary>
 76        ///     Can password be retrieved via email?
 77        /// </summary>
 78        public override bool EnablePasswordRetrieval
 79        {
 80            get
 81            {
 82                return false;
 83            }
 84        }
 85
 86        /// <summary>
 87        ///     Hardcoded to 5
 88        /// </summary>
 89        public override int MaxInvalidPasswordAttempts
 90        {
 91            get
 92            {
 93                return 5;
 94            }
 95        }
 96
 97        /// <summary>
 98        ///     Hardcoded to 0
 99        /// </summary>
100        public override int MinRequiredNonAlphanumericCharacters
101        {
102            get
103            {
104                return 0;
105            }
106        }
107
108        /// <summary>
109        ///     Hardcoded to 4
110        /// </summary>
111        public override int MinRequiredPasswordLength
112        {
113            get
114            {
115                return 4;
116            }
117        }
118
119        /// <summary>
120        ///     Not implemented
121        /// </summary>
122        public override int PasswordAttemptWindow
123        {
124            get
125            {
126                throw new NotImplementedException();
127            }
128        }
129
130        /// <summary>
131        ///     Password format (Clear or Hashed)
132        /// </summary>
133        public override MembershipPasswordFormat PasswordFormat
134        {
135            get
136            {
137                return this.passwordFormat;
138            }
139        }
140
141        /// <summary>
142        ///     Not Implemented
143        /// </summary>
144        public override string PasswordStrengthRegularExpression
145        {
146            get
147            {
148                throw new NotImplementedException();
149            }
150        }
151
152        /// <summary>
153        ///     Hardcoded to false
154        /// </summary>
155        public override bool RequiresQuestionAndAnswer
156        {
157            get
158            {
159                return false;
160            }
161        }
162
163        /// <summary>
164        ///     Hardcoded to false
165        /// </summary>
166        public override bool RequiresUniqueEmail
167        {
168            get
169            {
170                return false;
171            }
172        }
173
174        #endregion
175
176        #region Public Methods
177
178        /// <summary>
179        /// Change the password if the old password matches what is stored
180        /// </summary>
181        /// <param name="username">The user to update the password for.</param>
182        /// <param name="oldPassword">The current password for the specified user.</param>
183        /// <param name="newPassword">The new password for the specified user.</param>
184        /// <returns>The change password.</returns>
185        public override bool ChangePassword(string username, string oldPassword, string newPassword)
186        {
187            var oldPasswordCorrect = false;
188            var success = false;
189
190            using (var conn = this.CreateConnection())
191            {
192                if (conn.HasConnection)
193                {
194                    using (var cmd = conn.CreateTextCommand(string.Format("SELECT password FROM {0}Users WHERE BlogID = {1}blogid AND userName = {1}name", this.tablePrefix, this.parmPrefix)))
195                    {
196                        // Check Old Password
197
198                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
199                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("name"), username));
200
201                        using (var rdr = cmd.ExecuteReader())
202                        {
203                            if (rdr.Read())
204                            {
205                                var actualPassword = rdr.GetString(0);
206                                if (actualPassword == string.Empty)
207                                {
208                                    // This is a special case used for resetting.
209                                    if (oldPassword.ToLower() == "admin")
210                                    {
211                                        oldPasswordCorrect = true;
212                                    }
213                                }
214                                else
215                                {
216                                    if (this.passwordFormat == MembershipPasswordFormat.Hashed)
217                                    {
218                                        if (actualPassword == Utils.HashPassword(oldPassword))
219                                        {
220                                            oldPasswordCorrect = true;
221                                        }
222                                    }
223                                    else if (actualPassword == oldPassword)
224                                    {
225                                        oldPasswordCorrect = true;
226                                    }
227                                }
228                            }
229                        }
230
231                        // Update New Password
232                        if (oldPasswordCorrect)
233                        {
234                            cmd.CommandText = string.Format("UPDATE {0}Users SET password = {1}pwd WHERE BlogID = {1}blogid AND userName = {1}name", this.tablePrefix, this.parmPrefix);
235
236                            cmd.Parameters.Add(conn.CreateParameter(FormatParamName("pwd"), (this.passwordFormat == MembershipPasswordFormat.Hashed ? Utils.HashPassword(newPassword) : newPassword)));
237
238                            cmd.ExecuteNonQuery();
239                            success = true;
240                        }
241                    }
242                }
243            }
244
245            return success;
246        }
247
248        /// <summary>
249        /// Not implemented
250        /// </summary>
251        /// <param name="username">The user to change the password question and answer for.</param>
252        /// <param name="password">The password for the specified user.</param>
253        /// <param name="newPasswordQuestion">The new password question for the specified user.</param>
254        /// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
255        /// <returns>The change password question and answer.</returns>
256        public override bool ChangePasswordQuestionAndAnswer(
257            string username, string password, string newPasswordQuestion, string newPasswordAnswer)
258        {
259            throw new NotImplementedException();
260        }
261
262        /// <summary>
263        /// Add new user to database
264        /// </summary>
265        /// <param name="username">The user name for the new user.</param>
266        /// <param name="password">The password for the new user.</param>
267        /// <param name="email">The e-mail address for the new user.</param>
268        /// <param name="passwordQuestion">The password question for the new user.</param>
269        /// <param name="passwordAnswer">The password answer for the new user</param>
270        /// <param name="approved">Whether or not the new user is approved to be validated.</param>
271        /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
272        /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"/> enumeration value indicating whether the user was created successfully.</param>
273        /// <returns>
274        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.
275        /// </returns>
276        public override MembershipUser CreateUser(
277            string username,
278            string password,
279            string email,
280            string passwordQuestion,
281            string passwordAnswer,
282            bool approved,
283            object providerUserKey,
284            out MembershipCreateStatus status)
285        {
286
287            using (var conn = this.CreateConnection())
288            {
289                if (conn.HasConnection)
290                {
291                    var sqlQuery = string.Format("INSERT INTO {0}Users (blogId, userName, password, emailAddress, lastLoginTime) VALUES ({1}blogid, {1}name, {1}pwd, {1}email, {1}login)", this.tablePrefix, this.parmPrefix);
292                    using (var cmd = conn.CreateTextCommand(sqlQuery))
293                    {
294
295                        var parms = cmd.Parameters;
296                        parms.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
297                        parms.Add(conn.CreateParameter(FormatParamName("name"), username));
298                        parms.Add(conn.CreateParameter(FormatParamName("pwd"), (this.passwordFormat == MembershipPasswordFormat.Hashed ? Utils.HashPassword(password) : password)));
299                        parms.Add(conn.CreateParameter(FormatParamName("email"), email));
300                        parms.Add(conn.CreateParameter(FormatParamName("login"), DateTime.Now));
301
302                        cmd.ExecuteNonQuery();
303                    }
304                }
305            }
306
307            MembershipUser user = this.GetMembershipUser(username, email, DateTime.Now);
308            status = MembershipCreateStatus.Success;
309
310            return user;
311        }
312
313        /// <summary>
314        /// Delete user from database
315        /// </summary>
316        /// <param name="username">The name of the user to delete.</param>
317        /// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
318        /// <returns>The delete user.</returns>
319        public override bool DeleteUser(string username, bool deleteAllRelatedData)
320        {
321            bool success = false;
322
323            using (var conn = this.CreateConnection())
324            {
325                if (conn.HasConnection)
326                {
327                    using (var cmd = conn.CreateTextCommand(string.Format("DELETE FROM {0}Users WHERE blogId = {1}blogid AND userName = {1}name", this.tablePrefix, this.parmPrefix)))
328                    {
329                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
330                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("name"), username));
331
332                        try
333                        {
334                            cmd.ExecuteNonQuery();
335                            success = true;
336                        }
337                        catch (Exception ex)
338                        {
339                            success = false;
340                            throw;
341                        }
342                    }
343                }
344            }
345
346            return success;
347        }
348
349        /// <summary>
350        /// Not implemented
351        /// </summary>
352        /// <param name="emailToMatch">The e-mail address to search for.</param>
353        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param>
354        /// <param name="pageSize">The size of the page of results to return.</param>
355        /// <param name="totalRecords">The total number of matched users.</param>
356        /// <returns>
357        /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.
358        /// </returns>
359        public override MembershipUserCollection FindUsersByEmail(
360            string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
361        {
362            throw new NotImplementedException();
363        }
364
365        /// <summary>
366        /// Not implemented
367        /// </summary>
368        /// <param name="usernameToMatch">The user name to search for.</param>
369        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param>
370        /// <param name="pageSize">The size of the page of results to return.</param>
371        /// <param name="totalRecords">The total number of matched users.</param>
372        /// <returns>
373        /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.
374        /// </returns>
375        public override MembershipUserCollection FindUsersByName(
376            string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
377        {
378            throw new NotImplementedException();
379        }
380
381        /// <summary>
382        /// Return all users in MembershipUserCollection
383        /// </summary>
384        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param>
385        /// <param name="pageSize">The size of the page of results to return.</param>
386        /// <param name="totalRecords">The total number of matched users.</param>
387        /// <returns>
388        /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.
389        /// </returns>
390        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
391        {
392            var users = new MembershipUserCollection();
393
394            using (var conn = this.CreateConnection())
395            {
396                if (conn.HasConnection)
397                {
398                    using (var cmd = conn.CreateTextCommand(string.Format("SELECT username, EmailAddress, lastLoginTime FROM {0}Users WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix)))
399                    {
400                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
401
402                        using (var rdr = cmd.ExecuteReader())
403                        {
404                            while (rdr.Read())
405                            {
406                                users.Add(this.GetMembershipUser(rdr.GetString(0), rdr.GetString(1), rdr.GetDateTime(2)));
407                            }
408                        }
409                    }
410                }
411            }
412
413            totalRecords = users.Count;
414            return users;
415        }
416
417        /// <summary>
418        /// Not implemented
419        /// </summary>
420        /// <returns>
421        /// The get number of users online.
422        /// </returns>
423        public override int GetNumberOfUsersOnline()
424        {
425            throw new NotImplementedException();
426        }
427
428        /// <summary>
429        /// Not implemented
430        /// </summary>
431        /// <param name="username">The user to retrieve the password for.</param>
432        /// <param name="answer">The password answer for the user.</param>
433        /// <returns>The get password.</returns>
434        public override string GetPassword(string username, string answer)
435        {
436            throw new NotImplementedException();
437        }
438
439        /// <summary>
440        /// Gets user information from the data source based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
441        /// </summary>
442        /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
443        /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
444        /// <returns>
445        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.
446        /// </returns>
447        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
448        {
449            return this.GetUser(providerUserKey.ToString(), userIsOnline);
450        }
451
452        /// <summary>
453        /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
454        /// </summary>
455        /// <param name="username">The name of the user to get information for.</param>
456        /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
457        /// <returns>
458        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.
459        /// </returns>
460        public override MembershipUser GetUser(string username, bool userIsOnline)
461        {
462            MembershipUser user = null;
463
464            using (var conn = this.CreateConnection())
465            {
466                if (conn.HasConnection)
467                {
468                    using (var cmd = conn.CreateTextCommand(string.Format("SELECT username, EmailAddress, lastLoginTime FROM {0}Users WHERE BlogID = {1}blogid AND UserName = {1}name", this.tablePrefix, this.parmPrefix)))
469                    {
470                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
471                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("name"), username));
472
473                        using (var rdr = cmd.ExecuteReader())
474                        {
475                            if (rdr.Read())
476                            {
477                                user = this.GetMembershipUser(username, rdr.GetString(1), rdr.GetDateTime(2));
478                            }
479                        }
480                    }
481                }
482            }
483
484            return user;
485        }
486
487        /// <summary>
488        /// Gets the user name associated with the specified e-mail address.
489        /// </summary>
490        /// <param name="email">The e-mail address to search for.</param>
491        /// <returns>
492        /// The user name associated with the specified e-mail address. If no match is found, return null.
493        /// </returns>
494        public override string GetUserNameByEmail(string email)
495        {
496            if (email == null)
497            {
498                throw new ArgumentNullException("email");
499            }
500
501            string userName = null;
502
503            using (var conn = this.CreateConnection())
504            {
505                if (conn.HasConnection)
506                {
507                    using (var cmd = conn.CreateTextCommand(string.Format("SELECT userName FROM {0}Users WHERE BlogID = {1}blogid AND emailAddress = {1}email", this.tablePrefix, this.parmPrefix)))
508                    {
509                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
510                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("email"), email));
511
512                        using (var rdr = cmd.ExecuteReader())
513                        {
514                            if (rdr.Read())
515                            {
516                                userName = rdr.GetString(0);
517                            }
518                        }
519                    }
520                }
521            }
522
523            return userName;
524        }
525
526        /// <summary>
527        /// Initializes the provider
528        /// </summary>
529        /// <param name="name">
530        /// Configuration name
531        /// </param>
532        /// <param name="config">
533        /// Configuration settings
534        /// </param>
535        public override void Initialize(string name, NameValueCollection config)
536        {
537            if (config == null)
538            {
539                throw new ArgumentNullException("config");
540            }
541
542            if (string.IsNullOrEmpty(name))
543            {
544                name = "DbMembershipProvider";
545            }
546
547            if (Utils.IsMono)
548            {
549                // Mono dies with a "Unrecognized attribute: description" if a description is part of the config.
550                if (!string.IsNullOrEmpty(config["description"]))
551                {
552                    config.Remove("description");
553                }
554            }
555            else
556            {
557                if (string.IsNullOrEmpty(config["description"]))
558                {
559                    config.Remove("description");
560                    config.Add("description", "Generic Database Membership Provider");
561                }
562            }
563
564            base.Initialize(name, config);
565
566            // Connection String
567            if (config["connectionStringName"] == null)
568            {
569                config["connectionStringName"] = "BlogEngine";
570            }
571
572            this.connStringName = config["connectionStringName"];
573            config.Remove("connectionStringName");
574
575            // Table Prefix
576            if (config["tablePrefix"] == null)
577            {
578                config["tablePrefix"] = "be_";
579            }
580
581            this.tablePrefix = config["tablePrefix"];
582            config.Remove("tablePrefix");
583
584            // Parameter character
585            if (config["parmPrefix"] == null)
586            {
587                config["parmPrefix"] = "@";
588            }
589
590            this.parmPrefix = config["parmPrefix"];
591            config.Remove("parmPrefix");
592
593            // Application Name
594            if (config["applicationName"] == null)
595            {
596                config["applicationName"] = "BlogEngine";
597            }
598
599            this.applicationName = config["applicationName"];
600            config.Remove("applicationName");
601
602            // Password Format
603            if (config["passwordFormat"] == null)
604            {
605                config["passwordFormat"] = "Hashed";
606                this.passwordFormat = MembershipPasswordFormat.Hashed;
607            }
608            else if (string.Compare(config["passwordFormat"], "clear", true) == 0)
609            {
610                this.passwordFormat = MembershipPasswordFormat.Clear;
611            }
612            else
613            {
614                this.passwordFormat = MembershipPasswordFormat.Hashed;
615            }
616
617            config.Remove("passwordFormat");
618
619            // Throw an exception if unrecognized attributes remain
620            if (config.Count > 0)
621            {
622                var attr = config.GetKey(0);
623                if (!string.IsNullOrEmpty(attr))
624                {
625                    throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr));
626                }
627            }
628        }
629
630        /// <summary>
631        /// Resets a user's password to a new, automatically generated password.
632        /// </summary>
633        /// <param name="username">The user to reset the password for.</param>
634        /// <param name="answer">The password answer for the specified user.</param>
635        /// <returns>The new password for the specified user.</returns>
636        public override string ResetPassword(string username, string answer)
637        {
638            if (string.IsNullOrEmpty(username))
639            {
640                return string.Empty;
641            }
642
643            var oldPassword = string.Empty;
644            var randomPassword = Utils.RandomPassword();
645
646            using (var conn = this.CreateConnection())
647            {
648                if (conn.HasConnection)
649                {
650
651                    using (var cmd = conn.CreateTextCommand(string.Format("SELECT password FROM {0}Users WHERE BlogID = {1}blogid AND userName = {1}name", this.tablePrefix, this.parmPrefix)))
652                    {
653                        // Check Old Password
654
655                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
656                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("name"), username));
657
658                        using (var rdr = cmd.ExecuteReader())
659                        {
660                            if (rdr.Read())
661                            {
662                                oldPassword = rdr.GetString(0);
663                            }
664                        }
665
666                        // Update Password
667                        if (!string.IsNullOrEmpty(oldPassword))
668                        {
669                            cmd.CommandText = string.Format("UPDATE {0}Users SET password = {1}pwd WHERE BlogID = {1}blogid AND userName = {1}name", this.tablePrefix, this.parmPrefix);
670
671                            cmd.Parameters.Add(conn.CreateParameter(FormatParamName("pwd"), (this.passwordFormat == MembershipPasswordFormat.Hashed ? Utils.HashPassword(randomPassword) : randomPassword)));
672
673                            cmd.ExecuteNonQuery();
674                            return randomPassword;
675                        }
676                    }
677                }
678            }
679
680            return string.Empty;
681        }
682
683        /// <summary>
684        /// Not implemented
685        /// </summary>
686        /// <param name="userName">The membership user whose lock status you want to clear.</param>
687        /// <returns>The unlock user.</returns>
688        public override bool UnlockUser(string userName)
689        {
690            throw new NotImplementedException();
691        }
692
693        /// <summary>
694        /// Update User Data (not password)
695        /// </summary>
696        /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"/> object that represents the user to update and the updated information for the user.</param>
697        public override void UpdateUser(MembershipUser user)
698        {
699            using (var conn = this.CreateConnection())
700            {
701                if (conn.HasConnection)
702                {
703                    using (var cmd = conn.CreateTextCommand(string.Format("UPDATE {0}Users SET emailAddress = {1}email WHERE BlogId = {1}blogId AND userName = {1}name", this.tablePrefix, this.parmPrefix)))
704                    {
705                        var parms = cmd.Parameters;
706                        parms.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
707                        parms.Add(conn.CreateParameter(FormatParamName("name"), user.UserName));
708                        parms.Add(conn.CreateParameter(FormatParamName("email"), user.Email));
709
710                        cmd.ExecuteNonQuery();
711                    }
712                }
713            }
714        }
715
716        /// <summary>
717        /// Check username and password
718        /// </summary>
719        /// <param name="username">The name of the user to validate.</param>
720        /// <param name="password">The password for the specified user.</param>
721        /// <returns>The validate user.</returns>
722        public override bool ValidateUser(string username, string password)
723        {
724            var validated = false;
725
726            using (var conn = this.CreateConnection())
727            {
728                if (conn.HasConnection)
729                {
730                    using (var cmd = conn.CreateTextCommand(string.Format("SELECT password FROM {0}Users WHERE BlogID = {1}blogid AND UserName = {1}name", this.tablePrefix, this.parmPrefix)))
731                    {
732                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString()));
733                        cmd.Parameters.Add(conn.CreateParameter(FormatParamName("name"), username));
734
735                        using (var rdr = cmd.ExecuteReader())
736                        {
737                            if (rdr.Read())
738                            {
739                                var storedPwd = rdr.GetString(0);
740
741                                if (storedPwd == string.Empty)
742                                {
743                                    // This is a special case used for resetting.
744                                    if (password.ToLower() == "admin")
745                                    {
746                                        validated = true;
747                                    }
748                                }
749                                else
750                                {
751                                    if (this.passwordFormat == MembershipPasswordFormat.Hashed)
752                                    {
753                                        if (storedPwd == Utils.HashPassword(password))
754                                        {
755                                            validated = true;
756                                        }
757                                    }
758                                    else if (storedPwd == password)
759                                    {
760                                        validated = true;
761                                    }
762                                }
763                            }
764                        }
765                    }
766                }
767            }
768
769            return validated;
770        }
771
772        #endregion
773
774        #region Methods
775
776        private DbConnectionHelper CreateConnection()
777        {
778            var settings = ConfigurationManager.ConnectionStrings[this.connStringName];
779            return new DbConnectionHelper(settings);
780        }
781
782
783        /// <summary>
784        /// Returns a formatted parameter name to include this DbBlogProvider instance's paramPrefix.
785        /// </summary>
786        /// <param name="parameterName"></param>
787        /// <returns></returns>
788        private string FormatParamName(string parameterName)
789        {
790            return string.Format("{0}{1}", this.parmPrefix, parameterName);
791        }
792
793        /// <summary>
794        /// Gets membership user.
795        /// </summary>
796        /// <param name="userName">
797        /// The user name.
798        /// </param>
799        /// <param name="email">
800        /// The email.
801        /// </param>
802        /// <param name="lastLogin">
803        /// The last login.
804        /// </param>
805        /// <returns>
806        /// A MembershipUser.
807        /// </returns>
808        private MembershipUser GetMembershipUser(string userName, string email, DateTime lastLogin)
809        {
810            var user = new MembershipUser(
811                this.Name, // Provider name
812                userName, // Username
813                userName, // providerUserKey
814                email, // Email
815                string.Empty, // passwordQuestion
816                string.Empty, // Comment
817                true, // approved
818                false, // isLockedOut
819                DateTime.Now, // creationDate
820                lastLogin, // lastLoginDate
821                DateTime.Now, // lastActivityDate
822                DateTime.Now, // lastPasswordChangedDate
823                new DateTime(1980, 1, 1)); // lastLockoutDate
824            return user;
825        }
826
827        #endregion
828    }
829}