// RoleProvider.AddUsersToRoles public override void AddUsersToRoles(string[] usernames, string[] rolenames) { foreach (string rolename in rolenames) { if (!RoleExists(rolename)) { throw new ProviderException("Role name not found."); } } foreach (string username in usernames) { if (username.Contains(",")) { throw new ArgumentException("User names cannot contain commas."); } foreach (string rolename in rolenames) { if (IsUserInRole(username, rolename)) { throw new ProviderException("User is already in role."); } } } using (var db = new SecurityEntities()) { var users = db.Users.Where(u => u.Application.ApplicationName == Membership.ApplicationName && usernames.Contains(u.UserName)).ToList(); var roles = db.Roles.Where(r => r.Application.ApplicationName == ApplicationName && rolenames.Contains(r.RoleName)).ToList(); roles.ForEach(r => users.ForEach(u => db.UserInRoles.Add(new UserInRole { Users = u, Roles = r }))); if (db.SaveChanges() > 0) { addUserToRoleStatus = true; } else { addUserToRoleStatus = false; } } }
// // ProfileProvider.DeleteInactiveProfiles // public override int DeleteInactiveProfiles( ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { using (var db = new SecurityEntities()) { IEnumerable<Profiles> profiles; profiles = db.Profiles.Where(p => p.User.Application.ApplicationName == Membership.ApplicationName && p.LastActivityDate <= userInactiveSinceDate); switch (authenticationOption) { case ProfileAuthenticationOption.Anonymous: profiles = profiles.Where(p => p.IsAnonymous != 0); break; case ProfileAuthenticationOption.Authenticated: profiles = profiles.Where(p => p.IsAnonymous == 0); break; default: break; } return DeleteProfiles(profiles.Select(p => p.User.UserName).ToArray()); } }
// // GetProfileInfo // Retrieves a count of profiles and creates a // ProfileInfoCollection from the profile data in the // database. Called by GetAllProfiles, GetAllInactiveProfiles, // FindProfilesByUserName, FindInactiveProfilesByUserName, // and GetNumberOfInactiveProfiles. // Specifying a pageIndex of 0 retrieves a count of the results only. // private ProfileInfoCollection GetProfileInfo( ProfileAuthenticationOption authenticationOption, string usernameToMatch, object userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { using (var db = new SecurityEntities()) { IEnumerable<Profiles> profileList; profileList = db.Profiles.Where(p => p.User.Application.ApplicationName == Membership.ApplicationName && usernameToMatch != null ? p.User.UserName == usernameToMatch : true && userInactiveSinceDate != null ? p.LastActivityDate <= (DateTime)userInactiveSinceDate : true); switch (authenticationOption) { case ProfileAuthenticationOption.Anonymous: profileList = profileList.Where(p => p.IsAnonymous != 0); break; case ProfileAuthenticationOption.Authenticated: profileList = profileList.Where(p => p.IsAnonymous == 0); break; default: break; } ProfileInfoCollection profiles = new ProfileInfoCollection(); totalRecords = profileList.Count(); // No profiles found. if (totalRecords <= 0) { return profiles; } // Count profiles only. if (pageSize == 0) { return profiles; } int startIndex = pageSize * pageIndex; profileList.Skip(startIndex).Take(pageSize).Select(p => new ProfileInfo( p.User.UserName, p.IsAnonymous != 0, p.LastActivityDate, p.LastUpdatedDate, 0)).ToList().ForEach(p => profiles.Add(p)); return profiles; } }
// MembershipProvider.ValidateUser public override bool ValidateUser(string username, string password) { bool isValid = false; bool isApproved = false; string pwd = ""; using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username && !u.IsLockedOut); if (user != null) { pwd = user.Password; isApproved = user.IsApproved; } else return false; if (CheckPassword(password, pwd)) { if (isApproved) { isValid = true; user.LastLoginDate = DateTime.Now; db.SaveChanges(); } } else UpdateFailureCount(username, "password"); return isValid; } }
// MembershipProvider.UnlockUser public override bool UnlockUser(string username) { using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); user.IsLockedOut = false; user.LastLockoutDate = DateTime.Now; if (db.SaveChanges() > 0) return true; } return false; }
// MembershipProvider.GetUserNameByEmail public override string GetUserNameByEmail(string email) { string username = ""; using (var db = new SecurityEntities()) { username = db.Users.Where(u => u.Application.ApplicationName == pApplicationName && u.Email == email) .Select(u => u.UserName).FirstOrDefault(); } if (username == null) username = ""; return username; }
// MembershipProvider.GetPassword public override string GetPassword(string username, string answer) { if (!EnablePasswordRetrieval) { throw new ProviderException("Password Retrieval Not Enabled."); } if (PasswordFormat == MembershipPasswordFormat.Hashed) { throw new ProviderException("Cannot retrieve Hashed passwords."); } string password = ""; string passwordAnswer = ""; using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); if (user != null) { if (user.IsLockedOut) throw new MembershipPasswordException("The supplied user is locked out."); password = user.Password; passwordAnswer = user.PasswordAnswer; } else throw new MembershipPasswordException("The supplied user name is not found."); } if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer)) { UpdateFailureCount(username, "passwordAnswer"); throw new MembershipPasswordException("Incorrect password answer."); } if (PasswordFormat == MembershipPasswordFormat.Encrypted) { password = UnEncodePassword(password); } return password; }
// MembershipProvider.GetAllUsers public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { totalRecords = 0; MembershipUserCollection users = new MembershipUserCollection(); using (var db = new SecurityEntities()) { var allUser = db.Users.Where(u => u.Application.ApplicationName == pApplicationName) .OrderBy(u => u.UserName); totalRecords = allUser.Count(); if (!allUser.Any()) return users; int startIndex = pageSize * pageIndex; allUser.Skip(startIndex).Take(pageSize).Select(u => new MembershipUser( this.Name, u.UserName, u.UserId, u.Email, u.PasswordQuestion, u.Comment, u.IsApproved, u.IsLockedOut, u.CreateDate, u.LastLoginDate, u.LastActivityDate, u.LastPasswordChangedDate, u.LastLockoutDate)).ToList().ForEach(u => users.Add(u)); } return users; }
// MembershipProvider.CreateUser public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true); OnValidatingPassword(args); if (args.Cancel) { status = MembershipCreateStatus.InvalidPassword; return null; } if (RequiresUniqueEmail && GetUserNameByEmail(email) != "") { status = MembershipCreateStatus.DuplicateEmail; return null; } MembershipUser u = GetUser(username, false); if (u == null) { DateTime createDate = DateTime.Now; int passwordFormat; switch (pPasswordFormat) { case MembershipPasswordFormat.Clear: passwordFormat = 0; break; case MembershipPasswordFormat.Encrypted: passwordFormat = 2; break; case MembershipPasswordFormat.Hashed: passwordFormat = 1; break; default: passwordFormat = 0; break; } using (var db = new SecurityEntities()) { var app = db.Applications.SingleOrDefault(a => a.ApplicationName == pApplicationName); var user = new Users { UserName = username, LoweredUserName = username.ToLower(), Password = EncodePassword(password), Email = email, PasswordFormat = passwordFormat, PasswordQuestion = passwordQuestion, PasswordAnswer = EncodePassword(passwordAnswer), IsApproved = isApproved, CreateDate = createDate, IsLockedOut = false, LastLockoutDate = createDate, FailedPasswordAttemptCount = 0, FailedPasswordAttemptWindowStart = createDate, FailedPasswordAnswerAttemptCount = 0, FailedPasswordAnswerAttemptWindowStart = createDate, LastActivityDate = System.DateTime.Now, LastLoginDate = System.DateTime.Now, LastPasswordChangedDate = System.DateTime.Now, ApplicationId = app.ApplicationId }; db.Users.Add(user); status = MembershipCreateStatus.Success; if (db.SaveChanges() > 0) status = MembershipCreateStatus.Success; else status = MembershipCreateStatus.UserRejected; } return GetUser(username, false); } else { status = MembershipCreateStatus.DuplicateUserName; } return null; }
// RoleProvider.GetAllRoles public override string[] GetAllRoles() { using (var db = new SecurityEntities()) { string[] allRoles = db.Roles.Where(r => r.Application.ApplicationName == ApplicationName).Select(r => r.RoleName).ToArray(); return allRoles; } }
// RoleProvider.FindUsersInRole public override string[] FindUsersInRole(string rolename, string usernameToMatch) { using (var db = new SecurityEntities()) { string[] usersInRole = db.Roles.Single(r => r.Application.ApplicationName == ApplicationName && r.RoleName == rolename).UserInRoles .Select(ur => ur.Users).Where(u => u.UserName == usernameToMatch) .Select(u => u.UserName) .ToArray(); return usersInRole; } }
// RoleProvider.DeleteRole public override bool DeleteRole(string rolename, bool throwOnPopulatedRole) { if (!RoleExists(rolename)) { throw new ProviderException("Role does not exist."); } if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0) { throw new ProviderException("Cannot delete a populated role."); } using (var db = new SecurityEntities()) { var role = db.Roles.SingleOrDefault(r => r.Application.ApplicationName == ApplicationName && r.RoleName == rolename); db.Roles.Remove(role); if (db.SaveChanges() > 0) return true; } return false; }
// // UpdateActivityDates // Updates the LastActivityDate and LastUpdatedDate values // when profile properties are accessed by the // GetPropertyValues and SetPropertyValues methods. // Passing true as the activityOnly parameter will update // only the LastActivityDate. // private void UpdateActivityDates(string username, bool isAuthenticated, bool activityOnly) { using (var db = new SecurityEntities()) { var profiles = db.Profiles.Where(p => p.User.Application.ApplicationName == Membership.ApplicationName && p.User.UserName == username && p.IsAnonymous == (isAuthenticated ? 0 : 1)) .ToList(); if (activityOnly) { profiles.ForEach(p => p.LastActivityDate = DateTime.Now); } else { profiles.ForEach(p => { p.LastActivityDate = DateTime.Now; p.LastUpdatedDate = DateTime.Now; }); } db.SaveChanges(); } }
// // SetFriendlyName // Inserts FriendlyName values into the database during // the call to SetPropertyValues. // private void SetFriendlyName(int uniqueID, string friendlyName) { using (var db = new SecurityEntities()) { db.ProfileValues.Where(p => p.UserId == uniqueID).ToList().ForEach(p => db.ProfileValues.Remove(p)); var profile = db.Profiles.SingleOrDefault(p => p.UserId == uniqueID); db.ProfileValues.Add(new FriendlyName { Profiles = profile, PropertyValue = friendlyName }); db.SaveChanges(); } }
// // GetUniqueID // Retrieves the uniqueID from the database for the current user and application. // private int GetUniqueID(string username, bool isAuthenticated, bool ignoreAuthenticationType) { int uniqueID = 0; using (var db = new SecurityEntities()) { if (ignoreAuthenticationType) uniqueID = db.Profiles.Where(p => p.User.Application.ApplicationName == Membership.ApplicationName && p.User.UserName == username) .Select(p => p.UserId) .FirstOrDefault(); else uniqueID = db.Profiles.Where(p => p.User.Application.ApplicationName == Membership.ApplicationName && p.User.UserName == username && p.IsAnonymous == (isAuthenticated ? 0 : 1)) .Select(p => p.UserId) .FirstOrDefault(); return uniqueID; } }
// MembershipProvider.ChangePassword public override bool ChangePassword(string username, string oldPwd, string newPwd) { if (!ValidateUser(username, oldPwd)) return false; ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPwd, true); OnValidatingPassword(args); if (args.Cancel) if (args.FailureInformation != null) throw args.FailureInformation; else throw new MembershipPasswordException("Change password canceled due to new password validation failure."); using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); user.Password = EncodePassword(newPwd); user.LastPasswordChangedDate = DateTime.Now; if (db.SaveChanges() > 0) return true; } return false; }
// MembershipProvider.ChangePasswordQuestionAndAnswer public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPwdQuestion, string newPwdAnswer) { if (!ValidateUser(username, password)) return false; using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); user.PasswordQuestion = newPwdQuestion; user.PasswordAnswer = EncodePassword(newPwdAnswer); if (db.SaveChanges() > 0) return true; } return false; }
// RoleProvider.GetRolesForUser public override string[] GetRolesForUser(string username) { using (var db = new SecurityEntities()) { string[] rolesForUser = db.Users.Single(u => u.Application.ApplicationName == Membership.ApplicationName && u.UserName == username).UserInRoles .Select(ur => ur.Roles.RoleName).ToArray(); return rolesForUser; } }
// MembershipProvider.DeleteUser public override bool DeleteUser(string username, bool deleteAllRelatedData) { using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); db.Users.Remove(user); if (deleteAllRelatedData) { // Process commands to delete all data for the user in the database. } db.SaveChanges(); if (db.SaveChanges() > 0) return true; } return false; }
//RoleProvider.GetUsersInRole public override string[] GetUsersInRole(string rolename) { using (var db = new SecurityEntities()) { string[] usersInRole = db.Roles.Single(r => r.Application.ApplicationName == ApplicationName && r.RoleName == rolename).UserInRoles .Select(ur => ur.Users.UserName) .ToArray(); return usersInRole; } }
// MembershipProvider.GetNumberOfUsersOnline public override int GetNumberOfUsersOnline() { TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0); DateTime compareTime = DateTime.Now.Subtract(onlineSpan); using (var db = new SecurityEntities()) { return db.Users.Where(u => u.Application.ApplicationName == pApplicationName && u.LastActivityDate > compareTime) .Count(); } }
//RoleProvider.IsUserInRole public override bool IsUserInRole(string username, string rolename) { using (var db = new SecurityEntities()) { var userInRole = db.UserInRoles.Where(ur => ur.Users.Application.ApplicationName == Membership.ApplicationName && ur.Users.UserName == username && ur.Roles.RoleName == rolename); if (userInRole.Any()) return true; return false; } }
// MembershipProvider.GetUser(object, bool) public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { MembershipUser mu = null; using (var db = new SecurityEntities()) { var user = db.Users.Where(u => u.UserId == (int)providerUserKey).FirstOrDefault(); if (user != null) { mu = new MembershipUser( this.Name, user.UserName, user.UserId, user.Email, user.PasswordQuestion, user.Comment, user.IsApproved, user.IsLockedOut, user.CreateDate, user.LastLoginDate, user.LastActivityDate, user.LastPasswordChangedDate, user.LastLockoutDate); } if (userIsOnline) { user.LastActivityDate = DateTime.Now; db.SaveChanges(); } } return mu; }
//RoleProvider.RemoveUsersFromRoles public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames) { foreach (string rolename in rolenames) { if (!RoleExists(rolename)) { throw new ProviderException("Role name not found."); } } foreach (string username in usernames) { foreach (string rolename in rolenames) { if (!IsUserInRole(username, rolename)) { throw new ProviderException("User is not in role."); } } } using (var db = new SecurityEntities()) { db.UserInRoles.Where(ur => usernames.Contains(ur.Users.UserName) && rolenames.Contains(ur.Roles.RoleName)).ToList().ForEach(ur => db.UserInRoles.Remove(ur)); db.SaveChanges(); } }
// MembershipProvider.ResetPassword public override string ResetPassword(string username, string answer) { if (!EnablePasswordReset) { throw new NotSupportedException("Password reset is not enabled."); } if (answer == null && RequiresQuestionAndAnswer) { UpdateFailureCount(username, "passwordAnswer"); throw new ProviderException("Password answer required for password reset."); } string newPassword = System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters); ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(args); if (args.Cancel) if (args.FailureInformation != null) throw args.FailureInformation; else throw new MembershipPasswordException("Reset password canceled due to password validation failure."); string passwordAnswer = ""; using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); passwordAnswer = user.PasswordAnswer; if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer)) { UpdateFailureCount(username, "passwordAnswer"); throw new MembershipPasswordException("Incorrect password answer."); } user.Password = EncodePassword(newPassword); user.LastPasswordChangedDate = DateTime.Now; if (db.SaveChanges() > 0) return newPassword; else throw new MembershipPasswordException("User not found, or user is locked out. Password not Reset."); } }
// RoleProvider.RoleExists public override bool RoleExists(string rolename) { using (var db = new SecurityEntities()) { var role = db.Roles.Where(r => r.Application.ApplicationName == ApplicationName && r.RoleName == rolename); if (role.Any()) return true; } return false; }
// MembershipProvider.UpdateUser public override void UpdateUser(MembershipUser user) { using (var db = new SecurityEntities()) { var mu = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == user.UserName); mu.Email = user.Email; mu.Comment = user.Comment; mu.IsApproved = user.IsApproved; db.SaveChanges(); } }
// RoleProvider.CreateRole public override void CreateRole(string rolename) { if (rolename.Contains(",")) { throw new ArgumentException("Role names cannot contain commas."); } if (RoleExists(rolename)) { throw new ProviderException("Role name already exists."); } using (var db = new SecurityEntities()) { var app = db.Applications.SingleOrDefault(a => a.ApplicationName == ApplicationName); var role = new UniCloud.Security.Models.Roles { RoleName = rolename, Application = app }; db.Roles.Add(role); app.FunctionItems.ToList().ForEach(f => db.FunctionsInRoles.Add(new FunctionsInRoles { Role = role, FunctionItem = f })); if (db.SaveChanges() > 0) { creatRoleStatus = true; } else { creatRoleStatus = false; } } }
// UpdateFailureCount // A helper method that performs the checks and updates associated with // password failure tracking. private void UpdateFailureCount(string username, string failureType) { DateTime windowStart = new DateTime(); int failureCount = 0; using (var db = new SecurityEntities()) { var user = db.Users.SingleOrDefault(u => u.Application.ApplicationName == pApplicationName && u.UserName == username); if (user != null) { if (failureType == "password") { failureCount = user.FailedPasswordAttemptCount; windowStart = user.FailedPasswordAttemptWindowStart; } if (failureType == "passwordAnswer") { failureCount = user.FailedPasswordAnswerAttemptCount; windowStart = user.FailedPasswordAnswerAttemptWindowStart; } } DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow); if (failureCount == 0 || DateTime.Now > windowEnd) { if (failureType == "password") { user.FailedPasswordAttemptCount = 1; user.FailedPasswordAttemptWindowStart = DateTime.Now; } if (failureType == "passwordAnswer") { user.FailedPasswordAnswerAttemptCount = 1; user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now; } db.SaveChanges(); } else { if (failureCount++ >= MaxInvalidPasswordAttempts) { user.IsLockedOut = true; user.LastLockoutDate = DateTime.Now; db.SaveChanges(); } else { if (failureType == "password") user.FailedPasswordAttemptCount = failureCount; if (failureType == "passwordAnswer") user.FailedPasswordAnswerAttemptCount = failureCount; db.SaveChanges(); } } } }
// // GetFriendlyName // Retrieves FriendlyName from the database during the call to GetPropertyValues. // private string GetFriendlyName(string username, bool isAuthenticated) { using (var db = new SecurityEntities()) { return db.ProfileValues.OfType<FriendlyName>().Where(p => p.Profiles.User.Application.ApplicationName == Membership.ApplicationName && p.Profiles.User.UserName == username && p.Profiles.IsAnonymous == (isAuthenticated ? 0 : 1)) .Select(p => p.PropertyValue).FirstOrDefault(); } }