/// <summary> /// Initializes a new instance of the <see cref="AccountEligibilityStatus"/> class. /// </summary> /// <param name="entity">The entity attributed with status <paramref name="eligibility"/>.</param> /// <param name="eligibility">The eligiblity status of <paramref name="entity"/>.</param> /// <param name="user">The user that matches <paramref name="entity"/>.</param> /// <param name="contactID">The contact ID of <paramref name="entity"/>.</param> public AccountEligibilityStatus(Entity entity, AccountEligibility eligibility, CPUser user = null, string contactID = null) { this.Entity = entity; this.Status = eligibility; this.MatchedUser = user; this.ContactID = contactID; }
/// <summary> /// Creats a new <see cref="CPUser"/> instance using .NET Membership data. /// </summary> /// <param name="user">The membership user to use.</param> /// <returns>A new C-Access user account instance using .NET Membership data if valid; otherwise, null.</returns> public static CPUser CreateUser(MembershipUser user) { if (user == null) { return(null); } DateTime creationDate = user.CreationDate; CPUser cpuser = new CPUser(user.UserName) { Email = user.Email, Enabled = user.IsApproved, LockedOut = user.IsLockedOut, CreationDate = creationDate }; if (user.LastActivityDate != creationDate) { cpuser.LastActivityDate = user.LastActivityDate; } if (user.LastLockoutDate != creationDate) { cpuser.LastLockoutDate = user.LastLockoutDate; } if (user.LastLoginDate != creationDate) { cpuser.LastLoginDate = user.LastLoginDate; } if (user.LastPasswordChangedDate != creationDate) { cpuser.LastPasswordChangedDate = user.LastPasswordChangedDate; } return(cpuser); }
/// <summary> /// Attempts to display a C-Access user in a new <see cref="UserAccountForm"/>. /// </summary> /// <param name="username">The username of the account to display.</param> private void ShowUserAccount(string username) { this.Cursor = Cursors.WaitCursor; new MethodInvoker(() => { CPUser user = CPSecurity.Provider.GetUser(username); this.BeginInvoke(new MethodInvoker(() => { try { if (user == null) { MessageBox.Show(this, string.Format("User \"{0}\" could not be found.", username), "User Not Found!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { UserAccountForm.ShowExistingAccountForm(user, this.MdiParent); } } finally { this.Cursor = Cursors.Default; } })); }).BeginInvoke(null, null); }
/// <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); }
/// <summary> /// Gets a <see cref="MailAddress"/> for contacting a user account via e-mail. /// </summary> /// <param name="user">The C-Access user to contact.</param> /// <returns>A <see cref="MailAddress"/> suitable for contating the user account specified via e-mail.</returns> /// <exception cref="ArgumentNullException"><paramref name="user"/> is null.</exception> public MailAddress GetMailAddress(CPUser user) { if (user == null) { throw new ArgumentNullException("user", "User must not be null."); } return(new MailAddress(user.Email, user.DisplayName, this.BodyEncoding)); }
private static CampaignContactViewModel CampaignContactFrom(CPUser source) { return(source == null ? new CampaignContactViewModel() : new CampaignContactViewModel { FullName = source.DisplayName, Email = source.Email, Reason = string.Format("Existing User ({0})", source.Email) }); }
/// <summary> /// Creates a user account form for displaying an existing user account. /// </summary> /// <param name="user">The user to display.</param> /// <returns>A <see cref="UserAccountForm"/> purposed for displaying user <paramref name="user"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="user"/> is null.</exception> public static UserAccountForm CreateExistingAccountForm(CPUser user) { if (user == null) { throw new ArgumentNullException("user", "User cannot be null."); } UserAccountForm form = new UserAccountForm(); form.SetUser(user); return(form); }
/// <summary> /// Factory method for creating a <see cref="ReportableUser"/> object for use in reports. /// </summary> /// <param name="user">The source <see cref="CPUser"/> to create from.</param> /// <param name="candidateName">The name of the candidate with whom the user is associated.</param> /// <returns>A reportable user object representing the specified user.</returns> public static ReportableUser CreateReportableUser(CPUser user, string candidateName) { return(user == null ? new ReportableUser() : new ReportableUser() { Cid = user.Cid, CandidateName = candidateName, UserName = user.UserName, DisplayName = user.DisplayName, Email = user.Email, LoginDate = user.LastLoginDate, LockedOut = user.LockedOut ? "Yes" : "No", Disabled = user.Enabled ? "No" : "Yes" }); }
/// <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> /// Shows a form for displaying an existing user account. /// </summary> /// <param name="user">The user to display.</param> /// <param name="owner">The existing form that should own the new form.</param> public static void ShowExistingAccountForm(CPUser user, Form owner = null) { if (owner != null) { // find already-open form and, if found, show that instead of a new one var existing = (from f in owner.OwnedForms where f is UserAccountForm && f.Tag is CPUser && ((CPUser)f.Tag).UserName == user.UserName select f).FirstOrDefault(); if (existing != null) { existing.BringToFront(); return; } } UserAccountForm.CreateExistingAccountForm(user).ShowAsOwnedBy(owner); }
/// <summary> /// Evaluates the current HTTP web session for pit stop conditions and executes them if found. /// </summary> /// <param name="username">The name of the current user.</param> /// <param name="context">The <see cref="HttpContext"/> to examine.</param> public static void CheckPitStops(this HttpContext context, string username = null) { if (username == null) { username = context.User.Identity.Name; } CPUser user = CPSecurity.Provider.GetUser(username); if (user != null && user.PasswordExpired && !PageUrlManager.ChangePasswordPageUrl.Equals(context.Request.Path, StringComparison.CurrentCultureIgnoreCase)) { context.Response.Pit(PageUrlManager.ChangePasswordPageUrl); } // redirection check for CMO settings, disabled pending policy change //else if ((CmoSettings.GetSettings(UserManagement.GetCfisId(context.User.Identity.Name)) == null) && !Properties.Settings.Default.ChangeCmoSettingsPage.Equals(context.Request.Path)) // Pit(context, Properties.Settings.Default.ChangeCmoSettingsPage); }
/// <summary> /// Sends an e-mail notification of a password reset to a user. /// </summary> /// <param name="recipient">The user whose password is being reset.</param> /// <param name="password">The user's new password.</param> /// <exception cref="ArgumentNullException"><paramref name="recipient"/> or <paramref name="password"/> is null.</exception> public static void Send(CPUser recipient, SecureString password) { if (recipient == null) { throw new ArgumentNullException("recipient", "Password reset message recipient cannot be null."); } if (password == null) { throw new ArgumentNullException("password", "Password cannot be null."); } using (CPMailMessage message = new CPMailMessage() { Recipient = new MailAddress(recipient.Email, recipient.DisplayName), Subject = CPProviders.SettingsProvider.ApplicationName + @" Username/Password Reset", Body = string.Format(MessageBodyFormat, recipient.DisplayName, CPProviders.SettingsProvider.AgencyName, CPProviders.SettingsProvider.ApplicationName, CPProviders.SettingsProvider.ApplicationUrl, recipient.UserName, password.Decrypt(), CPProviders.SettingsProvider.AgencyPhoneNumber) }) { message.Send(); message.Body.Remove(0); } }
/// <summary> /// Attempts to look up a user by email address and associated candidate ID and reset that user's password. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An <see cref="EventArgs"/> object that contains the event data.</param> protected void OnSubmit(object sender, EventArgs e) { string email = _email.Text.Trim(); string cid = _cid.Text.Trim(); if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(cid)) { return; } // try to find user CPUser user = CPSecurity.Provider.GetCampaignUsers(cid).FirstOrDefault(u => string.Equals(email, u.Email, StringComparison.InvariantCultureIgnoreCase)); if (user == null) { _errorMessage.Visible = true; return; } // check for deactivated account if (!user.Enabled) { _deactivatedMessage.Visible = true; return; } // reset password if (!CPSecurity.Provider.ResetPassword(user.UserName)) { Server.Transfer(PageUrlManager.ErrorPageUrl); } else { _resetPasswordPanel.Visible = false; _errorMessage.Visible = false; _successMessage.Visible = true; } }
/// <summary> /// Retrieves the corresponding C-Access ID for a C-Access user account. /// </summary> /// <param name="user">The user to retrieve an ID for.</param> /// <returns>The corresponding C-Access ID for the account.</returns> internal static string GetCaid(this CPUser user) { if (user == null) { return(null); } switch (user.SourceType) { case EntityType.Candidate: return(AccountAnalysis.CandidatePrefix + user.Cid); case EntityType.Treasurer: return(AccountAnalysis.TreasurerPrefix + user.SourceCommitteeID + user.SourceElectionCycle); case EntityType.Liaison: return(AccountAnalysis.LiaisonPrefix + user.SourceCommitteeID + user.SourceLiaisonID); case EntityType.Consultant: return(AccountAnalysis.ConsultantPrefix + user.SourceCommitteeID + user.SourceLiaisonID); default: return(null); } }
/// <summary> /// Gets the e-mail address of the currently logged-in user. /// </summary> /// <returns>The e-mail address of the currently logged-in user.</returns> public static MailAddress GetMailAddress() { CPUser user = CPSecurity.Provider.GetUser(UserName); return(user == null ? null : new MailAddress(user.Email, user.DisplayName)); }
/// <summary> /// Updates a C-Access Security user. /// </summary> /// <param name="user">The user to update.</param> /// <returns>An <see cref="UpdateResult"/> object representing the result of the synchronization.</returns> public UpdateResult UpdateUser(CPUser user) { using (SecurityClient client = new SecurityClient()) { return(client.UpdateUser(user)); } }
static void Main(string[] args) { Console.WriteLine("CFB Candidate Portal User Setup"); Console.WriteLine("Copyright (c) NYC Campaign Finance Board. All rights reserved.\n"); if ((args.Length == 0)) { Console.WriteLine(_UsageMessage); } else { string username = string.Empty; string password = string.Empty; string email = string.Empty; string cfisId = string.Empty; string caId = string.Empty; string name = string.Empty; string firstName = string.Empty; string lastName = string.Empty; string middle = string.Empty; bool passwordSwitch = false; bool emailSwitch = false; bool cfisIdSwitch = false; bool caIdSwitch = false; bool nameSwitch = false; bool firstNameSwitch = false; bool lastNameSwitch = false; bool miSwitch = false; UserOperation op = UserOperation.Unknown; // detect switches and store arguments foreach (string arg in args) { string trimmed = arg.Trim(); if (trimmed.Length == 2) { switch (trimmed.Substring(0, 2)) { case "/c": if (op != UserOperation.Unknown) { Console.WriteLine(_UsageMessage); return; } op = UserOperation.Create; break; case "/?": default: Console.WriteLine(_UsageMessage); return; } } else if (trimmed.Length > 2) { switch (trimmed.Substring(0, 3)) { case "/u:": if (op != UserOperation.Unknown) { Console.WriteLine(_UsageMessage); return; } op = UserOperation.Update; username = trimmed.Substring(3); break; case "/r:": if ((args.Length > 1) || (op != UserOperation.Unknown)) { Console.WriteLine(_UsageMessage); return; } op = UserOperation.PasswordReset; username = trimmed.Substring(3); break; case "/d:": if ((args.Length > 1) || (op != UserOperation.Unknown)) { Console.WriteLine(_UsageMessage); } op = UserOperation.Delete; username = trimmed.Substring(3); break; case "/l:": if ((args.Length > 1) || (op != UserOperation.Unknown)) { Console.WriteLine(_UsageMessage); } op = UserOperation.Unlock; username = trimmed.Substring(3); break; case "/x:": if ((args.Length > 1) || (op != UserOperation.Unknown)) { Console.WriteLine(_UsageMessage); } op = UserOperation.Disable; username = trimmed.Substring(3); break; case "/p:": if (passwordSwitch) { Console.WriteLine(_UsageMessage); return; } passwordSwitch = true; password = trimmed.Substring(3); break; case "/e:": if (emailSwitch) { Console.WriteLine(_UsageMessage); return; } emailSwitch = true; email = trimmed.Substring(3); break; case "/i:": if (cfisIdSwitch) { Console.WriteLine(_UsageMessage); return; } cfisIdSwitch = true; cfisId = trimmed.Substring(3); break; case "/a:": if (caIdSwitch) { Console.WriteLine(_UsageMessage); return; } caIdSwitch = true; caId = trimmed.Substring(3); break; case "/n:": if (nameSwitch) { Console.WriteLine(_UsageMessage); return; } nameSwitch = true; name = trimmed.Substring(3); break; case "/f:": if (firstNameSwitch) { Console.WriteLine(_UsageMessage); return; } firstNameSwitch = true; firstName = trimmed.Substring(3); break; case "/s:": if (lastNameSwitch) { Console.WriteLine(_UsageMessage); return; } lastNameSwitch = true; lastName = trimmed.Substring(3); break; case "/m:": if (miSwitch) { Console.WriteLine(_UsageMessage); return; } miSwitch = true; middle = trimmed.Substring(3); break; default: Console.WriteLine(_UsageMessage); return; } } } if (op == UserOperation.Unknown) { Console.WriteLine(_UsageMessage); return; } UserManagement.EnableTracing = true; // show user account properties Console.WriteLine("Got the following:"); if (op != UserOperation.Create) { Console.WriteLine("User Name: {0}", username); } if (passwordSwitch) { Console.WriteLine("Password: {0}", password); } if (emailSwitch) { Console.WriteLine("E-mail: {0}", email); } if (cfisIdSwitch) { Console.WriteLine("CFIS ID: {0}", cfisId); } if (caIdSwitch) { Console.WriteLine("C-Access ID: {0}", caId); } if (firstNameSwitch) { Console.WriteLine("First Name: {0}", firstName); } if (lastNameSwitch) { Console.WriteLine("Last Name: {0}", lastName); } if (miSwitch) { Console.WriteLine("Middle Initial: {0}", middle); } // dispatch operation if (op == UserOperation.Create) { // create user MembershipUser user = UserManagement.CreateUser(UserManagement.GenerateUserName(firstName, string.IsNullOrWhiteSpace(middle) ? null : (char?)middle.Trim().ToCharArray()[1], lastName, cfisId), password, email, typeof(Pumacmd).ToString()); if (!string.IsNullOrEmpty(name)) { CPUser cpuser = CPSecurity.Provider.GetUser(username); cpuser.DisplayName = name; CPSecurity.Provider.UpdateUser(cpuser); } Console.WriteLine((user == null) ? "Error creating user!" : string.Format("\nUser {0} was created.", user.UserName)); } else { if (string.IsNullOrEmpty(username)) { Console.Write(_UsageMessage); return; } MembershipUser user = Membership.GetUser(username); if (op == UserOperation.PasswordReset) { // reset password for user account string newPassword = UserManagement.ResetPassword(Membership.GetUser(username)).Decrypt(); if (!string.IsNullOrEmpty(newPassword)) { Console.WriteLine("Password successfully reset. New password is: {0}", newPassword); } else { Console.WriteLine("Password reset failed."); } } else if (op == UserOperation.Delete) { // delete user account if (UserManagement.DeleteUser(Membership.GetUser(username))) { Console.WriteLine("User {0} deleted successfully.", username); } else { Console.WriteLine("Error deleting user {0}", username); } } else if (op == UserOperation.Unlock) { // unlock user account if (UserManagement.UnlockUser(Membership.GetUser(username))) { Console.WriteLine("User {0} unlocked successfully.", username); } else { Console.WriteLine("Error unlocking user {0}", username); } } else if (op == UserOperation.Disable) { // enable/disable user account if (user != null && UserManagement.SetStatus(user, !user.IsApproved)) { Console.WriteLine("User {0} {1} successfully.", username, user.IsApproved ? "enabled" : "disabled"); } else { Console.WriteLine("Error toggling the active status for user {0}", username); } } else if (op == UserOperation.Update) { string message = null; if (emailSwitch) { user.Email = email; message = string.Format("E-mail address for user {0} was set to: {1}", username, email); } Membership.UpdateUser(user); Console.WriteLine(message); } else { Console.WriteLine(_UsageMessage); } } } }
/// <summary> /// Gets the e-mail address for the user. /// </summary> /// <param name="username">The C-Access user to query.</param> /// <returns>The e-mail address on record for the specified user.</returns> public string GetEmail(string username) { CPUser user = GetUser(username); return(user == null ? null : user.Email); }
private void _okButton_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; if (this.IsCreateMode) { // validate if (this.ValidateForm()) { // create new C-Access user account char? middleInitial = string.IsNullOrWhiteSpace(_miTextBox.Text) ? null : (char?)_miTextBox.Text.Trim().ToCharArray()[0]; string first = _firstNameTextBox.Text.Trim(); string last = _lastNameTextBox.Text.Trim(); CPUser user = CPSecurity.Provider.CreateUser(first, middleInitial, last, _candidateID, _passwordTextBox.Text.Trim(), _cfisEmailTextBox.Text.Trim(), SettingsManager.CurrentUser.Username, _entityType, _committeeID, _electionCycle, _liaisonID, _newUsernameTextBox.Visible ? _newUsernameTextBox.Text : null); if (user == null) { if (MessageBox.Show(this, string.Format("Unable to create a C-Access account for {0}. Retry?", Entity.ToFullName(first, last, middleInitial, false)), "Account Creation Failure", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.Retry) { _okButton_Click(sender, e); } } else { // auto-set security group var groups = from g in CPSecurity.Provider.GetGroups() where g.Name == user.SourceType.ToString() + "s" select g.ID; if (groups.Any()) { CPSecurity.Provider.AddUserToGroups(user.UserName, groups.ToList()); } // auto-set election cycle access if (!user.IsCandidate && !string.IsNullOrWhiteSpace(_electionCycle)) { user.ElectionCycles.Clear(); user.ImplicitElectionCycles = false; user.ElectionCycles.Add(_electionCycle); user.Save(); } else { user.Refresh(); } // refresh form this.SetUser(user); _mainTabControl.SelectedTab = _generalTabPage; _cancelButton.Location = _cancelButtonLocation; RefreshAccountExplorers(); } } } else if (_applyButton.Enabled) { _applyButton.PerformClick(); if (!_applyButton.Enabled) { this.Close(); } } else { this.Close(); } this.Cursor = Cursors.Default; }
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); }
/// <summary> /// Sets a C-Access user account to be displayed. /// </summary> /// <param name="user">The user to display.</param> /// <remarks>Setting a null user context will generate an error message and close the form.</remarks> private void SetUser(CPUser user) { if (user == null) { this.ShowTransactionError(); this.Close(); return; } this.Tag = _user = user; _readOnly = !_adminMode && user.SourceType == EntityType.Generic; // base properties _initializing = true; _displayNameTextBox.Text = user.DisplayName; _displayNameTextBox.ReadOnly = !_adminMode; _userNameTextBox.Text = user.UserName.ToLowerInvariant(); _emailTextBox.Text = user.Email; var dt = user.LastLoginDate; _loginTextBox.Text = dt.HasValue && dt.Value != DateTime.MinValue ? user.LastLoginDate.Value.ToString(DateFormatString) : "(never logged in)"; dt = user.LastLockoutDate; _lockoutTextBox.Text = dt.HasValue && dt.Value != DateTime.MinValue ? user.LastLockoutDate.Value.ToString(DateFormatString) : "(never locked out)"; dt = user.LastPasswordChangedDate; _pwSetTextBox.Text = dt.HasValue && dt.Value != DateTime.MinValue ? user.LastPasswordChangedDate.Value.ToString(DateFormatString) : "(password never changed)"; _createdTextBox.Text = user.CreationDate.ToString(DateFormatString); _unlockButton.Enabled = user.LockedOut && !_readOnly; _userImage.Image = _user.Enabled ? null : _disabledOverlay; SetEnableButtonProperties(); this.Text = string.Format("{0} - {1}", _defaultText, user.DisplayName); SetCandidate(user.Cid); // security tab AddGroups(CPSecurity.Provider.GetGroupMembership(user.UserName), false); // election cycles tab _electionsCheckedListBox.Items.Clear(); foreach (var ec in CPProviders.DataProvider.GetActiveElectionCycles(user.Cid, CPProviders.SettingsProvider.MinimumElectionCycle)) { _electionsCheckedListBox.Items.Add(ec); } _electionsCandidateToolTip.Active = _electionCandidateInfoPanel.Visible = _user.IsCandidate; _allCyclesCheckBox.Visible = _adminMode && user.SourceType == EntityType.Generic; _allCyclesCheckBox.Checked = _user.ImplicitElectionCycles; CheckElectionCycleCheckBoxItems(); // entity tab Entity entity = null; switch (_user.SourceType) { case EntityType.Candidate: entity = CPProviders.DataProvider.GetCandidate(_user.Cid); break; case EntityType.Treasurer: var committees = CPProviders.DataProvider.GetAuthorizedCommittees(_user.Cid, _user.SourceElectionCycle); AuthorizedCommittee comm; if (committees != null && _user.SourceCommitteeID.HasValue && committees.Committees.TryGetValue(_user.SourceCommitteeID.Value, out comm)) { entity = comm.Treasurer; } break; case EntityType.Liaison: case EntityType.Consultant: if (_user.SourceCommitteeID.HasValue && _user.SourceLiaisonID.HasValue) { var liaisons = CPProviders.DataProvider.GetLiaisonsByCommittee(_user.Cid, _user.SourceCommitteeID.Value); Liaison l; if (liaisons.TryGetValue(_user.SourceLiaisonID.Value, out l)) { entity = l; } } break; } _entityType = _user.SourceType; _electionCycle = _user.SourceElectionCycle; _committeeID = _user.SourceCommitteeID; _liaisonID = _user.SourceLiaisonID; SetEntity(entity, _user.SourceType, _user.Cid, _user.SourceElectionCycle, _user.SourceCommitteeID, _user.SourceLiaisonID); // switch to existing account view if (!_mainTabControl.TabPages.Contains(_generalTabPage)) { _mainTabControl.TabPages.Insert(0, _generalTabPage); } if (!_mainTabControl.TabPages.Contains(_securityTabPage)) { _mainTabControl.TabPages.Insert(1, _securityTabPage); } if (!_mainTabControl.TabPages.Contains(_electionsTabPage)) { _mainTabControl.TabPages.Insert(2, _electionsTabPage); } this.IsCreateMode = false; _cancelButton.Location = _cancelButtonLocation; _applyButton.Visible = true; _cfisDisplayNameTextBox.ReadOnly = _cfisEmailTextBox.ReadOnly = true; _newUsernameLabel.Visible = _newUsernameTextBox.Visible = _newUsernamePlaceholder.Visible = _usernameButton.Visible = _passwordTextBox.Visible = _passwordLabel.Visible = false; _passwordTextBox.Text = null; _newUsernameTextBox.CausesValidation = _passwordTextBox.CausesValidation = _cfisEmailTextBox.CausesValidation = _cfisDisplayNameTextBox.CausesValidation = false; _initializing = false; }
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)); }
public UpdateResult SynchronizeUser(string userName) { CPUser user = this.GetUser(userName); if (user == null) { return(new UpdateResult(null, UpdateResultState.MembershipUserNotFound)); } UpdateResultState state = UpdateResultState.Success; // find source entity Entity source = null; switch (user.SourceType) { case EntityType.Candidate: source = CPProviders.DataProvider.GetEntity(user.Cid); break; case EntityType.Treasurer: source = CPProviders.DataProvider.GetEntity(user.Cid, user.SourceCommitteeID, user.SourceElectionCycle); break; case EntityType.Liaison: case EntityType.Consultant: source = CPProviders.DataProvider.GetEntity(user.Cid, user.SourceCommitteeID, liaisonID: user.SourceLiaisonID); break; } if (source == null) { state |= UpdateResultState.CfisContactNotFound; } else { // update email/name MembershipUserCollection conflicts = Membership.FindUsersByEmail(source.Email); foreach (MembershipUser u in conflicts) { if (string.Equals(user.Cid, GetCid(u.UserName), StringComparison.OrdinalIgnoreCase) && !string.Equals(user.UserName, u.UserName, StringComparison.OrdinalIgnoreCase)) { state |= UpdateResultState.EmailAddressInUse; break; } } if (string.Equals(user.DisplayName, source.Name, StringComparison.OrdinalIgnoreCase)) // update only name or email address, but not both simultaneously { if (!string.IsNullOrEmpty(source.Email)) { MembershipUser u = Membership.GetUser(user.UserName); if (u != null) { user.Email = u.Email = source.Email; try { Membership.UpdateUser(u); state |= UpdateResultState.EmailAddressChanged; } catch { state |= UpdateResultState.AspNetMembershipFailure; } } else { state |= UpdateResultState.MembershipUserNotFound; } } } else { // update name if (!string.IsNullOrEmpty(source.Name)) { user.DisplayName = source.Name; state |= UpdateResultState.DisplayNameChanged; } } } // persist changes UpdateResult result = new UpdateResult(user, state); if (result.Succeeded) { result = UpdateUser(user); } return(result); }
/// <summary> /// Handles viewer postback commands. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> object that contains the event data.</param> void ExecuteCommand(object sender, CommandEventArgs e) { switch (e.CommandName) { case AccountViewer.ReturnCommandName: // return to account management screen if (Closed != null) { Closed(this, new AccountManagementEventArgs()); } break; case AccountViewer.SynchronizeCommandName: // synchronize current account var result = CPSecurity.Provider.SynchronizeUser(_user.UserName); var updated = result.User; switch (result.State) { case UpdateResultState.CfisContactNotFound: MessageText = string.Format("<span class=\"ms-error\">Unable to find a matching contact in CFIS for the current user. Please contact an Administrator for further assistance. (CAID: {0})</span>", _caid.Value); break; case UpdateResultState.EmailAddressInUse: MessageText = "<span class=\"ms-error\">Error: New e-mail address is already registered with another account for the current campaign.</span>"; break; case UpdateResultState.Success: MessageText = "There are no disparities to synchronize."; break; default: if ((result.State & UpdateResultState.DisplayNameChanged) == UpdateResultState.DisplayNameChanged) { MessageText += "<li>Display name updated.</li>"; } if ((result.State & UpdateResultState.EmailAddressChanged) == UpdateResultState.EmailAddressChanged) { MessageText += "<li>E-mail address updated.</li>"; } ReloadUser(); MessageText = "<span class=\"ms-error\">An error occurred while updating the user. Please see an Administrator for assistance.</span>"; break; } break; case AccountViewer.ResetPasswordCommandName: // reset password on account if (_user != null) { CPUser user = CPSecurity.Provider.GetUser(_user.UserName); if (user.ResetPassword()) { MessageText = string.Format("Password successfully reset. An e-mail was also automatically sent to the user at <strong>{0}</strong>.", _user.Email); } else { MessageText = "<span class=\"ms-error\">Unlock attempt failed. Please see an Administrator for assistance.</span>"; } ReloadUser(); } break; case AccountViewer.ImpersonateCommandName: // TODO: add code for impersonating current account MessageText = "Sorry, impersonation is not yet available."; break; case UnlockCommandName: // unlock account if (_user != null) { MessageText = UserManagement.UnlockUser(_user) ? "Account successfully unlocked." : "<span class=\"ms-error\">Unlock attempt failed. Please see an Administrator for assistance.</span>"; ReloadUser(); GetLockoutStatus(_user); } break; case ActivateCommandName: // activate account if (_user != null) { MessageText = UserManagement.SetStatus(_user, true) ? "Account successfully activated." : "<span class=\"ms-error\">Account activation attempt failed. Please see an Administrator for assistance.</span>"; ReloadUser(); GetActiveStatus(_user); } break; case DeactivateCommandName: // deactivate account if (_user != null) { MessageText = UserManagement.SetStatus(_user, false) ? "Account successfully deactivated." : "<span class=\"ms-error\">Account deactivation attempt failed. Please see an Administrator for assistance.</span>"; ReloadUser(); GetActiveStatus(_user); } break; case EditCommentCommandName: _newComment.Visible = true; _editCommentButton.CommandName = _editCommentButton.Text = SaveCommentCommandName; break; case SaveCommentCommandName: _user.Comment = _newComment.Text; Membership.UpdateUser(_user); ReloadUser(); _newComment.Visible = false; _editCommentButton.CommandName = _editCommentButton.Text = EditCommentCommandName; break; case CancelCommentCommandName: ReloadUser(); _newComment.Visible = false; _editCommentButton.CommandName = _editCommentButton.Text = EditCommentCommandName; break; } }
/// <summary> /// Analyzes an <see cref="Entity"/> to see if it is eligible for C-Access account creation. /// </summary> /// <param name="entity">The entity to check.</param> /// <param name="cid">The CFIS ID of the campaign of which entity is a member.</param> /// <param name="contactID">The C-Access ID of the entity.</param> /// <param name="user">For entities that are ineligible due to a conflict with a current C-Access user account, the conflicting user.</param> /// <returns>An <see cref="AccountEligibilityStatus"/> value representing the eligibility analysis results.</returns> private AccountEligibility DetermineEligibility(Entity entity, string cid, string contactID, out CPUser match) { match = null; if (entity == null) { return(AccountEligibility.IneligibleNull); } if (string.IsNullOrEmpty(entity.FirstName)) { return(AccountEligibility.IneligibleNoFirstName); } else if (string.IsNullOrEmpty(entity.LastName)) { return(AccountEligibility.IneligibleNoLastName); } else if (string.IsNullOrEmpty(entity.Email)) { return(AccountEligibility.IneligibleNoEmail); } else { // look for matching user Func <CPUser, bool> caidMatches = (user) => { return(string.Equals(contactID, user.GetCaid(), StringComparison.OrdinalIgnoreCase)); }; Func <CPUser, bool> firstMatches = (user) => { return(user.DisplayName.StartsWith(entity.FirstName + " ")); }; Func <CPUser, bool> lastMatches = (user) => { return(user.DisplayName.EndsWith(" " + entity.LastName)); }; match = _users.FirstOrDefault(u => string.Equals(u.Email, entity.Email, StringComparison.OrdinalIgnoreCase)); if (match != null) { bool caidMatch = caidMatches(match); bool firstMatch = firstMatches(match); bool lastMatch = lastMatches(match); return(caidMatch && (firstMatch || lastMatch) ? AccountEligibility.IneligibleExists : !caidMatch && firstMatch && lastMatch ? AccountEligibility.IneligibleDuplicateAccount : AccountEligibility.IneligibleDuplicateEmail); } match = _users.FirstOrDefault(u => firstMatches(u) && lastMatches(u)); return(match != null? caidMatches(match) ? AccountEligibility.IneligibleExists : AccountEligibility.IneligibleDuplicateAccount: AccountEligibility.Eligible); } }