public Credential CreateGlobalCredential(GlobalCredentialViewModel request) { if (!String.IsNullOrEmpty(request.PasswordSecret)) { //get encryption key var orgId = _organizationManager.GetDefaultOrganization().Id; _organizationSettingRepository.ForceIgnoreSecurity(); var organizationKey = _organizationSettingRepository.Find(null, o => o.OrganizationId == orgId).Items.FirstOrDefault().EncryptionKey; var applicationKey = _configuration.GetSection("ApplicationEncryption:Key").Value; var encryptionKey = applicationKey + organizationKey; //generate salt request.HashSalt = CredentialHasher.CreateSalt(32); //create 32 byte salt //generate hash request.PasswordHash = CredentialHasher.GenerateSaltedHash(request.PasswordSecret, request.HashSalt); // Encrypt and decrypt the sample text via the Aes256CbcEncrypter class. request.PasswordSecret = CredentialsEncrypter.Encrypt(request.PasswordSecret, encryptionKey); } Credential credential = new Credential(); credential = request.Map(request); CredentialNameAvailability(credential); if (!ValidateStartAndEndDates(credential)) { throw new EntityOperationException("Start and End Date are not valid"); } return(credential); }
public async Task <IActionResult> Get( [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0 ) { try { var response = base.GetMany(); if (response.Items.Count == 0) { var settings = new EmailSettings(); settings.IsEmailDisabled = true; settings.OrganizationId = (Guid)_organizationManager.GetDefaultOrganization().Id; repository.Add(settings); response = base.GetMany(); } return(Ok(response)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public async Task <IActionResult> Put(string id, [FromBody] StorageDrive request) { try { Guid?entityId = Guid.Parse(id); if (request.Id == null || request.Id == Guid.Empty || request.Id != entityId) { request.Id = entityId; } if (request.OrganizationId == null || request.OrganizationId == Guid.Empty) { request.OrganizationId = _organizationManager.GetDefaultOrganization().Id; } if (string.IsNullOrEmpty(request.StoragePath)) { request.StoragePath = request.Name; } _manager.UpdateDrive(id, request, request.OrganizationId.ToString()); await _webhookPublisher.PublishAsync("Files.DriveUpdated", id, request.Name).ConfigureAwait(false); return(await base.PutEntity(id, request)); } catch (Exception ex) { return(ex.GetActionResult()); } }
public bool HasDisallowedExecution() { var defaultOrganization = _organizationManager.GetDefaultOrganization(); _organizationSettingRepository.ForceIgnoreSecurity(); var orgSettings = _organizationSettingRepository.Find(null, s => s.OrganizationId == defaultOrganization.Id).Items.FirstOrDefault(); _organizationSettingRepository.ForceSecurity(); if (orgSettings != null && orgSettings.DisallowAllExecutions != null) { return(orgSettings.DisallowAllExecutions); } return(false); }
public PaginatedList <EmailSettings> Get( [FromQuery(Name = "$filter")] string filter = "", [FromQuery(Name = "$orderby")] string orderBy = "", [FromQuery(Name = "$top")] int top = 100, [FromQuery(Name = "$skip")] int skip = 0 ) { var response = base.GetMany(); if (response.Items.Count == 0) { var settings = new EmailSettings(); settings.IsEmailDisabled = true; settings.OrganizationId = (Guid)organizationManager.GetDefaultOrganization().Id; repository.Add(settings); response = base.GetMany(); } return(response); }
public string GetOrganizationId() { string identity = _caller.Identity.Name; var personEmail = personEmailRepository.Find(null, q => q.Address.ToLower(null) == identity.ToLower(null))?.Items?.FirstOrDefault(); string personId = personEmail.PersonId.ToString(); var orgMember = organizationMemberRepository.Find(0, 1).Items.Where(q => q.PersonId.ToString() == personId).FirstOrDefault(); string organizationId; if (orgMember == null) { organizationId = organizationManager.GetDefaultOrganization().Id.ToString(); } else { organizationId = orgMember.OrganizationId.ToString(); } return(organizationId); }
public string GetOrganizationId() { string identity = _caller.Identity.Name; var user = usersRepository.Find(null, u => u.UserName == identity).Items?.FirstOrDefault(); organizationMemberRepository.ForceIgnoreSecurity(); var orgMember = organizationMemberRepository.Find(null, om => om.PersonId.Equals(user.PersonId))?.Items?.FirstOrDefault(); string organizationId; if (orgMember == null) { organizationId = organizationManager.GetDefaultOrganization().Id.ToString(); } else { organizationId = orgMember.OrganizationId.ToString(); } return(organizationId); }
public Task SendEmailAsync(EmailMessage emailMessage, string accountName = null, string id = null, string direction = null) { Email emailObject = new Email(); Guid? emailId = Guid.NewGuid(); if (!string.IsNullOrEmpty(id)) { emailId = Guid.Parse(id); emailObject = _emailRepository.Find(null, q => q.Id == emailId)?.Items?.FirstOrDefault(); if (emailObject == null) { emailObject = new Email() { Id = emailId, Status = StatusType.Unknown.ToString() }; } } Email email = new Email(); if (!string.IsNullOrEmpty(id)) { email.Id = emailId; } //find email settings and determine is email is enabled/disabled var organizationId = Guid.Parse(_organizationManager.GetDefaultOrganization().Id.ToString()); var emailSettings = _emailSettingsRepository.Find(null, s => s.OrganizationId == organizationId).Items.FirstOrDefault(); //check if accountName exists var existingAccount = _emailAccountRepository.Find(null, d => d.Name.ToLower(null) == accountName?.ToLower(null))?.Items?.FirstOrDefault(); if (existingAccount == null) { existingAccount = _emailAccountRepository.Find(null, d => d.IsDefault && !d.IsDisabled).Items.FirstOrDefault(); } //if there are no records in the email settings table for that organization, email should be disabled if (emailSettings == null) { email.Status = StatusType.Blocked.ToString(); email.Reason = "Email disabled. Please configure email settings."; } //if there are email settings but they are disabled, don't send email else if (emailSettings != null && emailSettings.IsEmailDisabled) { email.Status = StatusType.Blocked.ToString(); email.Reason = "Email functionality has been disabled."; } else { if (existingAccount == null && emailSettings != null) { existingAccount = _emailAccountRepository.Find(null, a => a.IsDefault == true && a.IsDisabled == false)?.Items?.FirstOrDefault(); if (existingAccount == null) { email.Status = StatusType.Failed.ToString(); email.Reason = $"Account '{accountName}' could be found."; } if (existingAccount != null && existingAccount.IsDisabled == true) { email.Status = StatusType.Blocked.ToString(); email.Reason = $"Account '{accountName}' has been disabled."; } } //set from email address else if (existingAccount != null) { EmailAddress fromEmailAddress = new EmailAddress(existingAccount.FromName, existingAccount.FromEmailAddress); List <EmailAddress> emailAddresses = new List <EmailAddress>(); foreach (EmailAddress emailAddress in emailMessage.From) { if (!string.IsNullOrEmpty(emailAddress.Address)) { emailAddresses.Add(emailAddress); } } emailMessage.From.Clear(); foreach (EmailAddress emailAddress in emailAddresses) { emailMessage.From.Add(emailAddress); } emailMessage.From.Add(fromEmailAddress); } //remove email addresses in to, cc, and bcc lists with domains that are blocked or not allowed List <EmailAddress> toList = new List <EmailAddress>(); List <EmailAddress> ccList = new List <EmailAddress>(); List <EmailAddress> bccList = new List <EmailAddress>(); if (string.IsNullOrEmpty(emailSettings.AllowedDomains)) { if (!string.IsNullOrEmpty(emailSettings.BlockedDomains)) { //remove any email address that is in blocked domain IEnumerable <string>?denyList = (new List <string>(emailSettings?.BlockedDomains?.Split(','))).Select(s => s.ToLowerInvariant().Trim()); foreach (EmailAddress address in emailMessage.To) { if (!string.IsNullOrEmpty(address.Address)) { MailboxAddress mailAddress = new MailboxAddress(address.Address); if (!denyList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant())) { toList.Add(address); } } } emailMessage.To.Clear(); emailMessage.To = toList; foreach (EmailAddress address in emailMessage.CC) { if (!string.IsNullOrEmpty(address.Address)) { MailboxAddress mailAddress = new MailboxAddress(address.Address); if (!denyList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant())) { ccList.Add(address); } } } emailMessage.CC.Clear(); emailMessage.CC = ccList; foreach (EmailAddress address in emailMessage.Bcc) { if (!string.IsNullOrEmpty(address.Address)) { MailboxAddress mailAddress = new MailboxAddress(address.Address); if (!denyList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant())) { bccList.Add(address); } } } emailMessage.Bcc.Clear(); emailMessage.Bcc = bccList; } } else { if (!string.IsNullOrEmpty(emailSettings.AllowedDomains)) { //remove any email address that is not on white list IEnumerable <string> allowList = (new List <string>(emailSettings.AllowedDomains.Split(','))).Select(s => s.ToLowerInvariant().Trim()); foreach (EmailAddress address in emailMessage.To) { if (!string.IsNullOrEmpty(address.Address)) { MailboxAddress mailAddress = new MailboxAddress(address.Address); if (allowList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant())) { toList.Add(address); } } } emailMessage.To.Clear(); emailMessage.To = toList; foreach (EmailAddress address in emailMessage.CC) { if (!string.IsNullOrEmpty(address.Address)) { MailboxAddress mailAddress = new MailboxAddress(address.Address); if (allowList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant())) { ccList.Add(address); } } } emailMessage.CC.Clear(); emailMessage.CC = ccList; foreach (EmailAddress address in emailMessage.Bcc) { if (!string.IsNullOrEmpty(address.Address)) { MailboxAddress mailAddress = new MailboxAddress(address.Address); if (allowList.Contains(mailAddress.Address.Split("@")[1].ToLowerInvariant())) { bccList.Add(address); } } } emailMessage.Bcc.Clear(); emailMessage.Bcc = bccList; } } if (emailMessage.To.Count == 0) { email.Status = StatusType.Blocked.ToString(); email.Reason = "No email addresses to send email to."; } //add any necessary additional email addresses (administrators, etc.) if (!string.IsNullOrEmpty(emailSettings.AddToAddress)) { foreach (string toAddress in emailSettings.AddToAddress.Split(',')) { EmailAddress emailAddress = new EmailAddress(toAddress, toAddress); emailMessage.To.Add(emailAddress); } } if (!string.IsNullOrEmpty(emailSettings.AddCCAddress)) { foreach (string CCAddress in emailSettings.AddCCAddress.Split(',')) { EmailAddress emailAddress = new EmailAddress(CCAddress, CCAddress); emailMessage.CC.Add(emailAddress); } } if (!string.IsNullOrEmpty(emailSettings.AddBCCAddress)) { foreach (string BCCAddress in emailSettings.AddBCCAddress.Split(',')) { EmailAddress emailAddress = new EmailAddress(BCCAddress); emailMessage.Bcc.Add(emailAddress); } } //add subject and body prefixes/suffixes if (!string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && !string.IsNullOrEmpty(emailSettings.SubjectAddSuffix)) { emailMessage.Subject = string.Concat(emailSettings.SubjectAddPrefix, emailMessage.Subject, emailSettings.SubjectAddSuffix); } if (!string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && string.IsNullOrEmpty(emailSettings.SubjectAddSuffix)) { emailMessage.Subject = string.Concat(emailSettings.SubjectAddPrefix, emailMessage.Subject); } if (string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && !string.IsNullOrEmpty(emailSettings.SubjectAddSuffix)) { emailMessage.Subject = string.Concat(emailMessage.Subject, emailSettings.SubjectAddSuffix); } else { emailMessage.Subject = emailMessage.Subject; } //check if email message body is html or plaintext if (emailMessage.IsBodyHtml) { if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.Body = string.Concat(emailSettings.BodyAddPrefix, emailMessage.Body, emailSettings.BodyAddSuffix); } if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.Body = string.Concat(emailSettings.BodyAddPrefix, emailMessage.Body); } if (string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.Body = string.Concat(emailMessage.Body, emailSettings.BodyAddSuffix); } else { emailMessage.Body = emailMessage.Body; } } else { if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.PlainTextBody = string.Concat(emailSettings.BodyAddPrefix, emailMessage.PlainTextBody, emailSettings.BodyAddSuffix); } if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.PlainTextBody = string.Concat(emailSettings.BodyAddPrefix, emailMessage.PlainTextBody); } if (string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.PlainTextBody = string.Concat(emailMessage.PlainTextBody, emailSettings.BodyAddSuffix); } else { emailMessage.PlainTextBody = emailMessage.Body; } } //send email ISendEmailChore sendEmailChore = null; if (existingAccount != null) { if (existingAccount.Provider == "SMTP") { sendEmailChore = new SmtpSendEmailChore(existingAccount, emailSettings); } else if (existingAccount.Provider == "Azure") { sendEmailChore = new AzureSendEmailChore(emailSettings, existingAccount); } } if (sendEmailChore != null) { try { if (email.Status != StatusType.Blocked.ToString() || email.Status != StatusType.Failed.ToString()) { sendEmailChore.SendEmail(emailMessage); email.Status = StatusType.Sent.ToString(); email.Reason = "Email was sent successfully."; } } catch (Exception ex) { email.Status = StatusType.Failed.ToString(); email.Reason = "Error: " + ex.Message; } } else { email.Status = StatusType.Failed.ToString(); email.Reason = "Email failed to send."; } } //log email and its status if (existingAccount != null) { email.EmailAccountId = Guid.Parse(existingAccount.Id.ToString()); } email.SentOnUTC = DateTime.UtcNow; string newEmailMessage = Regex.Replace(emailMessage.Body, @"(<sensitive(\s|\S)*?<\/sensitive>)", "NULL"); email.EmailObjectJson = newEmailMessage; List <string> nameList = new List <string>(); List <string> emailList = new List <string>(); foreach (EmailAddress address in emailMessage.From) { nameList.Add(address.Name); emailList.Add(address.Address); } email.SenderName = JsonConvert.SerializeObject(nameList); email.SenderAddress = JsonConvert.SerializeObject(emailList); email.SenderUserId = _applicationUser?.PersonId; if (string.IsNullOrEmpty(direction)) { email.Direction = Direction.Unknown.ToString(); } else { email.Direction = direction; } //TODO: add logic to next two lines of code to allow for assignment of these Guids email.ConversationId = null; email.ReplyToEmailId = null; if (emailObject.Status == StatusType.Unknown.ToString()) { email.Id = emailObject.Id; email.CreatedOn = DateTime.UtcNow; email.CreatedBy = _httpContextAccessor.HttpContext.User.Identity.Name; _emailRepository.Add(email); } else if (email.Id != null && email.Id != emailId) { email.CreatedOn = DateTime.UtcNow; email.CreatedBy = _httpContextAccessor.HttpContext.User.Identity.Name; _emailRepository.Add(email); } else { emailObject.EmailAccountId = email.EmailAccountId; emailObject.SentOnUTC = email.SentOnUTC; emailObject.EmailObjectJson = email.EmailObjectJson; emailObject.SenderName = email.SenderName; emailObject.SenderAddress = email.SenderAddress; emailObject.SenderUserId = email.SenderUserId; emailObject.Direction = email.Direction; emailObject.ConversationId = email.ConversationId; emailObject.ReplyToEmailId = email.ReplyToEmailId; emailObject.Status = email.Status; emailObject.Reason = email.Reason; _emailRepository.Update(emailObject); } return(Task.CompletedTask); }
public void SaveFile(SaveServerFileViewModel request) { var file = request.File; Guid? id = request.Id; string path = request.StoragePath; Guid? organizationId = organizationManager.GetDefaultOrganization().Id; var hash = GetHash(path); //add FileAttribute entities var attributes = new Dictionary <string, int>() { { FileAttributes.StorageCount.ToString(), 1 }, { FileAttributes.RetrievalCount.ToString(), 0 }, { FileAttributes.AppendCount.ToString(), 0 } }; List <FileAttribute> fileAttributes = new List <FileAttribute>(); foreach (var attribute in attributes) { var fileAttribute = new FileAttribute() { ServerFileId = request.Id, AttributeValue = attribute.Value, CreatedBy = httpContextAccessor.HttpContext.User.Identity.Name, CreatedOn = DateTime.UtcNow, DataType = attribute.Value.GetType().ToString(), Name = attribute.Key, OrganizationId = organizationId }; fileAttributeRepository.Add(fileAttribute); fileAttributes.Add(fileAttribute); } //add file properties to ServerFile entity var serverFile = new ServerFile() { Id = id, ContentType = file.ContentType, CorrelationEntity = request.CorrelationEntity, CorrelationEntityId = request.CorrelationEntityId, CreatedBy = httpContextAccessor.HttpContext.User.Identity.Name, CreatedOn = DateTime.UtcNow, HashCode = hash, Name = file.FileName, SizeInBytes = file.Length, StorageFolderId = request.StorageFolderId, StoragePath = path, StorageProvider = request.StorageProvider, OrganizationId = organizationId, FileAttributes = fileAttributes }; serverFileRepository.Add(serverFile); webhookPublisher.PublishAsync("Files.NewFileCreated", serverFile.Id.ToString(), serverFile.Name); //upload file to local server //CheckDirectoryExists(path, organizationId); //if (file.Length <= 0 || file.Equals(null)) throw new Exception("No file exists"); //if (file.Length > 0) //{ // path = Path.Combine(path, serverFile.Id.ToString()); // using (var stream = new FileStream(path, FileMode.Create)) // file.CopyTo(stream); // ConvertToBinaryObject(path); //} }
/// <summary> /// Checks if the IPAddress is allowed in the IPFencing rules /// </summary> /// <param name="iPAddress"></param> /// <returns>True if the IP is allowed for the current organization</returns> public bool IsRequestAllowed(IPAddress iPAddress, IPFencingMode?fencingMode = null) { //local host addresses IPAddress localIPV4 = IPAddress.Parse("::1"); IPAddress localIPV6 = IPAddress.Parse("127.0.0.1"); //IP is local host if (iPAddress.Equals(localIPV4) || iPAddress.Equals(localIPV6)) { return(true); } List <IPFencing> ipFencingRules = new List <IPFencing>(); Guid? organizationId = Guid.Empty; var user = _accessor.HttpContext.User; var requestHeaders = _accessor.HttpContext.Request.Headers; Guid userId = Guid.Empty; var defaultOrg = organizationManager.GetDefaultOrganization(); if (defaultOrg != null) { organizationId = defaultOrg.Id; organizationSettingRepo.ForceIgnoreSecurity(); var orgSettings = organizationSettingRepo.Find(0, 1).Items?.Where(q => q.OrganizationId == organizationId).FirstOrDefault(); organizationSettingRepo.ForceSecurity(); if (orgSettings == null) { fencingMode = IPFencingMode.AllowMode; } else { fencingMode = orgSettings.IPFencingMode; } } //if there is no default organization, find the current user's organization else if (user != null) { string userIdStr = _userManager.GetUserId(user); if (string.IsNullOrEmpty(userIdStr)) { //if there is no user or organization, then use default IP fencing rules if (organizationId == null || organizationId == Guid.Empty) { ipFencingRules = repo.Find(0, 1).Items?.Where(i => i.OrganizationId == null)?.ToList(); //if no organization, user, or rules exist, allow user to access the site //this means the user is accessing the server application for the first time if (ipFencingRules.Count == 0) { return(true); } else { foreach (var rule in ipFencingRules) { if (rule.IPAddress == iPAddress.ToString() && rule.Usage == UsageType.Allow) { return(true); } } } } } } else { return(false); } if (fencingMode == IPFencingMode.AllowMode) { ipFencingRules = repo.Find(0, 1).Items?.Where(i => i.OrganizationId == organizationId && i.Usage == UsageType.Deny)?.ToList(); //if mode is allow, then any matched rules will be forbidden return(!MatchedOnRule(iPAddress, ipFencingRules, requestHeaders)); } else { ipFencingRules = repo.Find(0, 1).Items?.Where(i => i.OrganizationId == organizationId && i.Usage == UsageType.Allow)?.ToList(); //if mode is deny, then any matched rules will be allowed return(MatchedOnRule(iPAddress, ipFencingRules, requestHeaders)); } }
public async Task <IActionResult> Register(SignUpViewModel signupModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } EmailVerification emailAddress = emailVerificationRepository.Find(null, p => p.Address.Equals(signupModel.Email, StringComparison.OrdinalIgnoreCase)).Items?.FirstOrDefault(); if (emailAddress != null) { organizationMemberRepository.ForceIgnoreSecurity(); var member = organizationMemberRepository.Find(null, m => m.PersonId == emailAddress.PersonId)?.Items?.FirstOrDefault(); organizationMemberRepository.ForceSecurity(); if (member != null) { //Already a member of the organization ModelState.AddModelError("Register", "Email address already exists"); return(BadRequest(ModelState)); } // Make a request to join organization var oldOrganization = organizationManager.GetDefaultOrganization(); if (oldOrganization != null) { //Update user if (!IsPasswordValid(signupModel.Password)) { ModelState.AddModelError("Password", PasswordRequirementMessage(signupModel.Password)); return(BadRequest(ModelState)); } var existingUser = await userManager.FindByEmailAsync(emailAddress.Address).ConfigureAwait(false); existingUser.Name = signupModel.Name; existingUser.ForcedPasswordChange = false; existingUser.PasswordHash = userManager.PasswordHasher.HashPassword(existingUser, signupModel.Password); var result = await userManager.UpdateAsync(existingUser).ConfigureAwait(true); if (!result.Succeeded) { return(GetErrorResult(result)); } Person person = personRepository.Find(null, p => p.Id == emailAddress.PersonId)?.Items?.FirstOrDefault(); person.Name = signupModel.Name; person.Department = signupModel.Department; personRepository.Update(person); //Create a new access request Model.Membership.AccessRequest accessRequest = new Model.Membership.AccessRequest() { OrganizationId = oldOrganization.Id, PersonId = person.Id, IsAccessRequested = true, AccessRequestedOn = DateTime.UtcNow }; accessRequestManager.AddAnonymousAccessRequest(accessRequest); return(Ok("Access Request has been created for existing user")); } } var user = new ApplicationUser() { Name = signupModel.Name, UserName = signupModel.Email, Email = signupModel.Email, ForcedPasswordChange = false //Set this property to not show password reset secreen for new user }; RandomPassword randomPass = new RandomPassword(); string passwordString = ""; bool isPasswordProvided = false; if (string.IsNullOrWhiteSpace(signupModel.Password)) { passwordString = randomPass.GenerateRandomPassword(); isPasswordProvided = false; } else { passwordString = signupModel.Password; isPasswordProvided = true; } var loginResult = await userManager.CreateAsync(user, passwordString).ConfigureAwait(false); bool IsEmailAllowed = emailSender.IsEmailAllowed(); if (!loginResult.Succeeded) { return(GetErrorResult(loginResult)); } else { //Add person email var emailIds = new List <EmailVerification>(); var personEmail = new EmailVerification() { PersonId = Guid.Empty, Address = signupModel.Email, IsVerified = false }; emailIds.Add(personEmail); Person newPerson = new Person() { Company = signupModel.Organization, Department = signupModel.Department, Name = signupModel.Name, EmailVerifications = emailIds }; var person = personRepository.Add(newPerson); var oldOrganization = organizationManager.GetDefaultOrganization(); if (oldOrganization != null) { //Add it to access requests Model.Membership.AccessRequest accessRequest = new Model.Membership.AccessRequest() { OrganizationId = oldOrganization.Id, PersonId = person.Id, IsAccessRequested = true, AccessRequestedOn = DateTime.UtcNow }; accessRequestManager.AddAnonymousAccessRequest(accessRequest); } if (IsEmailAllowed) { string code = await userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false); EmailMessage emailMessage = new EmailMessage(); EmailAddress address = new EmailAddress(user.Name, user.Email); emailMessage.To.Add(address); emailMessage.Body = SendConfirmationEmail(code, user.Id, passwordString, "en"); emailMessage.Subject = "Confirm your account at " + Constants.PRODUCT; await emailSender.SendEmailAsync(emailMessage).ConfigureAwait(false); } else { ModelState.AddModelError("Email", "Email is disabled. Verification email was not sent."); } //Update the user if (person != null) { var registeredUser = userManager.FindByNameAsync(user.UserName).Result; registeredUser.PersonId = (Guid)person.Id; registeredUser.ForcedPasswordChange = true; await userManager.UpdateAsync(registeredUser).ConfigureAwait(false); } } if (!IsEmailAllowed) { return(Ok(ModelState)); } else { return(Ok()); } }
public Task SendEmailAsync(EmailMessage emailMessage, string accountName = "") { EmailLog emailLog = new EmailLog(); //Find Email Settings and determine is email is enabled/disabled var organizationId = Guid.Parse(_organizationManager.GetDefaultOrganization().Id.ToString()); var emailSettings = _emailSettingsRepository.Find(null, s => s.OrganizationId == organizationId).Items.FirstOrDefault(); // If there are NO records in the Email Settings table for that Organization, email should be disabled if (emailSettings == null) { emailLog.Status = StatusType.Blocked.ToString(); emailLog.Reason = "Email disabled. Please configure email settings."; } if (emailSettings != null && emailSettings.IsEmailDisabled) { emailLog.Status = StatusType.Blocked.ToString(); emailLog.Reason = "Email functionality has been disabled."; } //Check if accountName exists var existingAccount = _emailAccountRepository.Find(null, d => d.Name.ToLower(null) == accountName.ToLower(null))?.Items?.FirstOrDefault(); if (existingAccount == null && emailSettings != null) { existingAccount = _emailAccountRepository.Find(null, a => a.IsDefault == true && a.IsDisabled == false)?.Items?.FirstOrDefault(); if (existingAccount == null) { emailLog.Status = StatusType.Failed.ToString(); } emailLog.Reason = $"Account '{accountName}' could be found."; if (existingAccount != null && existingAccount.IsDisabled == true) { emailLog.Status = StatusType.Blocked.ToString(); } emailLog.Reason = $"Account '{accountName}' has been disabled."; } //Set From Email Address if (existingAccount != null) { EmailAddress fromEmailAddress = new EmailAddress(existingAccount.FromName, existingAccount.FromEmailAddress); List <EmailAddress> emailAddresses = new List <EmailAddress>(); foreach (EmailAddress emailAddress in emailMessage.From) { if (!string.IsNullOrEmpty(emailAddress.Address)) { emailAddresses.Add(emailAddress); } } emailMessage.From.Clear(); foreach (EmailAddress emailAddress in emailAddresses) { emailMessage.From.Add(emailAddress); } emailMessage.From.Add(fromEmailAddress); } //Remove email addresses in to, cc, and bcc lists with domains that are blocked or not allowed List <EmailAddress> toList = new List <EmailAddress>(); List <EmailAddress> ccList = new List <EmailAddress>(); List <EmailAddress> bccList = new List <EmailAddress>(); if (string.IsNullOrEmpty(emailSettings.AllowedDomains)) { //Remove any email address that is in blocked domain IEnumerable <string>?denyList = (new List <string>(emailSettings?.BlockedDomains?.Split(','))).Select(s => s.ToLowerInvariant().Trim()); foreach (EmailAddress address in emailMessage.To) { if (!string.IsNullOrEmpty(address.Address)) { MailAddress mailAddress = new MailAddress(address.Address); if (!denyList.Contains(mailAddress.Host.ToLowerInvariant())) { toList.Add(address); } } } emailMessage.To.Clear(); emailMessage.To = toList; foreach (EmailAddress address in emailMessage.CC) { if (!string.IsNullOrEmpty(address.Address)) { MailAddress mailAddress = new MailAddress(address.Address); if (!denyList.Contains(mailAddress.Host.ToLowerInvariant())) { ccList.Add(address); } } } emailMessage.CC.Clear(); emailMessage.CC = ccList; foreach (EmailAddress address in emailMessage.Bcc) { if (!string.IsNullOrEmpty(address.Address)) { MailAddress mailAddress = new MailAddress(address.Address); if (!denyList.Contains(mailAddress.Host.ToLowerInvariant())) { bccList.Add(address); } } } emailMessage.Bcc.Clear(); emailMessage.Bcc = bccList; } else { //Remove any email address that is not on white list IEnumerable <string> allowList = (new List <string>(emailSettings.AllowedDomains.Split(','))).Select(s => s.ToLowerInvariant().Trim()); foreach (EmailAddress address in emailMessage.To) { if (!string.IsNullOrEmpty(address.Address)) { MailAddress mailAddress = new MailAddress(address.Address); if (allowList.Contains(mailAddress.Host.ToLowerInvariant())) { toList.Add(address); } } } emailMessage.To.Clear(); emailMessage.To = toList; foreach (EmailAddress address in emailMessage.CC) { if (!string.IsNullOrEmpty(address.Address)) { MailAddress mailAddress = new MailAddress(address.Address); if (allowList.Contains(mailAddress.Host.ToLowerInvariant())) { ccList.Add(address); } } } emailMessage.CC.Clear(); emailMessage.CC = ccList; foreach (EmailAddress address in emailMessage.Bcc) { if (!string.IsNullOrEmpty(address.Address)) { MailAddress mailAddress = new MailAddress(address.Address); if (allowList.Contains(mailAddress.Host.ToLowerInvariant())) { bccList.Add(address); } } } emailMessage.Bcc.Clear(); emailMessage.Bcc = bccList; } if (emailMessage.To.Count == 0) { emailLog.Status = StatusType.Blocked.ToString(); } emailLog.Reason = "No email addresses to send email to."; //Add any necessary additional email addresses (Administrators, etc.) if (!string.IsNullOrEmpty(emailSettings.AddToAddress)) { foreach (string toAddress in emailSettings.AddToAddress.Split(',')) { EmailAddress email = new EmailAddress(toAddress, toAddress); emailMessage.To.Add(email); } } if (!string.IsNullOrEmpty(emailSettings.AddCCAddress)) { foreach (string CCAddress in emailSettings.AddCCAddress.Split(',')) { EmailAddress email = new EmailAddress(CCAddress, CCAddress); emailMessage.CC.Add(email); } } if (!string.IsNullOrEmpty(emailSettings.AddBCCAddress)) { foreach (string BCCAddress in emailSettings.AddBCCAddress.Split(',')) { EmailAddress email = new EmailAddress(BCCAddress); emailMessage.Bcc.Add(email); } } //Add Subject and Body Prefixes/Suffixes if (!string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && !string.IsNullOrEmpty(emailSettings.SubjectAddSuffix)) { emailMessage.Subject = string.Concat(emailSettings.SubjectAddPrefix, emailMessage.Subject, emailSettings.SubjectAddSuffix); } if (!string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && string.IsNullOrEmpty(emailSettings.SubjectAddSuffix)) { emailMessage.Subject = string.Concat(emailSettings.SubjectAddPrefix, emailMessage.Subject); } if (string.IsNullOrEmpty(emailSettings.SubjectAddPrefix) && !string.IsNullOrEmpty(emailSettings.SubjectAddSuffix)) { emailMessage.Subject = string.Concat(emailMessage.Subject, emailSettings.SubjectAddSuffix); } else { emailMessage.Subject = emailMessage.Subject; } //Check if Email Message body is html or plaintext //emailMessage.IsBodyHtml = true; if (emailMessage.IsBodyHtml) { if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.Body = string.Concat(emailSettings.BodyAddPrefix, emailMessage.Body, emailSettings.BodyAddSuffix); } if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.Body = string.Concat(emailSettings.BodyAddPrefix, emailMessage.Body); } if (string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.Body = string.Concat(emailMessage.Body, emailSettings.BodyAddSuffix); } else { emailMessage.Body = emailMessage.Body; } } else { if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.PlainTextBody = string.Concat(emailSettings.BodyAddPrefix, emailMessage.PlainTextBody, emailSettings.BodyAddSuffix); } if (!string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.PlainTextBody = string.Concat(emailSettings.BodyAddPrefix, emailMessage.PlainTextBody); } if (string.IsNullOrEmpty(emailSettings.BodyAddPrefix) && !string.IsNullOrEmpty(emailSettings.BodyAddSuffix)) { emailMessage.PlainTextBody = string.Concat(emailMessage.PlainTextBody, emailSettings.BodyAddSuffix); } else { emailMessage.PlainTextBody = emailMessage.Body; } } //Send email ISendEmailChore sendEmailChore = null; if (existingAccount != null) { if (existingAccount.Provider == "SMTP") { sendEmailChore = new SmtpSendEmailChore(existingAccount, emailSettings); } else if (existingAccount.Provider == "Azure") { sendEmailChore = new AzureSendEmailChore(emailSettings, existingAccount); } } if (sendEmailChore != null) { try { if (emailLog.Status != StatusType.Blocked.ToString() || emailLog.Status != StatusType.Failed.ToString()) { ; } { sendEmailChore.SendEmail(emailMessage); emailLog.Status = StatusType.Sent.ToString(); emailLog.Reason = "Email was sent successfully."; } } catch (Exception ex) { emailLog.Status = StatusType.Failed.ToString(); emailLog.Reason = "Error: " + ex.Message; } } else { emailLog.Status = StatusType.Failed.ToString(); emailLog.Reason = "Email failed to send."; } //Log email and its status emailLog.Id = Guid.NewGuid(); if (existingAccount != null) { emailLog.EmailAccountId = Guid.Parse(existingAccount.Id.ToString()); } emailLog.SentOnUTC = DateTime.UtcNow; string newEmailMessage = Regex.Replace(emailMessage.Body, @"(<sensitive(\s|\S)*?<\/sensitive>)", "NULL"); emailLog.EmailObjectJson = JsonConvert.SerializeObject(newEmailMessage); List <string> nameList = new List <string>(); List <string> emailList = new List <string>(); foreach (EmailAddress address in emailMessage.From) { nameList.Add(address.Name); emailList.Add(address.Address); } emailLog.SenderName = JsonConvert.SerializeObject(nameList); emailLog.SenderAddress = JsonConvert.SerializeObject(emailList); emailLog.CreatedOn = DateTime.UtcNow; emailLog.CreatedBy = applicationUser?.UserName; emailLog.SenderUserId = applicationUser?.PersonId; _emailLogRepository.Add(emailLog); return(Task.CompletedTask); }
public StorageDrive AddStorageDrive(StorageDrive drive) { Guid?organizationId = _organizationManager.GetDefaultOrganization().Id; var existingDrive = _storageDriveRepository.Find(null).Items?.Where(q => q.OrganizationId == organizationId && q.Name.ToLower() == drive.Name.ToLower()).FirstOrDefault(); if (existingDrive != null) { throw new EntityAlreadyExistsException($"Drive {drive.Name} already exists within this organization"); } CheckDefaultDrive(drive, organizationId); var adapterType = drive.FileStorageAdapterType; if (string.IsNullOrEmpty(adapterType)) { adapterType = AdapterType.LocalFileStorage.ToString(); } //check if a new drive can be created for the current organization long?maxSizeInBytes = drive.MaxStorageAllowedInBytes; //size of new drive long?organizationStorage = GetTotalOrganizationStorage(organizationId); //sum of all drives for the current organization long?orgMaxSizeInBytes = _organizationManager.GetMaxStorageInBytes(organizationId); //max allowed storage for the current organization long?updatedOrgStorage = maxSizeInBytes + organizationStorage; //sum of new drive and all existing drives if (orgMaxSizeInBytes != null && maxSizeInBytes > orgMaxSizeInBytes) { throw new EntityOperationException("Drive size would exceed the allowed storage space for this organization"); } if (string.IsNullOrEmpty(drive.StoragePath)) { drive.StoragePath = drive.Name; } if (drive.MaxStorageAllowedInBytes == null) { drive.MaxStorageAllowedInBytes = orgMaxSizeInBytes; } if (string.IsNullOrEmpty(drive.FileStorageAdapterType)) { drive.FileStorageAdapterType = AdapterType.LocalFileStorage.ToString(); } if (drive.IsDefault == null) { drive.IsDefault = false; } var storageDrive = new StorageDrive() { Name = drive.Name, FileStorageAdapterType = drive.FileStorageAdapterType, OrganizationId = organizationId, StoragePath = drive.StoragePath, CreatedBy = _httpContextAccessor.HttpContext.User.Identity.Name, CreatedOn = DateTime.UtcNow, StorageSizeInBytes = drive.StorageSizeInBytes ?? 0, MaxStorageAllowedInBytes = drive.MaxStorageAllowedInBytes, IsDefault = drive.IsDefault }; _storageDriveRepository.Add(storageDrive); _webhookPublisher.PublishAsync("Files.NewDriveCreated", storageDrive.Id.ToString(), storageDrive.Name); return(storageDrive); }