From: <mar...@us...> - 2010-02-06 23:19:54
|
Revision: 18 http://cronoscontrol.svn.sourceforge.net/cronoscontrol/?rev=18&view=rev Author: marioarce Date: 2010-02-06 23:19:47 +0000 (Sat, 06 Feb 2010) Log Message: ----------- Ticket #3 Custom Membership Provider for CronosControl Implements the methods of MembershipProvider to provide the ASP.NET membership services for CronosControl TrackerManager.cs This class implements the methods necessary for maintaining users with rol 'Tracker' in CronosControl using the database schema, mdf file and entity mappings of CronosControl. Added Paths: ----------- source/trunk/CronosControl/Libraries/BusinessLogic/Profile/ source/trunk/CronosControl/Libraries/BusinessLogic/Profile/CronosControlMembershipProvider.cs source/trunk/CronosControl/Libraries/BusinessLogic/Tracker/ source/trunk/CronosControl/Libraries/BusinessLogic/Tracker/TrackerManager.cs Added: source/trunk/CronosControl/Libraries/BusinessLogic/Profile/CronosControlMembershipProvider.cs =================================================================== --- source/trunk/CronosControl/Libraries/BusinessLogic/Profile/CronosControlMembershipProvider.cs (rev 0) +++ source/trunk/CronosControl/Libraries/BusinessLogic/Profile/CronosControlMembershipProvider.cs 2010-02-06 23:19:47 UTC (rev 18) @@ -0,0 +1,477 @@ +//------------------------------------------------------------------------------ +// The contents of this file are subject to the GNU General Public License Version 3.0 ("License"); you may not use this file except in compliance with the License. +// You may obtain a copy of the License at http://www.cronoscontrol.net/license.html. +// +// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. +// See the License for the specific language governing rights and limitations under the License. +// +// The Original Code is CronosControl. +// The Initial Developer of the Original Code is WebImageConsulting http://www.wicnow.com/. +// All Rights Reserved. +// +// Contributor(s): Mario Alberto Arce, _______. +//------------------------------------------------------------------------------ + +using System; +using System.Web; +using System.Web.Security; +using System.Text.RegularExpressions; +using System.Configuration.Provider; +using System.Collections.Generic; +using System.Collections.Specialized; +using CronosControl.Common.Utils; +using CronosControl.BusinessLogic.Tracker; +using CronosControl.Model; + +namespace CronosControl.BusinessLogic.Profile +{ + public class CronosControlMembershipProvider : MembershipProvider + { + #region Fields + private string _AppName; + private bool _EnablePasswordReset; + private bool _EnablePasswordRetrieval; + private int _MaxInvalidPasswordAttempts; + private int _MinRequiredNonalphanumericCharacters; + private int _MinRequiredPasswordLength; + private int _PasswordAttemptWindow; + private string _PasswordStrengthRegularExpression; + private bool _RequiresQuestionAndAnswer; + private bool _RequiresUniqueEmail; + #endregion + + #region Methods + /// <summary> + /// Processes a request to update the password for a membership user. + /// </summary> + /// <param name="username">The user to update the password for. </param> + /// <param name="oldPassword">The current password for the specified user.</param> + /// <param name="newPassword">The new password for the specified user.</param> + /// <returns>true if the password was updated successfully; otherwise, false.</returns> + public override bool ChangePassword(string username, string oldPassword, string newPassword) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Processes a request to update the password question and answer for a membership user. + /// </summary> + /// <param name="username">The user to change the password question and answer for.</param> + /// <param name="password">The password for the specified user.</param> + /// <param name="newPasswordQuestion">The new password question for the specified user.</param> + /// <param name="newPasswordAnswer">The new password answer for the specified user.</param> + /// <returns>true if the password question and answer are updated successfully; otherwise, false.</returns> + public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Adds a new membership user to the data source. + /// </summary> + /// <param name="username">The user name for the new user.</param> + /// <param name="password">The password for the new user.</param> + /// <param name="email">The e-mail address for the new user.</param> + /// <param name="passwordQuestion">The password question for the new user.</param> + /// <param name="passwordAnswer">The password answer for the new user.</param> + /// <param name="isApproved">Whether or not the new user is approved to be validated.</param> + /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param> + /// <param name="status">A MembershipCreateStatus enumeration value indicating whether the user was created successfully.</param> + /// <returns>A MembershipUser object populated with the information for the newly created user.</returns> + public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) + { + MembershipUser user = null; + + // add tracker + TrackerManager.AddTracker(email, username, password, username, "-", isApproved, out status); + + // user key + string userKey = string.Empty; + if (providerUserKey == null) + { + userKey = Guid.NewGuid().ToString(); + } + else + { + userKey = providerUserKey.ToString(); + } + + if (status == MembershipCreateStatus.Success) + { + // create membership user + DateTime dt = DateTimeHelper.ConvertToUtcTime(DateTime.Now); + user = new MembershipUser(this.Name, username, null, email, string.Empty, null, true, false, dt, dt, dt, dt, dt); + } + return user; + } + + /// <summary> + /// Removes a user from the membership data source. + /// </summary> + /// <param name="username">The name of the user to delete.</param> + /// <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> + /// <returns>true if the user was successfully deleted; otherwise, false.</returns> + public override bool DeleteUser(string username, bool deleteAllRelatedData) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match. + /// </summary> + /// <param name="EmailToMatch">The e-mail address to search for.</param> + /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> + /// <param name="pageSize">The size of the page of results to return.</param> + /// <param name="totalRecords">The total number of matched users.</param> + /// <returns>A MembershipUserCollection collection that contains a page of pageSizeMembershipUser objects beginning at the page specified by pageIndex.</returns> + public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets a collection of membership users where the user name contains the specified user name to match. + /// </summary> + /// <param name="usernameToMatch">The user name to search for.</param> + /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> + /// <param name="pageSize">The size of the page of results to return.</param> + /// <param name="totalRecords">The total number of matched users.</param> + /// <returns>A MembershipUserCollection collection that contains a page of pageSizeMembershipUser objects beginning at the page specified by pageIndex.</returns> + public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets a collection of all the users in the data source in pages of data. + /// </summary> + /// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param> + /// <param name="pageSize">The size of the page of results to return.</param> + /// <param name="totalRecords">The total number of matched users.</param> + /// <returns>A MembershipUserCollection collection that contains a page of pageSizeMembershipUser objects beginning at the page specified by pageIndex.</returns> + public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets the number of users currently accessing the application. + /// </summary> + /// <returns>The number of users currently accessing the application.</returns> + public override int GetNumberOfUsersOnline() + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets the password for the specified user name from the data source. + /// </summary> + /// <param name="username">The user to retrieve the password for.</param> + /// <param name="answer">The password answer for the user.</param> + /// <returns>The password for the specified user name.</returns> + public override string GetPassword(string username, string answer) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user. + /// </summary> + /// <param name="username">The name of the user to get information for.</param> + /// <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> + /// <returns>A MembershipUser object populated with the specified user's information from the data source.</returns> + public override MembershipUser GetUser(string username, bool userIsOnline) + { + User user = TrackerManager.GetTrackerByUsername(username); + + if (user == null) + return null; + DateTime dt = DateTimeHelper.ConvertToUtcTime(DateTime.Now); + + return new MembershipUser(this.Name, username, user.IdUser, user.Email, string.Empty, null, true, false, dt, dt, dt, dt, dt); + } + + /// <summary> + /// 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. + /// </summary> + /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param> + /// <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> + /// <returns>A MembershipUser object populated with the specified user's information from the data source.</returns> + public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets the user name associated with the specified e-mail address. + /// </summary> + /// <param name="email">The e-mail address to search for.</param> + /// <returns>The user name associated with the specified e-mail address. If no match is found, return null.</returns> + public override string GetUserNameByEmail(string email) + { + User user = TrackerManager.GetTrackerByEmail(email); + if (user == null) + return null; + return user.Username; + } + + /// <summary> + /// Initializes the provider. + /// </summary> + /// <param name="name">The friendly name of the provider.</param> + /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> + public override void Initialize(string name, NameValueCollection config) + { + if (config == null) + { + throw new ArgumentNullException("config"); + } + if (string.IsNullOrEmpty(name)) + { + name = "CronosControlMembershipProvider"; + } + if (string.IsNullOrEmpty(config["description"])) + { + config.Remove("description"); + config.Add("description", "Membership Provider for CronosControl"); + } + base.Initialize(name, config); + this._EnablePasswordReset = CommonHelper.ConfigGetBooleanValue(config, "enablePasswordReset", true); + this._EnablePasswordRetrieval = CommonHelper.ConfigGetBooleanValue(config, "enablePasswordRetrieval", true); + this._RequiresQuestionAndAnswer = CommonHelper.ConfigGetBooleanValue(config, "requiresQuestionAndAnswer", true); + this._RequiresUniqueEmail = CommonHelper.ConfigGetBooleanValue(config, "requiresUniqueEmail", true); + this._MaxInvalidPasswordAttempts = CommonHelper.ConfigGetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0); + this._PasswordAttemptWindow = CommonHelper.ConfigGetIntValue(config, "passwordAttemptWindow", 10, false, 0); + this._MinRequiredPasswordLength = CommonHelper.ConfigGetIntValue(config, "minRequiredPasswordLength", 7, false, 0x80); + this._MinRequiredNonalphanumericCharacters = CommonHelper.ConfigGetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 0x80); + this._PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; + if (this._PasswordStrengthRegularExpression != null) + { + this._PasswordStrengthRegularExpression = this._PasswordStrengthRegularExpression.Trim(); + if (this._PasswordStrengthRegularExpression.Length != 0) + { + try + { + new Regex(this._PasswordStrengthRegularExpression); + } + catch (ArgumentException ex) + { + throw new ProviderException(ex.Message, ex); + } + } + } + this._PasswordStrengthRegularExpression = string.Empty; + if (this._MinRequiredNonalphanumericCharacters > this._MinRequiredPasswordLength) + { + throw new HttpException("MinRequiredNonalphanumericCharacters can not be more than MinRequiredPasswordLength"); + } + this._AppName = config["applicationName"]; + if (string.IsNullOrEmpty(this._AppName)) + { + this._AppName = "CronosControl"; + } + if (this._AppName.Length > 0x100) + { + throw new ProviderException("Provider application name too long"); + } + + string connectionStringName = config["connectionStringName"]; + if (string.IsNullOrEmpty(connectionStringName)) + { + this._AppName = "CronosControlEntities"; + } + + config.Remove("enablePasswordReset"); + config.Remove("enablePasswordRetrieval"); + config.Remove("requiresQuestionAndAnswer"); + config.Remove("applicationName"); + config.Remove("requiresUniqueEmail"); + config.Remove("maxInvalidPasswordAttempts"); + config.Remove("passwordAttemptWindow"); + config.Remove("commandTimeout"); + config.Remove("name"); + config.Remove("minRequiredPasswordLength"); + config.Remove("minRequiredNonalphanumericCharacters"); + config.Remove("passwordStrengthRegularExpression"); + config.Remove("connectionStringName"); + if (config.Count > 0) + { + string key = config.GetKey(0); + if (!string.IsNullOrEmpty(key)) + { + throw new ProviderException(string.Format("Provider unrecognized attribute {0}", key)); + } + } + } + + /// <summary> + /// Resets a user's password to a new, automatically generated password. + /// </summary> + /// <param name="username">The user to reset the password for.</param> + /// <param name="answer">The password answer for the specified user.</param> + /// <returns>The new password for the specified user.</returns> + public override string ResetPassword(string username, string answer) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Clears a lock so that the membership user can be validated. + /// </summary> + /// <param name="userName">The membership user whose lock status you want to clear.</param> + /// <returns>true if the membership user was successfully unlocked; otherwise, false.</returns> + public override bool UnlockUser(string userName) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Updates information about a user in the data source. + /// </summary> + /// <param name="user">A MembershipUser object that represents the user to update and the updated information for the user.</param> + public override void UpdateUser(MembershipUser user) + { + throw new NotImplementedException(); + } + + /// <summary> + /// Verifies that the specified user name and password exist in the data source. + /// </summary> + /// <param name="username">The name of the user to validate.</param> + /// <param name="password">The password for the specified user.</param> + /// <returns>true if the specified username and password are valid; otherwise, false.</returns> + public override bool ValidateUser(string username, string password) + { + User user = TrackerManager.GetTrackerByUsername(username); + return TrackerManager.Login(username, password); + } + #endregion + + #region Properties + /// <summary> + /// The name of the application using the custom membership provider. + /// </summary> + public override string ApplicationName + { + get + { + return this._AppName; + } + set + { + this._AppName = value; + } + } + + /// <summary> + /// Indicates whether the membership provider is configured to allow users to reset their passwords. + /// </summary> + public override bool EnablePasswordReset + { + get + { + return this._EnablePasswordReset; + } + } + + /// <summary> + /// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out. + /// </summary> + public override int MaxInvalidPasswordAttempts + { + get + { + return this._MaxInvalidPasswordAttempts; + } + } + + /// <summary> + /// Gets the minimum number of special characters that must be present in a valid password. + /// </summary> + public override int MinRequiredNonAlphanumericCharacters + { + get + { + return this._MinRequiredNonalphanumericCharacters; + } + } + + /// <summary> + /// Gets the minimum length required for a password. + /// </summary> + public override int MinRequiredPasswordLength + { + get + { + return this._MinRequiredPasswordLength; + } + } + + /// <summary> + /// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out. + /// </summary> + public override int PasswordAttemptWindow + { + get + { + return this._PasswordAttemptWindow; + } + } + + /// <summary> + /// Gets the regular expression used to evaluate a password. + /// </summary> + public override string PasswordStrengthRegularExpression + { + get + { + return this._PasswordStrengthRegularExpression; + } + } + + /// <summary> + /// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval. + /// </summary> + public override bool RequiresQuestionAndAnswer + { + get + { + return this._RequiresQuestionAndAnswer; + } + } + + /// <summary> + /// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name. + /// </summary> + public override bool RequiresUniqueEmail + { + get + { + return this._RequiresUniqueEmail; + } + } + + /// <summary> + /// Indicates whether the membership provider is configured to allow users to retrieve their passwords. + /// </summary> + public override bool EnablePasswordRetrieval + { + get + { + return _EnablePasswordRetrieval; + } + } + + /// <summary> + /// Gets a value indicating the format for storing passwords in the membership data store. + /// </summary> + public override MembershipPasswordFormat PasswordFormat + { + get + { + return MembershipPasswordFormat.Hashed; + } + } + #endregion + } +} Added: source/trunk/CronosControl/Libraries/BusinessLogic/Tracker/TrackerManager.cs =================================================================== --- source/trunk/CronosControl/Libraries/BusinessLogic/Tracker/TrackerManager.cs (rev 0) +++ source/trunk/CronosControl/Libraries/BusinessLogic/Tracker/TrackerManager.cs 2010-02-06 23:19:47 UTC (rev 18) @@ -0,0 +1,234 @@ +//------------------------------------------------------------------------------ +// The contents of this file are subject to the GNU General Public License Version 3.0 ("License"); you may not use this file except in compliance with the License. +// You may obtain a copy of the License at http://www.cronoscontrol.net/license.html. +// +// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. +// See the License for the specific language governing rights and limitations under the License. +// +// The Original Code is CronosControl. +// The Initial Developer of the Original Code is WebImageConsulting http://www.wicnow.com/. +// All Rights Reserved. +// +// Contributor(s): Mario Alberto Arce, _______. +//------------------------------------------------------------------------------ + +using System; +using System.Linq; +using System.Text; +using System.Web.Security; +using System.Collections.Generic; +using System.Security.Cryptography; +using CronosControl.Model; +using CronosControl.BusinessLogic.Configuration.Settings; +using CronosControl.Business; +using CronosControl.Common.Utils; + +namespace CronosControl.BusinessLogic.Tracker +{ + /// <summary> + /// Tracker manager + /// </summary> + public partial class TrackerManager + { + #region Methods + /// <summary> + /// Adds a tracker + /// </summary> + /// <param name="Email">The email</param> + /// <param name="Username">The username</param> + /// <param name="Password">The password</param> + /// <param name="Name">A value indicating whether the name of the tracker</param> + /// <param name="Lastname">A value indicating whether the lastname of the tracker</param> + /// <param name="Enabled">A value indicating whether the tracker is active</param> + /// <param name="status">Status</param> + /// <returns>A tracker</returns> + public static User AddTracker(string email, string username, string password, + string name, string lastname, + bool enabled, out MembershipCreateStatus status) + { + string saltKey = string.Empty; + string passwordHash = string.Empty; + status = MembershipCreateStatus.UserRejected; + + // duplicated UserName ? + //status = MembershipCreateStatus.DuplicateUserName; + + // invalid UserName ? + //status = MembershipCreateStatus.InvalidUserName; + + // duplicated email ? + //status = MembershipCreateStatus.DuplicateEmail; + + // invalid email ? + if (!CommonHelper.IsValidEmail(email)) + status = MembershipCreateStatus.InvalidEmail; + + + int idCompany = Convert.ToInt32(SettingManager.Current["base", "idCompany"]); + passwordHash = CreatePasswordMd5Hash(password); + + User userEntity = new User(); + userEntity.Name = name; + userEntity.Lastname = lastname; + userEntity.Username = username; + userEntity.Password = passwordHash; + userEntity.Email = email; + userEntity.IdCompany = idCompany; + userEntity.CreatedAt = DateTimeHelper.ConvertToUtcTime(DateTime.Now); + userEntity.Enabled = enabled; + + try + { + Users users = new Users(); + users.Save(userEntity); + } + catch + { + status = MembershipCreateStatus.ProviderError; + } + + status = MembershipCreateStatus.Success; + return userEntity; + } + + /// <summary> + /// Creates a salt + /// </summary> + /// <param name="size">A salt size</param> + /// <returns>A salt</returns> + private static string CreateSalt(int size) + { + RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); + byte[] data = new byte[size]; + provider.GetBytes(data); + return Convert.ToBase64String(data); + } + + /// <summary> + /// Creates a password hash + /// </summary> + /// <param name="Password">Password</param> + /// <param name="Salt">Salt</param> + /// <returns>Password hash</returns> + private static string CreatePasswordHash(string Password, string Salt) + { + //MD5, SHA1 + string passwordFormat = SettingManager.Current["Security", "PasswordFormat"]; + if (String.IsNullOrEmpty(passwordFormat)) + passwordFormat = "SHA1"; + + return FormsAuthentication.HashPasswordForStoringInConfigFile(Password + Salt, passwordFormat); + } + + /// <summary> + /// Creates a password Md5 hash + /// </summary> + /// <param name="Password">Password</param> + /// <returns>Password hash</returns> + private static string CreatePasswordMd5Hash(string password) + { + if (string.IsNullOrEmpty(password)) + return string.Empty; + + // Create a new instance of the MD5CryptoServiceProvider object. + MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); + + // Convert the input string to a byte array and compute the hash. + byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(password)); + + // Create a new Stringbuilder to collect the bytes + // and create a string. + StringBuilder sBuilder = new StringBuilder(); + + // Loop through each byte of the hashed data + // and format each one as a hexadecimal string. + for (int i = 0; i < data.Length; i++) + { + sBuilder.Append(data[i].ToString("x2")); + } + + // Return the hexadecimal string. + return sBuilder.ToString(); + } + + /// <summary> + /// Gets a tracket by email + /// </summary> + /// <param name="Username">Tracker email</param> + /// <returns>A tracker</returns> + public static User GetTrackerByEmail(string email) + { + if (string.IsNullOrEmpty(email)) + return null; + if (!CommonHelper.IsValidEmail(email)) + return null; + + CronosControlEntities cronosControlEntities = new CronosControlEntities(); + User user = (from u in cronosControlEntities.User + where u.Email.Equals(email) + select u).First<User>(); + + return user; + } + + /// <summary> + /// Gets a tracket + /// </summary> + /// <param name="Username">Tracker identifier</param> + /// <returns>A tracker</returns> + public static User GetTrackerByID(int trackerID) + { + if (trackerID == 0) + return null; + + CronosControlEntities cronosControlEntities = new CronosControlEntities(); + User user = (from u in cronosControlEntities.User + where u.IdUser.Equals(trackerID) + select u).First<User>(); + + return user; + } + + /// <summary> + /// Gets a tracket by username + /// </summary> + /// <param name="Username">Tracker username</param> + /// <returns>A tracker</returns> + public static User GetTrackerByUsername(string username) + { + if (string.IsNullOrEmpty(username)) + return null; + + CronosControlEntities cronosControlEntities = new CronosControlEntities(); + User user = (from u in cronosControlEntities.User + where u.Username.Equals(username) + select u).First<User>(); + + return user; + } + + /// <summary> + /// Login a tracker + /// </summary> + /// <param name="Email">A tracker username</param> + /// <param name="Password">Password</param> + /// <returns>Result</returns> + public static bool Login(string username, string password) + { + User user = GetTrackerByUsername(username); + + if (user == null) + return false; + if (!user.Enabled) + return false; + + string passwordHash = CreatePasswordMd5Hash(password); + bool result = user.Password.Equals(passwordHash); + + // any session stuff here ... + + return result; + } + #endregion + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |