public ScheduledItem SaveAndRunNow(ScheduledItem instance, NodeVisit visit) { ValidateCanEditFlowById(visit, instance.FlowId); if ((instance == null)) { throw new ArgumentException("Input values are null."); } instance.ModifiedById = visit.Account.Id; string flowName = _flowManager.GetDataFlowNameById(instance.FlowId); TransactionTemplate.Execute(delegate { _scheduleDao.SaveAndRunNow(instance); ActivityManager.LogAudit(NodeMethod.None, flowName, instance.Name, visit, "{0} saved and ran scheduled item: {1}.", visit.Account.NaasAccount, instance.ToString()); return(null); }); return(instance); }
public DataService SaveService(DataService instance, NodeVisit visit) { ValidateCanEditFlowById(visit, instance.FlowId); if (instance == null) { throw new ArgumentException("Input values are null."); } instance.ModifiedById = visit.Account.Id; string flowName = GetDataFlowNameById(instance.FlowId); TransactionTemplate.Execute(delegate { _serviceDao.Save(instance); ActivityManager.LogAudit(NodeMethod.None, flowName, instance.Name, visit, "{0} saved data service: {1}.", visit.Account.NaasAccount, instance.ToString()); return(null); }); return(instance); }
public ConfigItem Save(string curItemId, ConfigItem item, NodeVisit visit) { ValidateByRole(visit, SystemRoleType.Admin); ParsingHelper.ValidateKey(item.Id); if (!item.IsEditable) { throw new InvalidOperationException("The item cannot be saved since it is not editable."); } ConfigItem saveItem = new ConfigItem(item); saveItem.ModifiedById = visit.Account.Id; saveItem.Value = _cryptographyProvider.Encrypt(item.Value); lock (_lockObject) { TransactionTemplate.Execute(delegate { _configDao.Save(curItemId, saveItem); lock (_lockObject) { if (!string.IsNullOrEmpty(curItemId)) { if (_configItems.ContainsKey(curItemId.ToUpper())) { _configItems.Remove(curItemId.ToUpper()); } } _configItems[item.Id.ToUpper()] = item; } ActivityManager.LogAudit(NodeMethod.None, null, visit, "{0} updated configuration value: {1}.", visit.Account.NaasAccount, saveItem.ToString()); return(null); }); item.ModifiedById = saveItem.ModifiedById; item.ModifiedOn = saveItem.ModifiedOn; } return(item); }
public UserAccount ResetPassword(string currentPassword, string newPassword, UserAccount instance, NodeVisit visit) { try { ValidateByRole(visit, SystemRoleType.Program); _naasManager.ChangePassword(instance.NaasAccount, currentPassword, newPassword); ActivityManager.LogAudit(NodeMethod.None, null, visit, "{0} reset password for user account: {1}.", visit.Account.NaasAccount, instance.ToString()); return(instance); } catch (Exception e) { ActivityManager.LogError(NodeMethod.None, null, e, visit, "{0} failed to reset password for user account: {1}.", visit.Account.NaasAccount, instance.ToString()); throw; } }
public UserAccount ResetPassword(UserAccount instance, NodeVisit visit) { try { ValidateByRole(visit, SystemRoleType.Admin); string newPassword = GenerateRandomPassword(); _naasManager.ResetPassword(instance.NaasAccount, newPassword); ActivityManager.LogAudit(NodeMethod.None, null, visit, "{0} reset password for user account: {1}.", visit.Account.NaasAccount, instance.ToString()); _notificationManager.DoChangePasswordNotifications(instance.NaasAccount, newPassword); return(instance); } catch (Exception e) { ActivityManager.LogError(NodeMethod.None, null, e, visit, "{0} failed to reset password for user account: {1}.", visit.Account.NaasAccount, instance.ToString()); throw; } }
public AccountAuthorizationRequest AcceptRequest(AccountAuthorizationRequest request, NodeVisit visit) { ValidateByRole(visit, SystemRoleType.Admin); ExceptionUtils.ThrowIfNull(request.Response, "request.Response"); IDictionary <string, string> upperFlowNameToIdMap = _flowManager.GetAllProtectedUpperDataFlowNamesToIdMap(); bool userExists = ValidateUserExistance(request.NaasAccount, request.AffiliatedNodeId, null, upperFlowNameToIdMap); string password = _accountManager.GenerateRandomPassword(); UserAccount userAccount = _accountDao.GetByName(request.NaasAccount); List <UserAccessPolicy> policies = null; if (userAccount == null) { userAccount = new UserAccount(); userAccount.ModifiedById = visit.Account.Id; userAccount.NaasAccount = request.NaasAccount; userAccount.Role = SystemRoleType.Authed; } else { if (!CollectionUtils.IsNullOrEmpty(userAccount.Policies)) { policies = new List <UserAccessPolicy>(userAccount.Policies); } } userAccount.IsActive = true; if (!CollectionUtils.IsNullOrEmpty(request.RequestedFlows)) { foreach (AccountAuthorizationRequestFlow requestedFlow in request.RequestedFlows) { UserAccessPolicy curPolicy = GetPolicyForFlow(requestedFlow.FlowName, policies); bool foundFlow = (curPolicy != null); if (foundFlow && !requestedFlow.AccessGranted) { policies.Remove(curPolicy); } else if (!foundFlow && requestedFlow.AccessGranted) { UserAccessPolicy policy = _accountPolicyManager.CreatePolicy(userAccount.Role, null, requestedFlow.FlowName, FlowRoleType.Endpoint); policy.ModifiedById = visit.Account.Id; CollectionUtils.Add(policy, ref policies); } } userAccount.Policies = policies; } _accountManager.Save(userAccount, true, password, visit); request.Response.AuthorizationAccountId = visit.Account.Id; request.Response.DidCreateInNaas = !userExists; _accountAuthorizationRequestDao.DoRequestUpdate(request, visit.Account.NaasAccount, true); string statusDetail = string.Format("{0} accepted authorization request from user \"{1} ({2})\": {3}", visit.Account.NaasAccount, request.FullName, request.NaasAccount, request.ToString()); ActivityManager.LogAudit(NodeMethod.None, null, request.TransactionId, visit, statusDetail); return(request); }
/// <summary> /// Check to see if the input request is already valid (user exists in NAAS and the node and already has access to /// the requested flows. If so, automatically set the request to Accepted, thereby bypassing the need for /// the node Admin to formally accept the request. /// </summary> protected void CheckForAlreadyValidAuthorizationRequest(AccountAuthorizationRequest item) { UserAccount userAccount = null; try { userAccount = _accountManager.GetByName(item.NaasAccount); } catch (Exception) { } if ((userAccount != null) && userAccount.IsActive) { IList <string> protectedFlows = _flowManager.GetProtectedFlowNames(); bool hasAccessToAllRequestedFlows = true; IList <AccountAuthorizationRequestFlow> requestedFlows = null; if (!CollectionUtils.IsNullOrEmpty(protectedFlows)) { if (CollectionUtils.IsNullOrEmpty(item.RequestedFlows)) { // If item.RequestedFlows == null, this is a request to grant access to all protected flows requestedFlows = new List <AccountAuthorizationRequestFlow>(protectedFlows.Count); foreach (string flowName in protectedFlows) { requestedFlows.Add(new AccountAuthorizationRequestFlow(flowName)); } } else { // Deep copy the list so that we can update element without affecting the "real" request // until we are sure we will accept the user requestedFlows = new List <AccountAuthorizationRequestFlow>(item.RequestedFlows.Count); foreach (AccountAuthorizationRequestFlow requestedFlow in item.RequestedFlows) { requestedFlows.Add(new AccountAuthorizationRequestFlow(requestedFlow.FlowName)); } } // Check that the user has access to all the requested flows: IDictionary <string, string> upperFlowNameToIdMap = _flowManager.GetAllProtectedUpperDataFlowNamesToIdMap(); foreach (AccountAuthorizationRequestFlow requestedFlow in requestedFlows) { if (upperFlowNameToIdMap.ContainsKey(requestedFlow.FlowName.ToUpper())) { if (!HasPolicyForFlow(requestedFlow.FlowName, userAccount.Policies)) { hasAccessToAllRequestedFlows = false; break; } else { requestedFlow.AccessGranted = true; } } } } if (hasAccessToAllRequestedFlows) { // Validate that the user is actually in NAAS if (_naasManager.UserExists(userAccount.NaasAccount)) { // Accept this user automatically item.RequestedFlows = requestedFlows; item.Response = new AccountAuthorizationResponse(); item.Response.AuthorizationAccountId = _accountManager.AdminAccount.Id; item.Response.AuthorizationComments = "The node admin automatically accepted the request since all requested policies are currently active"; item.Response.DidCreateInNaas = false; _accountAuthorizationRequestDao.DoRequestUpdate(item, _accountManager.AdminAccount.NaasAccount, true); string statusDetail = string.Format("Automatically accepted authorization request from user \"{0} ({1})\" since all requested policies are currently active: {2}", item.FullName, item.NaasAccount, item.ToString()); ActivityManager.LogAudit(NodeMethod.None, null, item.TransactionId, null, statusDetail); } } } }
public UserAccount Save(UserAccount instance, bool allowCreateInNaasIfNecessary, string naasCreatePassword, NodeVisit visit) { try { if ((instance == null) || string.IsNullOrEmpty(instance.NaasAccount)) { throw new ArgumentException("Input values are null."); } bool createInDB = string.IsNullOrEmpty(instance.Id); bool needToCreateInNAAS = !_naasManager.UserExists(instance.NaasAccount); if (needToCreateInNAAS && string.IsNullOrEmpty(naasCreatePassword)) { throw new ArgumentException("Password cannot be empty."); } if (needToCreateInNAAS && !allowCreateInNaasIfNecessary) { throw new ArgumentException(string.Format("The user \"{0}\" does not exist in NAAS and cannot be added to the node", instance.NaasAccount)); } string activityFormatString; if (createInDB) { if (needToCreateInNAAS) { activityFormatString = "{0} created user account on this local node and within NAAS: {1}."; } else { activityFormatString = "{0} created user account on this local node: {1}."; } } else { if (needToCreateInNAAS) { activityFormatString = "{0} saved user account on this local node and created account within NAAS: {1}."; } else { activityFormatString = "{0} saved user account on this local node: {1}."; } } instance.Policies = _accountPolicyManager.CleanseFlowPoliciesForUser(instance.Role, instance.Policies); string naasPassword = null; if (needToCreateInNAAS) { // First, attempt to create the user in NAAS naasPassword = _naasManager.CreateUser(instance.NaasAccount, naasCreatePassword, instance.Role); } instance.ModifiedById = visit.Account.Id; TransactionTemplate.Execute(delegate { _accountDao.Save(instance); ActivityManager.LogAudit(NodeMethod.None, null, visit, activityFormatString, visit.Account.NaasAccount, instance.ToString()); return(null); }); if (needToCreateInNAAS) { _notificationManager.DoNewNaasAccountNotifications(instance.NaasAccount, naasCreatePassword, (instance.Role == SystemRoleType.Authed)); } else if (createInDB) { _notificationManager.DoNewNodeAccountNotifications(instance.NaasAccount, (instance.Role == SystemRoleType.Authed)); } return(instance); } catch (Exception e) { ActivityManager.LogError(NodeMethod.None, null, e, visit, "{0} failed to save user account: {1}.", visit.Account.NaasAccount, instance.ToString()); throw; } }
/// <summary> /// Sends a message based on the configured message templates /// Allows for body to be formatted with arguments. /// </summary> /// <param name="messageKey">key of the message configured during the setup</param> /// <param name="args">array of arguments (optional)</param> private void SendNotificationsPriv(string flowName, string transactionId, string toEmailAddresses, string notificationKey, string subject, Stream attachmentContent, string attachmentName, string[] args) { if (string.IsNullOrEmpty(toEmailAddresses)) { return; } Activity activity = new Activity(NodeMethod.None, flowName, null, ActivityType.Info, transactionId, null, null); try { string messageBody = LoadNotificationBody(notificationKey); if (args != null) { for (int i = 0; i < args.Length; ++i) { args[i] = HttpUtility.HtmlEncode(args[i]).Replace(Environment.NewLine, "<br/>"); } messageBody = string.Format(messageBody, args); } using (MailMessage msg = new MailMessage(FromEmailAddress, toEmailAddresses, subject, messageBody)) { msg.IsBodyHtml = true; if (attachmentContent != null) { Attachment attachment = new Attachment(attachmentContent, attachmentName); msg.Attachments.Add(attachment); } //SaveMailMessage(msg); int retryCount = 3; do { try { SmtpClient smtpClient = new SmtpClient(SmtpHost, SmtpPort); smtpClient.DeliveryMethod = DeliveryMethod; smtpClient.EnableSsl = _smtpEnableSsl; //If an exception is thrown, this setting causes max cpu usage on a background worker thread for no good reason, so I'm commenting it out: //smtpClient.ServicePoint.MaxIdleTime = 1; if (!string.IsNullOrEmpty(_smtpUsername)) { smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential(_smtpUsername, _smtpPassword); } smtpClient.Send(msg); retryCount = 1; } catch (Exception smtpException) { if (retryCount > 1) { activity.AppendFormat("Failed to send email notification: From ({0}), To ({1}), Type ({2}), DeliveryMethod ({3}), EnableSsl ({4}), SmtpHost ({5}), SmtpPort ({6}), SmtpUsername ({7})", FromEmailAddress, toEmailAddresses, notificationKey, DeliveryMethod, _smtpEnableSsl, SmtpHost, SmtpPort, _smtpUsername ?? string.Empty); activity.AppendFormat("EXCEPTION: {0}", ExceptionUtils.ToShortString(smtpException)); activity.AppendFormat("Retrying email send ..."); } else { throw; } } } while (--retryCount > 0); } activity.AppendFormat("Successfully sent \"{0}\" email notification to \"{1}\"", notificationKey, toEmailAddresses); ActivityManager.Log(activity); } catch (Exception ex) { string message = string.Format("Failed to send email notification: From ({0}), To ({1}), Type ({2}), DeliveryMethod ({3}), EnableSsl ({4}), SmtpHost ({5}), SmtpPort ({6})", FromEmailAddress, toEmailAddresses, notificationKey, DeliveryMethod, _smtpEnableSsl, SmtpHost, SmtpPort); activity.AppendFormat(message); activity.AppendFormat("EXCEPTION: {0}", ExceptionUtils.ToShortString(ex)); activity.Type = ActivityType.Error; ActivityManager.Log(activity); LOG.Error(message, ex); if (ThrowOnNotificationFailure) { throw; } } }