public bool AddUserToGroups(string username, List <byte> groupIDs) { using (CPSecurityEntities context = new CPSecurityEntities()) { foreach (var id in (groupIDs ?? new List <byte>()).Except(from m in context.SecurityGroupMemberships where m.UserName == username select m.GroupId)) { context.SecurityGroupMemberships.AddObject(new SecurityGroupMembership() { UserName = username, GroupId = id }); } try { context.SaveChanges(); return(true); } catch (ConstraintException) { return(false); } } }
/// <summary> /// Creates a new <see cref="CPUser"/> instance using C-Access Security profile data. /// </summary> /// <param name="profile">The profile to use.</param> /// <returns>A new C-Access user account instance using the specified C-Access Security profile data if valid; otherwise, null.</returns> public static CPUser CreateUser(SecurityUserProfile profile) { CPUser user = null; if (profile != null) { user = CreateUser(Membership.GetUser(profile.UserName)); if (user != null) { user.DisplayName = profile.DisplayName; user.Cid = profile.CandidateId; user.PasswordExpired = profile.PasswordExpired; // load additional user data user.ElectionCycles.AddRange(CPSecurity.Provider.GetAuthorizedElectionCycles(user.UserName)); user.ImplicitElectionCycles = !SecurityService.GetExplicitElectionCycles(user.UserName).Any(); user.UserRights = CPSecurity.Provider.GetUserRights(user.UserName); using (CPSecurityEntities context = new CPSecurityEntities()) { foreach (var app in context.SecuritySsoApplications) { if (user.UserRights.HasFlag((CPUserRights)app.UserRights)) { user.Applications.Add(ApplicationFactory.CreateApplication(app)); } } } // get CFIS source info user.SourceType = Enum.IsDefined(typeof(EntityType), profile.CfisType) ? (EntityType)profile.CfisType : EntityType.Generic; if (!string.IsNullOrWhiteSpace(profile.CfisCommitteeID)) { user.SourceCommitteeID = profile.CfisCommitteeID.ToCharArray()[0]; } byte liaisonID; if (byte.TryParse(profile.CfisCommitteeContactID, out liaisonID)) { user.SourceLiaisonID = liaisonID; // attempt to determine election cycle of associated committee if (user.SourceCommitteeID.HasValue) { char commID = user.SourceCommitteeID.Value; var elections = from ec in CPProviders.DataProvider.GetActiveElectionCycles(profile.CandidateId, CPProviders.SettingsProvider.MinimumElectionCycle) let comm = CPProviders.DataProvider.GetAuthorizedCommittees(profile.CandidateId, ec) where comm.Committees.ContainsKey(commID) select ec; if (elections.Any()) { user.SourceElectionCycle = elections.First(); } } } else { user.SourceElectionCycle = profile.CfisCommitteeContactID; } } } return(user); }
public bool RemoveUserFromGroups(string username, List <byte> groupIDs) { if (groupIDs == null || groupIDs.Count == 0) { return(true); } using (CPSecurityEntities context = new CPSecurityEntities()) { foreach (var m in from m in context.SecurityGroupMemberships where m.UserName == username && groupIDs.Contains(m.GroupId) select m) { context.DeleteObject(m); } try { context.SaveChanges(); return(true); } catch (ConstraintException) { return(false); } } }
public CPGroup UpdateGroup(CPGroup group) { if (group == null) { return(null); } using (CPSecurityEntities context = new CPSecurityEntities()) { var match = context.SecurityGroups.FirstOrDefault(g => g.GroupId == group.ID); if (match == null) { return(null); } match.GroupName = group.Name; match.UserRights = (int)group.UserRights; try { context.SaveChanges(); } catch (OptimisticConcurrencyException) { context.Refresh(RefreshMode.ClientWins, match); context.SaveChanges(); } catch (ConstraintException) { } return(GetGroup(match.GroupName)); } }
public bool ChangePassword(string username, string oldPassword, string newPassword) { MembershipUser user = Membership.GetUser(username); if (user != null && user.ChangePassword(oldPassword, newPassword)) { using (CPSecurityEntities context = new CPSecurityEntities()) { var match = context.SecurityUserProfiles.FirstOrDefault(p => p.UserName == username); if (match != null) { match.PasswordExpired = false; try { context.SaveChanges(); } catch (OptimisticConcurrencyException) { context.Refresh(RefreshMode.ClientWins, match); context.SaveChanges(); } } } return(true); } return(false); }
/// <summary> /// Gets a collection of all C-Access Security groups. /// </summary> /// <returns>A collection of all C-Access Security groups.</returns> public List <CPGroup> GetGroups() { using (CPSecurityEntities context = new CPSecurityEntities()) { return(context.SecurityGroups.AsEnumerable().Select(g => CPGroupFactory.CreateGroup(g)).ToList()); } }
/// <summary> /// Gets a C-Access Security group. /// </summary> /// <param name="groupName">The name of the group to retrieve.</param> /// <returns>The security group if found; otherwise, null.</returns> public CPGroup GetGroup(string groupName) { using (CPSecurityEntities context = new CPSecurityEntities()) { return(CPGroupFactory.CreateGroup(context.SecurityGroups.FirstOrDefault(g => g.GroupName == groupName))); } }
/// <summary> /// Creates a new login token for authenticating a specific user for a specific application. /// </summary> /// <param name="username">The login name of the user requesting authentication.</param> /// <param name="applicationID">The unique identifier of the application requesting authentication.</param> /// <returns>A new login token if the specified user has access to the specified application; otherwise, null.</returns> public Token CreateToken(string username, byte applicationID) { using (CPSecurityEntities context = new CPSecurityEntities()) { var app = context.SecuritySsoApplications.FirstOrDefault(a => a.ApplicationId == applicationID); if (app != null && HasUserRights(username, (CPUserRights)app.UserRights)) { SecuritySsoToken token = new SecuritySsoToken() { UserName = username, SecuritySsoApplication = app }; try { context.SecuritySsoTokens.AddObject(token); context.SaveChanges(); return(TokenFactory.CreateToken(token)); } catch { } } } return(null); }
/// <summary> /// Gets a C-Access user account. /// </summary> /// <param name="username">The login name for the account to retrieve.</param> /// <returns>The C-Access user account matching the specified username if found; otherwise, null.</returns> public CPUser GetUser(string username) { if (string.IsNullOrWhiteSpace(username)) { return(null); } username = username.Trim(); MembershipUser muser = Membership.GetUser(username); if (muser == null) { return(null); } username = muser.UserName; using (CPSecurityEntities context = new CPSecurityEntities()) { SecurityUserProfile profile = (from p in context.SecurityUserProfiles where p.UserName == username select p).FirstOrDefault(); // automatic legacy .NET Membership/SharePoint conversion if (profile == null) { profile = context.AddToSecurityUserProfiles(Membership.GetUser(username)); } return(CPUserFactory.CreateUser(profile)); } }
/// <summary> /// Gets information about a specific SSO-enabled application. /// </summary> /// <param name="applicationID">The unique identifier of the application.</param> /// <returns>The application requested if found; otherwise, null.</returns> public Application GetApplication(byte applicationID) { using (CPSecurityEntities context = new CPSecurityEntities()) { var app = context.SecuritySsoApplications.FirstOrDefault(a => a.ApplicationId == applicationID); return(ApplicationFactory.CreateApplication(app)); } }
/// <summary> /// Gets a collection of users who are members of the specified security group. /// </summary> /// <param name="groupName">The group to get the list of members for.</param> /// <returns>A collection of the names of all the users who are members of the specified security group.</returns> public List <string> GetGroupMembers(string groupName) { using (CPSecurityEntities context = new CPSecurityEntities()) { return((from m in context.SecurityGroupMemberships where m.SecurityGroup.GroupName == groupName select m.UserName).ToList()); } }
/// <summary> /// Gets the election cycles that a C-Access user account is explicitly authorized for. /// </summary> /// <param name="username">The C-Access user to query.</param> /// <returns>A collection of election cycles that the specified user is explicitly authorized to access.</returns> /// <remarks>Unrestricted users will result in an empty collection.</remarks> internal static List <string> GetExplicitElectionCycles(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { return((from o in context.SecurityUserElectionCycles where o.UserName == username select o.ElectionCycle).ToList()); } }
/// <summary> /// Gets the election cycles that a C-Access user account is authorized for. /// </summary> /// <param name="username">The C-Access user to query.</param> /// <returns>A collection of election cycles that the specified user is authorized to access.</returns> public List <string> GetAuthorizedElectionCycles(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { var cycles = GetExplicitElectionCycles(username); // cross reference against CFIS var active = Elections.GetActiveElectionCycles(GetCid(username)); return(cycles.Count() > 0 ? cycles.Intersect(active).ToList() : active.ToList()); } }
/// <summary> /// Gets a list of the groups that a user is in. /// </summary> /// <param name="username">The name of the user to return a list of groups for.</param> /// <returns>A collection containing the names of all the groups that the specified user is in.</returns> public List <CPGroup> GetGroupMembership(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { return((from g in context.SecurityGroups join m in context.SecurityGroupMemberships on g.GroupId equals m.GroupId where m.UserName == username select g).AsEnumerable().Select(g => CPGroupFactory.CreateGroup(g)).ToList()); } }
public bool DeleteUser(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { context.DeleteSecurityUserProfile(username); MembershipUser user = Membership.GetUser(username); if (user != null) { return(UserManagement.DeleteUser(user)); } return(UserManagement.DeleteUser(Membership.GetUser(username))); } }
/// <summary> /// Gets the friendly display name for a C-Access user account. /// </summary> /// <param name="username">The C-Access user to query.</param> /// <returns>The user friendly display name (e.g., full name) on record for the specified user.</returns> public string GetDisplayName(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { var match = from p in context.SecurityUserProfiles where p.UserName == username select p.DisplayName; if (match.Count() > 0) { return(match.First()); } CPUser user = GetUser(username); return(user == null ? null : user.DisplayName); } }
/// <summary> /// Gets a <see cref="CPUserRights"/> value that represents the access rights granted to the specified user. /// </summary> /// <param name="username">The name of the user to get access rights for.</param> /// <returns>A <see cref="CPUserRights"/> value indicating the total access rights granted to the specified user.</returns> public CPUserRights GetUserRights(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { CPUserRights rights = CPUserRights.None; var groupRights = from m in context.SecurityGroupMemberships where m.UserName == username select(CPUserRights) m.SecurityGroup.UserRights; foreach (var right in groupRights) { rights |= right; } return(CPSecurity.Sanitize(rights)); } }
/// <summary> /// Gets the candidate ID associated with a C-Access user account. /// </summary> /// <param name="username">The name of the user to query.</param> /// <returns>The candidate ID associated with the specified user.</returns> public string GetCid(string username) { using (CPSecurityEntities context = new CPSecurityEntities()) { var match = from p in context.SecurityUserProfiles where p.UserName == username select p.CandidateId; if (match.Count() > 0) { return(match.First()); } // attempt to convert legacy data var profile = context.AddToSecurityUserProfiles(Membership.GetUser(username)); return(profile == null ? null : profile.CandidateId); } }
/// <summary> /// Deletes a security user profile from the datastore. /// </summary> /// <param name="context">The datastore entity context to use.</param> /// <param name="username">The username of the profile to delete.</param> public static void DeleteSecurityUserProfile(this CPSecurityEntities context, string username) { var match = context.SecurityUserProfiles.FirstOrDefault(p => p.UserName == username); if (match != null) { try { context.DeleteObject(match); context.SaveChanges(); } catch (OptimisticConcurrencyException) { context.Refresh(RefreshMode.ClientWins, match); context.DeleteObject(match); } } }
/// <summary> /// Creates a new security user profile entity instance from a membership user and adds it to the datastore. /// </summary> /// <param name="context">The datastore entity context to use.</param> /// <param name="user">The membership user to convert and add.</param> /// <returns>A <see cref="SecurityUserProfile"/> instance representing the newly created profile that has been added to the datastore.</returns> public static SecurityUserProfile AddToSecurityUserProfiles(this CPSecurityEntities context, MembershipUser user) { if (user == null) { return(null); } string username = user.UserName; string caid = UserManagement.GetCaid(username); SecurityUserProfile profile = context.AddToSecurityUserProfiles(username, UserManagement.GetCfisId(username), UserManagement.GetFullName(user), AccountAnalysis.ParseEntityType(caid), AccountAnalysis.ParseCommitteeID(caid), AccountAnalysis.ParseElectionCycle(caid), AccountAnalysis.ParseLiaisonID(caid), UserManagement.IsPasswordExpired(user)); return(profile); }
/// <summary> /// Adds a new security user profile entity instance to the datastore. /// </summary> /// <param name="context">The datastore entity context to use.</param> /// <param name="username">The username for the new profile.</param> /// <param name="candidateID">The candidate ID for the new profile.</param> /// <param name="displayName">The display name for the profile.</param> /// <param name="type">The entity type of the CFB-registered contact used to create the profile.</param> /// <param name="committeeID">If not representing a candidate, the ID of the profile's committee.</param> /// <param name="electionCycle">If representing a treasurer, the election cycle for which the profile's committee is authorized.</param> /// <param name="liaisonID">If representing a liaison, the committee-relative liaison ID of the profile.</param> /// <param name="passwordExpired">Indicates whether or not the password on the newly created profile is to be expired.</param> /// <returns>A <see cref="SecurityUserProfile"/> instance representing the newly created profile that has been added to the datastore.</returns> public static SecurityUserProfile AddToSecurityUserProfiles(this CPSecurityEntities context, string username, string candidateID, string displayName = null, EntityType type = EntityType.Generic, char?committeeID = null, string electionCycle = null, byte?liaisonID = null, bool passwordExpired = true) { if (context == null || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(candidateID)) { return(null); } SecurityUserProfile profile = SecurityUserProfile.CreateSecurityUserProfile(username, candidateID, passwordExpired, (byte)type); profile.DisplayName = displayName; if (committeeID.HasValue) { profile.CfisCommitteeID = committeeID.Value.ToString(); } profile.CfisCommitteeContactID = liaisonID.HasValue ? liaisonID.Value.ToString() : electionCycle; context.SecurityUserProfiles.AddObject(profile); context.SaveChanges(); return(profile); }
/// <summary> /// Checks whether or not a login token exists and is valid for authentication. /// </summary> /// <param name="tokenID">The unique identifier of the token to validate.</param> /// <returns>The login name of the user attempting to authenticate with the specified token, if valid; otherwise, null.</returns> /// <remarks>The login token is automatically discarded once validated.</remarks> public string ValidateToken(Guid tokenID) { string username = null; if (tokenID != null) { using (CPSecurityEntities context = new CPSecurityEntities()) { var token = context.SecuritySsoTokens.FirstOrDefault(t => t.TokenId == tokenID); if (token != null) { if (DateTime.Now <= token.Created.Add(Properties.Settings.Default.TokenValidationWindow)) { username = token.UserName; } context.DeleteObject(token); context.SaveChanges(); } } } return(username); }
public CPGroup CreateGroup(string groupName) { using (CPSecurityEntities context = new CPSecurityEntities()) { if (!context.SecurityGroups.Any(g => g.GroupName == groupName)) { SecurityGroup group = new SecurityGroup() { GroupName = groupName }; try { context.SecurityGroups.AddObject(group); context.SaveChanges(); return(CPGroupFactory.CreateGroup(group)); } catch (ConstraintException) { } } } return(null); }
public bool DeleteGroup(string groupName) { using (CPSecurityEntities context = new CPSecurityEntities()) { var match = context.SecurityGroups.FirstOrDefault(g => g.GroupName == groupName); if (match == null) { return(true); } context.DeleteObject(match); try { return(context.SaveChanges() > 0); } catch (OptimisticConcurrencyException) { return(false); } catch (ConstraintException) { return(false); } } }
public CPUser CreateUser(string firstName, char?middleInitial, string lastName, string candidateID, string password, string email, string creator, EntityType type = EntityType.Generic, char?committeeID = null, string electionCycle = null, byte?liaisonID = null, string username = null) { if (username == null) { username = GenerateUserName(firstName, middleInitial, lastName, candidateID); } if (!string.IsNullOrWhiteSpace(username)) { if (password == null) { password = Membership.GeneratePassword(10, 0); } if (UserManagement.CreateUser(username, password, email, creator) != null) { using (CPSecurityEntities context = new CPSecurityEntities()) { switch (type) // sanitize CFIS source entity properties first { case EntityType.Liaison: electionCycle = null; break; case EntityType.Treasurer: liaisonID = null; break; default: committeeID = null; electionCycle = null; liaisonID = null; break; } context.DeleteSecurityUserProfile(username); CPUser user = CPUserFactory.CreateUser(context.AddToSecurityUserProfiles(username, candidateID, Entity.ToFullName(firstName, lastName, middleInitial, false), type, committeeID, electionCycle, liaisonID)); if (user != null) { CPGroup group = GetGroup(type.ToString() + "s"); if (group != null) { AddUserToGroups(user.UserName, new List <byte>(new[] { group.ID })); } if (electionCycle != null) { user.ElectionCycles.Add(electionCycle); } if (!user.Save()) { this.DeleteUser(user.UserName); user = null; } } else { UserManagement.DeleteUser(Membership.GetUser(username)); } return(user); } } } return(null); }
public UpdateResult UpdateUser(CPUser user) { UpdateResultState state = UpdateResultState.Success; // .NET Membership properties MembershipUser muser = user == null ? null : Membership.GetUser(user.UserName); if (muser == null) { state |= UpdateResultState.MembershipUserNotFound; } else { bool dirty = false; if (muser.Email != user.Email) { muser.Email = user.Email; dirty = true; } if (muser.IsApproved != user.Enabled) { muser.IsApproved = user.Enabled; dirty = true; } if (muser.IsLockedOut && !user.LockedOut) { muser.UnlockUser(); dirty = true; } if (dirty) { try { Membership.UpdateUser(muser); } catch { state |= UpdateResultState.AspNetMembershipFailure; } } // C-Access Security using (CPSecurityEntities context = new CPSecurityEntities()) { var match = context.SecurityUserProfiles.FirstOrDefault(u => u.UserName == user.UserName); if (match == null) { state |= UpdateResultState.ProfileNotFound; } else { // basic properties match.CandidateId = user.Cid; match.DisplayName = user.DisplayName; match.CfisType = (byte)user.SourceType; match.CfisCommitteeID = user.SourceCommitteeID.HasValue ? user.SourceCommitteeID.Value.ToString() : null; match.CfisCommitteeContactID = user.SourceLiaisonID.HasValue ? user.SourceLiaisonID.Value.ToString() : user.SourceElectionCycle; // election cycles var currentCycles = context.SecurityUserElectionCycles.Where(c => c.UserName == user.UserName); var updateCycles = user.ElectionCycles; if (user.ImplicitElectionCycles == updateCycles.Any()) // implicit EC access requires both an empty EC collection AND a set flag { state |= UpdateResultState.ElectionCycleNotFound; } else { // delete old cycles foreach (var cycle in currentCycles.Where(c => !updateCycles.Contains(c.ElectionCycle))) { context.SecurityUserElectionCycles.DeleteObject(cycle); } // add new cycles foreach (var cycle in updateCycles.Except(currentCycles.Select(c => c.ElectionCycle))) { context.SecurityUserElectionCycles.AddObject(SecurityUserElectionCycle.CreateSecurityUserElectionCycle(user.UserName, cycle)); } } // save changes try { context.SaveChanges(); } catch (OptimisticConcurrencyException) { context.Refresh(RefreshMode.ClientWins, match); context.SaveChanges(); } catch (ConstraintException) { state |= UpdateResultState.ProfileFailure; } } } } return(new UpdateResult(GetUser(user.UserName), state)); }