public void Create(IUnitOfWork uow, Fr8AccountDO submittedDockyardAccountData) { submittedDockyardAccountData.State = UserState.Active; submittedDockyardAccountData.Id = Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(submittedDockyardAccountData.UserName)) { submittedDockyardAccountData.UserName = submittedDockyardAccountData.EmailAddress != null ? submittedDockyardAccountData.EmailAddress.Address : null; } if (string.IsNullOrEmpty(submittedDockyardAccountData.UserName)) { throw new ApplicationException("User must have username or email address"); } submittedDockyardAccountData.EmailAddress = uow.EmailAddressRepository.GetOrCreateEmailAddress(submittedDockyardAccountData.EmailAddress.Address); submittedDockyardAccountData.Roles.ToList().ForEach(e => uow.AspNetUserRolesRepository.Add(new AspNetUserRolesDO { RoleId = e.RoleId, UserId = submittedDockyardAccountData.Id })); submittedDockyardAccountData.Roles.Clear(); var userManager = new DockyardIdentityManager(uow); var result = userManager.Create(submittedDockyardAccountData); if (!result.Succeeded) { throw new AggregateException(result.Errors.Select(s => new ApplicationException(s))); } uow.SaveChanges(); EventManager.ExplicitCustomerCreated(submittedDockyardAccountData.Id); }
public Task <Tuple <LoginStatus, string> > ProcessLoginRequest(string username, string password, bool isPersistent, HttpRequestMessage request = null) { using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { LoginStatus curLoginStatus; string userId; Fr8AccountDO fr8AccountDO = uow.UserRepository.FindOne(x => x.UserName == username); if (fr8AccountDO != null) { userId = fr8AccountDO.Id; if (string.IsNullOrEmpty(fr8AccountDO.PasswordHash)) { curLoginStatus = LoginStatus.ImplicitUser; } else { curLoginStatus = Login(uow, fr8AccountDO, password, isPersistent); } } else { curLoginStatus = LoginStatus.UnregisteredUser; userId = ""; } return(Task.FromResult(Tuple.Create(curLoginStatus, userId))); } }
public void Update(IUnitOfWork uow, Fr8AccountDO submittedDockyardAccountData, Fr8AccountDO existingDockyardAccount) { existingDockyardAccount.FirstName = submittedDockyardAccountData.FirstName; existingDockyardAccount.LastName = submittedDockyardAccountData.LastName; //Remove old roles foreach (var existingRole in existingDockyardAccount.Roles.ToList()) { if (!submittedDockyardAccountData.Roles.Select(role => role.RoleId).Contains(existingRole.RoleId)) { uow.AspNetUserRolesRepository.Remove( uow.AspNetUserRolesRepository.FindOne( e => e.RoleId == existingRole.RoleId && e.UserId == existingDockyardAccount.Id)); } } //Add new roles foreach (var newRole in submittedDockyardAccountData.Roles) { if (!existingDockyardAccount.Roles.Select(role => role.RoleId).Contains(newRole.RoleId)) { uow.AspNetUserRolesRepository.Add(new AspNetUserRolesDO { RoleId = newRole.RoleId, UserId = submittedDockyardAccountData.Id }); } } uow.SaveChanges(); }
private async Task <PlanDO> CreateAndConfigureNewPlan(Fr8AccountDO systemUser) { using (var uow = _unitOfWorkFactory.Create()) { var activityTemplates = uow.ActivityTemplateRepository.GetQuery().ToArray(); var result = await CreatePlanWithMonitoringActivity(uow, systemUser, activityTemplates).ConfigureAwait(false); Logger.GetLogger().Info($"{ManifestMonitoringPrefix}Created a plan"); try { await ConfigureMonitoringActivity(uow, systemUser, result.ChildNodes[0].ChildNodes[0] as ActivityDO).ConfigureAwait(false); Logger.GetLogger().Info($"{ManifestMonitoringPrefix}Configured Monitor Form Response activity"); await ConfigureBuildMessageActivity(uow, systemUser, activityTemplates, result.Id).ConfigureAwait(false); Logger.GetLogger().Info($"{ManifestMonitoringPrefix}Configured Build Message activity"); await ConfigureSaveJiraActivity(uow, systemUser, activityTemplates, result.Id).ConfigureAwait(false); Logger.GetLogger().Info($"{ManifestMonitoringPrefix}Configured Save Jira activity"); } catch { await _plan.Delete(result.Id); throw; } return(result); } }
private async Task ConfigureMonitoringActivity(IUnitOfWork uow, Fr8AccountDO systemUser, ActivityDO monitoringActivity) { using (var activityStorage = _crateManager.GetUpdatableStorage(monitoringActivity)) { var authenticationCrate = activityStorage.FirstCrateOrDefault <StandardAuthenticationCM>(); if (authenticationCrate != null) { throw new ApplicationException("There is no default authentication token for system user in Google terminal"); } var controls = activityStorage.CrateContentsOfType <StandardConfigurationControlsCM>().SingleOrDefault(); if (controls == null) { throw new ApplicationException("Monitor Form Responses doesn't contain controls crate"); } var formsSelector = controls.FindByName <DropDownList>("Selected_Google_Form"); if (formsSelector == null) { throw new ApplicationException("Monitor Form Responses doesn't contain form selector control"); } var formId = _configRepository.Get("ManifestSubmissionFormId"); if (string.IsNullOrEmpty(formId)) { throw new ApplicationException("Configuration doesn't contain info about form Id to monitor"); } formsSelector.SelectByValue(formId); if (string.IsNullOrEmpty(formsSelector.Value)) { throw new ApplicationException("Form specified in configuration doesn't belong to system user's account Google authorization"); } } await _activity.Configure(uow, systemUser.Id, monitoringActivity).ConfigureAwait(false); }
public static void CustomerCreated(Fr8AccountDO user) { if (AlertCustomerCreated != null) { AlertCustomerCreated(user); } }
public static void UserRegistration(Fr8AccountDO curUser) { if (AlertUserRegistration != null) { AlertUserRegistration(curUser); } }
public void UpdatePassword(IUnitOfWork uow, Fr8AccountDO dockyardAccountDO, string password) { if (dockyardAccountDO != null) { uow.UserRepository.UpdateUserCredentials(dockyardAccountDO, password: password); } }
//public void DispatchNegotiationRequests(IUnitOfWork uow, EmailDO generatedEmailDO, int negotiationID) //{ // DispatchNegotiationRequests(uow, generatedEmailDO, uow.NegotiationsRepository.GetByKey(negotiationID)); //} //public void DispatchNegotiationRequests(IUnitOfWork uow, EmailDO generatedEmailDO, NegotiationDO negotiationDO) //{ // var batches = generatedEmailDO.Recipients.GroupBy(r => // { // var curUserDO = uow.UserRepository.GetOrCreateUser(r.EmailAddress); // return GetCRTemplate(curUserDO); // }); // foreach (var batch in batches) // { // DispatchBatchedNegotiationRequests(uow, batch.Key, generatedEmailDO.HTMLText, batch.ToList(), negotiationDO); // } //} //public void DispatchBatchedNegotiationRequests(IUnitOfWork uow, String templateName, String htmlText, IList<RecipientDO> recipients, NegotiationDO negotiationDO) //{ // if (!recipients.Any()) // return; // var emailDO = new EmailDO(); // //This means, when the customer replies, their client will include the bookingrequest id // emailDO.TagEmailToBookingRequest(negotiationDO.BookingRequest); // var customer = negotiationDO.BookingRequest.Customer; // var mode = _user.GetMode(customer); // if (mode == CommunicationMode.Direct) // { // var directEmailAddress = _configRepository.Get("EmailFromAddress_DirectMode"); // var directEmailName = _configRepository.Get("EmailFromName_DirectMode"); // emailDO.From = uow.EmailAddressRepository.GetOrCreateEmailAddress(directEmailAddress); // emailDO.FromName = directEmailName; // } // else // { // var delegateEmailAddress = _configRepository.Get("EmailFromAddress_DelegateMode"); // var delegateEmailName = _configRepository.Get("EmailFromName_DelegateMode"); // emailDO.From = uow.EmailAddressRepository.GetOrCreateEmailAddress(delegateEmailAddress); // emailDO.FromName = String.Format(delegateEmailName, customer.DisplayName); // } // emailDO.Subject = string.Format("Need Your Response on {0} {1} event: {2}", // negotiationDO.BookingRequest.Customer.FirstName, // (negotiationDO.BookingRequest.Customer.LastName ?? ""), // "RE: " + negotiationDO.Name); // var responseUrl = String.Format("NegotiationResponse/View?negotiationID={0}", negotiationDO.Id); // var tokenUrls = new List<String>(); // foreach (var attendee in recipients) // { // emailDO.AddEmailRecipient(EmailParticipantType.To, attendee.EmailAddress); // var curUserDO = uow.UserRepository.GetOrCreateUser(attendee.EmailAddress); // var tokenURL = uow.AuthorizationTokenRepository.GetAuthorizationTokenURL(responseUrl, curUserDO); // tokenUrls.Add(tokenURL); // } // uow.EmailRepository.Add(emailDO); // var summaryQandAText = _negotiation.GetSummaryText(negotiationDO); // string currBookerAddress = negotiationDO.BookingRequest.Booker.EmailAddress.Address; // var conversationThread = _br.GetConversationThread(negotiationDO.BookingRequest); // // Fix an issue when coverting to UTF-8 // conversationThread = conversationThread.Replace((char)160, (char)32); // //uow.EnvelopeRepository.ConfigureTemplatedEmail(emailDO, templateName, // //new Dictionary<string, object> // //{ // // {"RESP_URL", tokenUrls}, // // {"bodytext", htmlText}, // // {"questions", String.Join("<br/>", summaryQandAText)}, // // {"conversationthread", conversationThread}, // // {"bookername", currBookerAddress.Replace("@kwasant.com","")} // //}); // negotiationDO.NegotiationState = NegotiationState.AwaitingClient; // //Everyone who gets an email is now an attendee. // var currentAttendeeIDs = negotiationDO.Attendees.Select(a => a.EmailAddressID).ToList(); // foreach (var recipient in recipients) // { // if (!currentAttendeeIDs.Contains(recipient.EmailAddressID)) // { // var newAttendee = new AttendeeDO // { // EmailAddressID = recipient.EmailAddressID, // Name = recipient.EmailAddress.Name, // NegotiationID = negotiationDO.Id // }; // uow.AttendeeRepository.Add(newAttendee); // } // } //} public string GetCRTemplate(Fr8AccountDO curDockyardAccountDO) { string templateName; // Max Kostyrkin: currently DockYardAccount#GetMode returns Direct if user has a booking request or has a password, otherwise Delegate. switch (_dockyardAccount.GetMode(curDockyardAccountDO)) { case CommunicationMode.Direct: templateName = _configRepository.Get("CR_template_for_creator"); break; case CommunicationMode.Delegate: templateName = _configRepository.Get("CR_template_for_precustomer"); break; case CommunicationMode.Precustomer: templateName = _configRepository.Get("CR_template_for_precustomer"); break; default: throw new ArgumentOutOfRangeException(); } return(templateName); }
private void ReportAuthError(IUnitOfWork uow, Fr8AccountDO user, InvalidTokenRuntimeException ex) { var activityTemplate = ex?.FailedActivityDTO.ActivityTemplate; var errorMessage = $"Activity {ex?.FailedActivityDTO.Label} was unable to authenticate with remote web-service."; errorMessage += $"Please re-authorize {ex?.FailedActivityDTO.Label} activity " + $"by clicking on the Settings dots in the upper " + $"right corner of the activity and then selecting Choose Authentication. "; // Try getting specific the instructions provided by the terminal. if (!String.IsNullOrEmpty(ex.Message)) { errorMessage += "Additional instructions from the terminal: "; errorMessage += ex.Message; } _pusherNotifier.NotifyUser(new NotificationMessageDTO { NotificationType = NotificationType.GenericFailure, Subject = "Plan Failed", Message = errorMessage, Collapsed = false }, user.Id); }
public IHttpActionResult Login([FromUri] string username, [FromUri] string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { Logger.GetLogger().Warn($"Username or password is not specified"); return(BadRequest("Username or password is not specified")); } Request.GetOwinContext().Authentication.SignOut(); using (IUnitOfWork uow = ObjectFactory.GetInstance <IUnitOfWork>()) { Fr8AccountDO dockyardAccountDO = uow.UserRepository.FindOne(x => x.UserName == username); if (dockyardAccountDO != null) { var passwordHasher = new PasswordHasher(); if (passwordHasher.VerifyHashedPassword(dockyardAccountDO.PasswordHash, password) == PasswordVerificationResult.Success) { ISecurityServices security = ObjectFactory.GetInstance <ISecurityServices>(); ClaimsIdentity identity = security.GetIdentity(uow, dockyardAccountDO); Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity); return(Ok()); } } } Logger.GetLogger().Warn($"Loging failed for {username}"); return(StatusCode(HttpStatusCode.Forbidden)); }
//public void Create(IUnitOfWork uow, UserDO submittedUserData, string role, bool sendEmail) //{ // if (sendEmail) // { // new Email().SendUserSettingsNotification(uow, submittedUserData); // } // new Account().Register(uow, submittedUserData.EmailAddress.Address, submittedUserData.FirstName, submittedUserData.LastName, "test@1234", role); //} //if we have a first name and last name, use them together //else if we have a first name only, use that //else if we have just an email address, use the portion preceding the @ unless there's a name //else throw public string GetDisplayName(Fr8AccountDO curDockyardAccount) { string firstName = curDockyardAccount.FirstName; string lastName = curDockyardAccount.LastName; if (firstName != null) { if (lastName == null) { return(firstName); } return(firstName + " " + lastName); } EmailAddressDO curEmailAddress = curDockyardAccount.EmailAddress; if (curEmailAddress.Name != null) { return(curEmailAddress.Name); } RegexUtilities.ValidateEmailAddress(_configRepository, curEmailAddress.Address); return(curEmailAddress.Address.Split(new[] { '@' })[0]); }
private PlanDO GetExistingPlan(Fr8AccountDO systemUser) { using (var uow = _unitOfWorkFactory.Create()) { return(uow.PlanRepository.GetPlanQueryUncached().FirstOrDefault(x => x.Name == MonitoringPlanName && x.Fr8AccountId == systemUser.Id && x.PlanState != PlanState.Deleted)); } }
// Return the Containers of current Account public IList <ContainerDO> GetByFr8Account(IUnitOfWork unitOfWork, Fr8AccountDO account, bool isAdmin = false, Guid?id = null) { if (account.Id == null) { throw new ApplicationException("UserId must not be null"); } var containerRepository = unitOfWork.ContainerRepository.GetQuery(); return((id == null ? containerRepository.Where(container => container.Plan.Fr8Account.Id == account.Id) : containerRepository.Where(container => container.Id == id && container.Plan.Fr8Account.Id == account.Id)).ToList()); }
public void SendUserSettingsNotification(IUnitOfWork uow, Fr8AccountDO submittedDockyardAccountData) { EmailDO curEmail = new EmailDO(); curEmail.From = submittedDockyardAccountData.EmailAddress; curEmail.AddEmailRecipient(EmailParticipantType.To, submittedDockyardAccountData.EmailAddress); curEmail.Subject = "DockYardAccount Settings Notification"; //new Email(uow).SendTemplate(uow, "User_Settings_Notification", curEmail, null); //uow.EnvelopeRepository.ConfigureTemplatedEmail(curEmail, "User_Settings_Notification", null); }
/// <summary> /// Determines <see cref="CommunicationMode">communication mode</see> for user /// </summary> /// <param name="dockyardAccountDO">DockYardAccount</param> /// <returns>Direct if the user has a booking request or a password. Otherwise, Delegate.</returns> public CommunicationMode GetMode(Fr8AccountDO dockyardAccountDO) { //if (userDO.UserBookingRequests != null && userDO.UserBookingRequests.Any()) // return CommunicationMode.Direct; if (!String.IsNullOrEmpty(dockyardAccountDO.PasswordHash)) { return(CommunicationMode.Direct); } return(CommunicationMode.Delegate); }
public async Task <ExternalAuthUrlDTO> GetOAuthInitiationURL( Fr8AccountDO user, TerminalDO terminal) { if (terminal.AuthenticationType == AuthenticationType.None) { throw new WrongAuthenticationTypeException(); } var restClient = ObjectFactory.GetInstance <IRestfulServiceClient>(); var response = await restClient.PostAsync( new Uri(terminal.Endpoint + "/authentication/request_url"), null, _terminalService.GetRequestHeaders(terminal, user.Id)); var externalAuthUrlDTO = JsonConvert.DeserializeObject <ExternalAuthUrlDTO>(response); using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { var authToken = uow.AuthorizationTokenRepository .GetPublicDataQuery() .FirstOrDefault(x => x.TerminalID == terminal.Id && x.UserID == user.Id && x.ExternalAccountId == null && x.ExternalStateToken != null ); if (authToken == null) { var curTerminal = _terminalService.GetByKey(terminal.Id); var curAccount = uow.UserRepository.GetByKey(user.Id); authToken = new AuthorizationTokenDO { UserID = curAccount.Id, TerminalID = curTerminal.Id, ExternalStateToken = externalAuthUrlDTO.ExternalStateToken }; uow.AuthorizationTokenRepository.Add(authToken); } else { authToken.ExternalAccountId = null; authToken.Token = null; authToken.ExternalStateToken = externalAuthUrlDTO.ExternalStateToken; } uow.SaveChanges(); } return(externalAuthUrlDTO); }
private Traits GetProperties(Fr8AccountDO fr8AccountDO) { return(new Traits { { "First Name", fr8AccountDO.FirstName }, { "Last Name", fr8AccountDO.LastName }, { "Username", fr8AccountDO.UserName }, { "Email", fr8AccountDO.EmailAddress.Address }, { "Delegate Account", _fr8Account.GetMode(fr8AccountDO) == CommunicationMode.Delegate }, { "Class", fr8AccountDO.Class } }); }
public void Registered(string anonimousId, Fr8AccountDO fr8AccountDO) { if (Analytics.Client == null) { return; } var userProperties = GetProperties(fr8AccountDO); Analytics.Client.Identify(fr8AccountDO.Id, userProperties); Analytics.Client.Track(fr8AccountDO.Id, "User Registered"); }
/// <summary> /// Updates status of current user /// </summary> /// <remarks> /// User must be logged in /// </remarks> /// <param name="userId">User Id</param> /// <param name="status">Status to set. 0 - deleted, 1 - active</param> public void UpdateStatus(string userId, int status) { using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { Fr8AccountDO curDockyardAccount = uow.UserRepository.GetQuery().Where(user => user.Id == userId).FirstOrDefault(); if (curDockyardAccount != null) { curDockyardAccount.State = status; uow.SaveChanges(); } } }
public override void SetUp() { base.SetUp(); _testUserAccount = FixtureData.TestUser1(); using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { uow.UserRepository.Add(_testUserAccount); uow.SaveChanges(); ObjectFactory.GetInstance <ISecurityServices>().Login(uow, _testUserAccount); } }
public bool IsValidHashedPassword(Fr8AccountDO dockyardAccountDO, string password) { if (dockyardAccountDO != null) { var passwordHasher = new PasswordHasher(); return(passwordHasher.VerifyHashedPassword(dockyardAccountDO.PasswordHash, password) == PasswordVerificationResult.Success); } else { return(false); } }
private void AssignProfileToUser(IUnitOfWork uow, Fr8AccountDO fr8Account, string profileName) { var profile = uow.ProfileRepository.GetQuery().FirstOrDefault(x => x.Name == profileName); if (profile != null) { fr8Account.ProfileId = profile.Id; } else { throw new ApplicationException($"Profile '{profileName}' not found for User"); } }
public void CanCreatedUser() { // DataProtectionProvider property is not getting initialised through startup // So Initiliaze it explicitly. DpapiDataProtectionProvider is used for test cases only DockyardIdentityManager.DataProtectionProvider = new DpapiDataProtectionProvider("fr8"); using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { Fr8AccountDO curDockyardAccountLocal = FixtureData.TestDockyardAccount4(); _fr8Account.Create(uow, curDockyardAccountLocal); Fr8AccountDO curDockyardAccountLocalNew = uow.UserRepository.GetQuery().Where(u => u.UserName == curDockyardAccountLocal.UserName).FirstOrDefault(); Assert.AreEqual(curDockyardAccountLocalNew.UserName, curDockyardAccountLocal.UserName); } }
public void CanAddUser() { using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { uow.AspNetRolesRepository.Add(FixtureData.TestRole()); //SETUP Fr8AccountDO currDockyardAccountDO = new Fr8AccountDO(); uow.UserRepository.Add(currDockyardAccountDO); Fr8AccountDO currRetrivedDockyardAccountDO = uow.UserRepository.GetQuery().FirstOrDefault(uu => currDockyardAccountDO.EmailAddressID == uu.EmailAddressID); } }
private PlanTemplateCM CreatePlanTemplateCM(PublishPlanTemplateDTO dto, PlanTemplateCM existing, Fr8AccountDO account) { return(new PlanTemplateCM() { Name = dto.Name, Description = dto.Description, ParentPlanId = dto.ParentPlanId.ToString(), PlanContents = dto.PlanContents, Version = existing?.Version ?? 1, OwnerId = account.Id, OwnerName = account.UserName }); }
public void UserRegistered(Fr8AccountDO curUser) { FactDO curFactDO = new FactDO { PrimaryCategory = "User", SecondaryCategory = "", Activity = "Registered", Fr8UserId = curUser.Id, ObjectId = null, Data = string.Format("User registrated with :{0},", curUser.EmailAddress.Address) //Data = "User registrated with " + curUser.EmailAddress.Address }; SaveAndLogFact(curFactDO); }
public void Identify(Fr8AccountDO fr8AccountDO) { if (Analytics.Client == null) { return; } var props = new Segment.Model.Properties(); foreach (var prop in GetProperties(fr8AccountDO)) { props.Add(prop.Key, prop.Value); } Analytics.Client.Identify(fr8AccountDO.Id, GetProperties(fr8AccountDO)); //Analytics.Client.Track(fr8AccountDO.Id, "User Logged In", props); }
public void Login(IUnitOfWork uow, Fr8AccountDO fr8AccountDO) { ClaimsIdentity identity = GetIdentity(uow, fr8AccountDO); HttpContext.Current.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity); var curUserRoles = GetRoleNames(); if (!curUserRoles.Contains(Roles.Guest)) { ObjectFactory.GetInstance <ITracker>().Identify(fr8AccountDO); } }
public Task <Tuple <LoginStatus, string> > CreateAuthenticateGuestUser() { Guid guid = Guid.NewGuid(); string guestUserEmail = guid + "@fr8.co"; string guestUserPassword = "******"; using (var uow = ObjectFactory.GetInstance <IUnitOfWork>()) { // Register a guest user Fr8AccountDO fr8AccountDO = Register(uow, guestUserEmail, guestUserEmail, guestUserEmail, guestUserPassword, Roles.Guest); uow.SaveChanges(); var loginStatus = Login(uow, fr8AccountDO, guestUserPassword, false); var userId = fr8AccountDO.Id; return(Task.FromResult(Tuple.Create(loginStatus, userId))); } }