/// <summary> /// Grabs all the roles from the DB /// </summary> /// <param name="username"> /// The username. /// </param> /// <returns> /// </returns> public override string[] GetRolesForUser(string username) { if (username.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "USERNAMEBLANK"); } StringCollection roleNames = null; // get the users's collection from the dictionary if (!this.UserRoleCache.ContainsKey(username.ToLower())) { roleNames = new StringCollection(); DataTable roles = DB.Current.GetRoles(this.ApplicationName, username); foreach (DataRow dr in roles.Rows) { roleNames.Add(dr["Rolename"].ToStringDBNull()); // add rolename to collection } // add it to the dictionary cache... this.UserRoleCache.AddOrUpdate(username.ToLower(), (k) => roleNames, (s, v) => roleNames); } else { roleNames = this.UserRoleCache[username.ToLower()]; } return(roleNames.ToStringArray()); // return as a string array }
/// <summary> /// The set property values. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="collection"> /// The collection. /// </param> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { var username = (string)context["UserName"]; if (string.IsNullOrEmpty(username) || collection.Count < 1) { return; } // this provider doesn't support anonymous users if (!Convert.ToBoolean(context["IsAuthenticated"])) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } // First make sure we have at least one item to save if (!collection.Cast <SettingsPropertyValue>().Any(pp => pp.IsDirty)) { return; } // load the data for the configuration this.LoadFromPropertyValueCollection(collection); object userID = DB.Current.GetProviderUserKey(this.ApplicationName, username); if (userID != null) { // start saving... DB.Current.SetProfileProperties(this.ApplicationName, userID, collection, this._settingsColumnsList); // erase from the cache this.DeleteFromProfileCacheIfExists(username.ToLower()); } }
/// <summary> /// Creates a role /// </summary> /// <param name="roleName"> /// </param> public override void CreateRole(string roleName) { if (roleName.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "ROLENAMEBLANK"); } DB.Current.CreateRole(this.ApplicationName, roleName); }
/// <summary> /// The get number of inactive profiles. /// </summary> /// <param name="authenticationOption"> /// The authentication option. /// </param> /// <param name="userInactiveSinceDate"> /// The user inactive since date. /// </param> /// <returns> /// The get number of inactive profiles. /// </returns> public override int GetNumberOfInactiveProfiles( ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { if (authenticationOption == ProfileAuthenticationOption.Anonymous) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } return(DB.Current.GetNumberInactiveProfiles(this.ApplicationName, userInactiveSinceDate)); }
/// <summary> /// Reset a users password - * /// </summary> /// <param name="username">User to be found based by Name</param> /// <param name="answer">Verifcation that it is them</param> /// <returns>Username as string</returns> public override string ResetPassword(string username, string answer) { string newPassword = string.Empty, newPasswordEnc = string.Empty, newPasswordSalt = string.Empty, newPasswordAnswer = string.Empty; /// Check Password reset is enabled if (!(this.EnablePasswordReset)) { ExceptionReporter.ThrowNotSupported("MEMBERSHIP", "RESETNOTSUPPORTED"); } // Check arguments for null values if (username == null) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMEPASSWORDNULL"); } // get an instance of the current password information class UserPasswordInfo currentPasswordInfo = UserPasswordInfo.CreateInstanceFromDB(this.ApplicationName, username, false, this.UseSalt); if (currentPasswordInfo != null) { if (UseSalt && String.IsNullOrEmpty(currentPasswordInfo.PasswordSalt)) { // get a new password salt... newPasswordSalt = YafMembershipProvider.GenerateSalt(); } else { // use existing salt... newPasswordSalt = currentPasswordInfo.PasswordSalt; } if (!String.IsNullOrEmpty(answer)) { // verify answer is correct... if (!currentPasswordInfo.IsCorrectAnswer(answer)) { return(null); } } // create a new password newPassword = YafMembershipProvider.GeneratePassword(this.MinRequiredPasswordLength, this.MinRequiredNonAlphanumericCharacters); // encode it... newPasswordEnc = YafMembershipProvider.EncodeString(newPassword, ( int )this.PasswordFormat, newPasswordSalt, this.UseSalt); // save to the database DB.ResetPassword(this.ApplicationName, username, newPasswordEnc, newPasswordSalt, ( int )this.PasswordFormat, this.MaxInvalidPasswordAttempts, this.PasswordAttemptWindow); // Return unencrypted password return(newPassword); } return(null); }
/// <summary> /// The delete inactive profiles. /// </summary> /// <param name="authenticationOption"> /// The authentication option. /// </param> /// <param name="userInactiveSinceDate"> /// The user inactive since date. /// </param> /// <returns> /// The delete inactive profiles. /// </returns> public override int DeleteInactiveProfiles( ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { if (authenticationOption == ProfileAuthenticationOption.Anonymous) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } // just clear the whole thing... this.ClearUserProfileCache(); return(DB.Current.DeleteInactiveProfiles(this.ApplicationName, userInactiveSinceDate)); }
/// <summary> /// The get profile as collection. /// </summary> /// <param name="authenticationOption"> /// The authentication option. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <param name="userNameToMatch"> /// The user name to match. /// </param> /// <param name="inactiveSinceDate"> /// The inactive since date. /// </param> /// <param name="totalRecords"> /// The total records. /// </param> /// <returns> /// </returns> private ProfileInfoCollection GetProfileAsCollection( ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, object userNameToMatch, object inactiveSinceDate, out int totalRecords) { if (authenticationOption == ProfileAuthenticationOption.Anonymous) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } if (pageIndex < 0) { ExceptionReporter.ThrowArgument("PROFILE", "PAGEINDEXTOOSMALL"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("PROFILE", "PAGESIZETOOSMALL"); } // get all the profiles... DataSet allProfilesDS = DB.Current.GetProfiles(this.ApplicationName, pageIndex, pageSize, userNameToMatch, inactiveSinceDate); // create an instance for the profiles... var profiles = new ProfileInfoCollection(); DataTable allProfilesDT = allProfilesDS.Tables[0]; DataTable profilesCountDT = allProfilesDS.Tables[1]; foreach (DataRow profileRow in allProfilesDT.Rows) { string username = profileRow["Username"].ToString(); DateTime lastActivity = DateTime.SpecifyKind(Convert.ToDateTime(profileRow["LastActivity"]), DateTimeKind.Utc); DateTime lastUpdated = DateTime.SpecifyKind(Convert.ToDateTime(profileRow["LastUpdatedDate"]), DateTimeKind.Utc); profiles.Add(new ProfileInfo(username, false, lastActivity, lastUpdated, 0)); } // get the first record which is the count... totalRecords = Convert.ToInt32(profilesCountDT.Rows[0][0]); return(profiles); }
/// <summary> /// Gets a list of usernames in a a particular role /// </summary> /// <param name="roleName"> /// Rolename /// </param> /// <returns> /// List of Usernames /// </returns> public override string[] GetUsersInRole(string roleName) { if (roleName.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "ROLENAMEBLANK"); } DataTable users = DB.Current.FindUsersInRole(this.ApplicationName, roleName); var userNames = new StringCollection(); foreach (DataRow dr in users.Rows) { userNames.Add(dr["Username"].ToStringDBNull()); } return(userNames.ToStringArray()); }
/// <summary> /// Retrieves a MembershipUser object from the criteria given /// </summary> /// <param name="username">Username to be foundr</param> /// <param name="userIsOnline">Is the User currently online</param> /// <returns>MembershipUser object</returns> public override MembershipUser GetUser(string username, bool userIsOnline) { if (username == null) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMENULL"); } // if it's empty don't bother calling the DB. if (String.IsNullOrEmpty(username)) { return(null); } DataRow dr = DB.GetUser(this.ApplicationName, null, username, userIsOnline); if (dr != null) { return(new MembershipUser(Utils.Transform.ToString(this.Name), Utils.Transform.ToString(dr ["Username"]), Utils.Transform.ToString(dr ["UserID"]), Utils.Transform.ToString(dr ["Email"]), Utils.Transform.ToString(dr ["PasswordQuestion"]), Utils.Transform.ToString(dr ["Comment"]), Utils.Transform.ToBool(dr ["IsApproved"]), Utils.Transform.ToBool(dr ["IsLockedOut"]), Utils.Transform.ToDateTime(dr ["Joined"]), Utils.Transform.ToDateTime(dr ["LastLogin"]), Utils.Transform.ToDateTime(dr ["LastActivity"]), Utils.Transform.ToDateTime(dr ["LastPasswordChange"]), Utils.Transform.ToDateTime(dr ["LastLockout"]))); } return(null); }
/// <summary> /// Retrieves the Users password (if EnablePasswordRetrieval is true) /// </summary> /// <param name="username">Username to retrieve password for</param> /// <param name="answer">Answer to the Users Membership Question</param> /// <param name="newPasswordQuestion">New question</param> /// <param name="newPasswordAnswer">New answer</param> /// <returns> Password unencrypted</returns> public override string GetPassword(string username, string answer) { if (!this.EnablePasswordRetrieval) { ExceptionReporter.ThrowNotSupported("MEMBERSHIP", "PASSWORDRETRIEVALNOTSUPPORTED"); } // Check for null arguments if ((username == null) || (answer == null)) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "USERNAMEPASSWORDNULL"); } UserPasswordInfo currentPasswordInfo = UserPasswordInfo.CreateInstanceFromDB(this.ApplicationName, username, false, this.UseSalt); if (currentPasswordInfo != null && currentPasswordInfo.IsCorrectAnswer(answer)) { return(YafMembershipProvider.DecodeString(currentPasswordInfo.Password, currentPasswordInfo.PasswordFormat)); } return(null); }
/// <summary> /// Retrieves all users into a MembershupUserCollection /// </summary> /// <param name="pageIndex">Page Index</param> /// <param name="userIsOnline">How many records to the page</param> /// <param name="totalRecords">Out - Number of records held</param> /// <returns>MembershipUser Collection</returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection users = new MembershipUserCollection(); if (pageIndex < 0) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGEINDEX"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("MEMBERSHIP", "BADPAGESIZE"); } // Loop through all users foreach (DataRow dr in DB.GetAllUsers(this.ApplicationName, pageIndex, pageSize).Rows) { // Add new user to collection users.Add(new MembershipUser(Utils.Transform.ToString(this.Name), Utils.Transform.ToString(dr ["Username"]), Utils.Transform.ToString(dr ["UserID"]), Utils.Transform.ToString(dr ["Email"]), Utils.Transform.ToString(dr ["PasswordQuestion"]), Utils.Transform.ToString(dr ["Comment"]), Utils.Transform.ToBool(dr ["IsApproved"]), Utils.Transform.ToBool(dr ["IsLockedOut"]), Utils.Transform.ToDateTime(dr ["Joined"]), Utils.Transform.ToDateTime(dr ["LastLogin"]), Utils.Transform.ToDateTime(dr ["LastActivity"]), Utils.Transform.ToDateTime(dr ["LastPasswordChange"]), Utils.Transform.ToDateTime(dr ["LastLockout"]))); } totalRecords = users.Count; return(users); }
/// <summary> /// The delete profiles. /// </summary> /// <param name="profiles"> /// The profiles. /// </param> /// <returns> /// The delete profiles. /// </returns> public override int DeleteProfiles(ProfileInfoCollection profiles) { if (profiles == null) { ExceptionReporter.ThrowArgumentNull("PROFILE", "PROFILESNULL"); } if (profiles.Count < 1) { ExceptionReporter.ThrowArgument("PROFILE", "PROFILESEMPTY"); } var usernames = new string[profiles.Count]; int index = 0; foreach (ProfileInfo profile in profiles) { usernames[index++] = profile.UserName; } return(DeleteProfiles(usernames)); }
/// <summary> /// Sets up the profile providers /// </summary> /// <param name="name"> /// </param> /// <param name="config"> /// </param> public override void Initialize(string name, NameValueCollection config) { // verify that the configuration section was properly passed if (config == null) { ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND"); } // Connection String Name this._connStrName = config["connectionStringName"].ToStringDBNull(); ConnStringHelpers.TrySetProviderConnectionString(this._connStrName, ConnStrAppKeyName); base.Initialize(name, config); // application name this._appName = config["applicationName"]; if (string.IsNullOrEmpty(this._appName)) { this._appName = "YetAnotherForum"; } }
/// <summary> /// Sets up the profile providers /// </summary> /// <param name="name"> /// </param> /// <param name="config"> /// </param> public override void Initialize(string name, NameValueCollection config) { // verify that the configuration section was properly passed if (config == null) { ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND"); } // Connection String Name this._connStrName = config["connectionStringName"].ToStringDBNull(); // is the connection string set? if (this._connStrName.IsSet()) { string connStr = ConfigurationManager.ConnectionStrings[this._connStrName].ConnectionString; // set the app variable... if (YafContext.Application[ConnStrAppKeyName] == null) { YafContext.Application.Add(ConnStrAppKeyName, connStr); } else { YafContext.Application[ConnStrAppKeyName] = connStr; } } base.Initialize(name, config); // application name this._appName = config["applicationName"]; if (string.IsNullOrEmpty(this._appName)) { this._appName = "YetAnotherForum"; } }
/// <summary> /// The get property values. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="collection"> /// The collection. /// </param> /// <returns> /// </returns> public override SettingsPropertyValueCollection GetPropertyValues( SettingsContext context, SettingsPropertyCollection collection) { var settingPropertyCollection = new SettingsPropertyValueCollection(); if (collection.Count < 1) { return(settingPropertyCollection); } string username = context["UserName"].ToString(); if (username.IsNotSet()) { return(settingPropertyCollection); } // this provider doesn't support anonymous users if (!Convert.ToBoolean(context["IsAuthenticated"])) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } // load the property collection (sync profile class) this.LoadFromPropertyCollection(collection); // see if it's cached... if (this.UserProfileCache.ContainsKey(username.ToLower())) { // just use the cached version... return(this.UserProfileCache[username.ToLower()]); } // transfer properties regardless... foreach (SettingsProperty prop in collection) { settingPropertyCollection.Add(new SettingsPropertyValue(prop)); } // get this profile from the DB DataSet profileDS = DB.Current.GetProfiles(this.ApplicationName, 0, 1, username, null); DataTable profileDT = profileDS.Tables[0]; if (profileDT.HasRows()) { DataRow row = profileDT.Rows[0]; // load the data into the collection... foreach (SettingsPropertyValue prop in settingPropertyCollection) { object val = row[prop.Name]; // Only initialize a SettingsPropertyValue for non-null values if (val is DBNull || val == null) { continue; } prop.PropertyValue = val; prop.IsDirty = false; prop.Deserialized = true; } } // save this collection to the cache this.UserProfileCache.AddOrUpdate(username.ToLower(), (k) => settingPropertyCollection, (k, v) => settingPropertyCollection); return(settingPropertyCollection); }
/// <summary> /// Initialie Membership Provider /// </summary> /// <param name="name">Membership Provider Name</param> /// <param name="config">NameValueCollection of configuration items</param> public override void Initialize(string name, NameValueCollection config) { // Verify that the configuration section was properly passed if (config == null) { ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND"); } // Retrieve information for provider from web config // config ints // Minimum Required Password Length from Provider configuration _minimumRequiredPasswordLength = int.Parse(config ["minRequiredPasswordLength"] ?? "6"); // Minimum Required Non Alpha-numeric Characters from Provider configuration _minRequiredNonAlphanumericCharacters = int.Parse(config ["minRequiredNonalphanumericCharacters"] ?? "1"); // Maximum number of allowed password attempts _maxInvalidPasswordAttempts = int.Parse(config ["maxInvalidPasswordAttempts"] ?? "5"); // Password Attempt Window when maximum attempts have been reached _passwordAttemptWindow = int.Parse(config ["passwordAttemptWindow"] ?? "10"); // Check whething Hashing methods should use Salt _useSalt = Utils.Transform.ToBool(config ["useSalt"] ?? "false"); // Application Name _appName = Utils.Transform.ToString(config ["applicationName"], "YetAnotherForum"); _passwordStrengthRegularExpression = Utils.Transform.ToString(config ["passwordStrengthRegularExpression"]); // Password reset enabled from Provider Configuration _enablePasswordReset = Utils.Transform.ToBool(config ["enablePasswordReset"] ?? "true"); _enablePasswordRetrieval = Utils.Transform.ToBool(config ["enablePasswordRetrieval"] ?? "false"); _requiresQuestionAndAnswer = Utils.Transform.ToBool(config ["requiresQuestionAndAnswer"] ?? "true"); _requiresUniqueEmail = Utils.Transform.ToBool(config ["requiresUniqueEmail"] ?? "true"); string strPasswordFormat = Utils.Transform.ToString(config ["passwordFormat"], "Hashed"); switch (strPasswordFormat) { case "Clear": _passwordFormat = MembershipPasswordFormat.Clear; break; case "Encrypted": _passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Hashed": _passwordFormat = MembershipPasswordFormat.Hashed; break; default: ExceptionReporter.Throw("MEMBERSHIP", "BADPASSWORDFORMAT"); break; } base.Initialize(name, config); }