private Member CreateMinimalMember() { // Crate a member with everything set. var member = new Member { Address = new Address { Location = _locationQuery.ResolveLocation(_locationQuery.GetCountry(Country), null) }, EmailAddresses = new[] { new EmailAddress { Address = PrimaryEmailAddress } }, FirstName = FirstName, LastName = LastName, VisibilitySettings = new VisibilitySettings(), IsActivated = true, IsEnabled = true, }; var credentials = new LoginCredentials { LoginId = PrimaryEmailAddress, PasswordHash = LoginCredentials.HashToString(Password) }; _memberAccountsCommand.CreateMember(member, credentials, null); return(member); }
public static void HashPasswords(string[] args) { if (args.Length < 2) { Program.Usage(); return; } Console.WriteLine("Plaintext\tHash (base64)\t\t\tHash (hex)"); Console.WriteLine(); for (int i = 1; i < args.Length; i++) { string plainText = args[i]; string base64 = args[i]; byte[] bytes; if (plainText.EndsWith("==")) { // The input is actually a base64 hash, not plaintext. bytes = Convert.FromBase64String(args[i]); plainText = "????????"; } else { bytes = LoginCredentials.HashToBytes(args[i]); base64 = LoginCredentials.HashToString(args[i]); } Console.WriteLine("{0}\t{1}\t{2}", plainText, base64, StringUtils.ByteArrayToHexString(bytes)); } Console.WriteLine(); Console.WriteLine("You can check the strength by entering the hex value at http://passcracking.com/"); }
protected override Member CreateMember() { // These must always be set. var member = new Member { FirstName = FirstName, LastName = LastName, EmailAddresses = new List <EmailAddress> { new EmailAddress { Address = EmailAddress } }, Address = new Address { Location = _locationQuery.ResolveLocation(_locationQuery.GetCountry(Country), Location) }, }; var credentials = new LoginCredentials { LoginId = EmailAddress, PasswordHash = LoginCredentials.HashToString(member.GetPassword()), }; _memberAccountsCommand.CreateMember(member, credentials, null); return(member); }
public void TestValidUserWithoutPermissions() { var ats = _integrationQuery.GetIntegrationSystem <Ats>(_jobG8Query.GetIntegratorUser().IntegrationSystemId); var integratorUser = new IntegratorUser { LoginId = "JobAdFeedTestUser", PasswordHash = LoginCredentials.HashToString(Password), Permissions = IntegratorPermissions.GetJobApplication, IntegrationSystemId = ats.Id, }; _integrationCommand.CreateIntegratorUser(integratorUser); var request = new PostAdvertRequestMessage { UserCredentials = new Credentials { Username = "******", Password = Password } }; var employer = CreateEmployer(0); PostAdvert(employer, request); }
private IntegratorUser AuthenticateRequest(string userName, string password, IntegratorPermissions permissions) { if (string.IsNullOrEmpty(userName)) { throw new UserException(NoUserNameError); } if (string.IsNullOrEmpty(password)) { throw new UserException(NoPasswordError); } var user = _integrationQuery.GetIntegratorUser(userName); if (user == null) { throw new UserException(string.Format(UnknownUserError, userName)); } var passwordHash = LoginCredentials.HashToString(password); if (passwordHash != user.PasswordHash) { throw new UserException(string.Format(IncorrectPasswordError, userName)); } if (!user.Permissions.IsFlagSet(permissions)) { throw new UserException(string.Format(PermissionDeniedError, user.LoginId)); } return(user); }
AuthenticationStatus IDevAuthenticationManager.AuthenticateUser(string password) { // For test case purposes also check directly against the hash. return(LoginCredentials.HashToString(password) == _passwordHash || password == _passwordHash ? AuthenticationStatus.Authenticated : AuthenticationStatus.Failed); }
public ActionResult ChangePassword(Guid id, EmployerLoginModel employerLogin, [Bind(Include = "SendPasswordEmail")] CheckBoxValue sendPasswordEmail) { var employer = _employersQuery.GetEmployer(id); if (employer == null) { return(NotFound("employer", "id", id)); } var credentials = _loginCredentialsQuery.GetCredentials(employer.Id); if (credentials == null) { return(NotFound("employer", "id", id)); } try { // Validate. employerLogin.SendPasswordEmail = sendPasswordEmail.IsChecked; employerLogin.Validate(); // Update. credentials.PasswordHash = LoginCredentials.HashToString(employerLogin.Password); credentials.MustChangePassword = true; _loginCredentialsCommand.UpdateCredentials(employer.Id, credentials, User.Id().Value); string message; if (employerLogin.SendPasswordEmail) { var members = _accountReportsQuery.GetUsers(UserType.Member, DateTime.Now); _emailsCommand.TrySend(new NewEmployerWelcomeEmail(employer, credentials.LoginId, employerLogin.Password, members)); message = "The password has been reset and an email has been sent."; } else { message = "The password has been reset."; } return(RedirectToRouteWithConfirmation(EmployersRoutes.Edit, new { id }, message)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } employerLogin.LoginId = credentials.LoginId; return(View("Edit", new UserModel <IEmployer, EmployerLoginModel> { User = _employersQuery.GetEmployer(id), UserLogin = employerLogin })); }
public ActionResult Convert(string verticalUrl, ConvertModel convertModel) { var community = GetCommunity(verticalUrl); if (community == null) { return(RedirectToRoute(Public.Routes.HomeRoutes.Home)); } convertModel.Community = community; try { convertModel.Prepare(); convertModel.Validate(); // Find the member. var member = _membersQuery.GetMember(convertModel.EmailAddress); if (member == null) { throw new ValidationErrorsException(new NotFoundValidationError("Account", null)); } // Must be a member of the community and the details must match. if (!MatchAccount(member, community, convertModel)) { throw new ValidationErrorsException(new NotFoundValidationError("Account", null)); } // Create the credentials. var credentials = new LoginCredentials { LoginId = convertModel.NewEmailAddress, PasswordHash = LoginCredentials.HashToString(convertModel.Password), }; _memberAccountsCommand.CreateCredentials(member, credentials); // Send an email if needed. if (!member.IsActivated) { _accountVerificationsCommand.SendActivation(member, member.GetPrimaryEmailAddress().Address); } return(RedirectToRoute(VerticalsRoutes.Converted)); } catch (UserException ex) { ModelState.AddModelError(ex, new VerticalsErrorHandler()); } return(View(convertModel)); }
public ActionResult ChangePassword(Guid id, MemberLoginModel memberLogin, [Bind(Include = "SendPasswordEmail")] CheckBoxValue sendPasswordEmail) { var member = _membersQuery.GetMember(id); if (member == null) { return(NotFound("member", "id", id)); } var credentials = _loginCredentialsQuery.GetCredentials(member.Id); if (credentials == null) { return(NotFound("member", "id", id)); } try { // Validate. memberLogin.SendPasswordEmail = sendPasswordEmail.IsChecked; memberLogin.Validate(); // Update. credentials.PasswordHash = LoginCredentials.HashToString(memberLogin.Password); credentials.MustChangePassword = true; _loginCredentialsCommand.UpdateCredentials(member.Id, credentials, User.Id().Value); string message; if (memberLogin.SendPasswordEmail) { var reminderEmail = new PasswordReminderEmail(member, credentials.LoginId, memberLogin.Password); _emailsCommand.TrySend(reminderEmail); message = "The password has been reset and an email has been sent."; } else { message = "The password has been reset."; } return(RedirectToRouteWithConfirmation(MembersRoutes.Edit, new { id }, message)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } memberLogin.LoginId = credentials.LoginId; return(View("Edit", new UserModel <IMember, MemberLoginModel> { User = _membersQuery.GetMember(id), UserLogin = memberLogin })); }
private void UpdateCredentials(Guid employerId, LoginCredentials credentials, string loginId, string password, string confirmPassword, bool useLinkedInProfile) { if (credentials == null) { if (!string.IsNullOrEmpty(loginId) || !string.IsNullOrEmpty(password) || !string.IsNullOrEmpty(confirmPassword)) { // No existing credentials but trying to create some. var credentialsModel = new LoginCredentialsModel { LoginId = loginId, Password = password, ConfirmPassword = confirmPassword }; credentialsModel.Validate(); _loginCredentialsCommand.CreateCredentials(employerId, new LoginCredentials { LoginId = loginId, PasswordHash = LoginCredentials.HashToString(password) }); } } else { if (loginId != credentials.LoginId) { // Cannot remove the login id. if (string.IsNullOrEmpty(loginId)) { throw new ValidationErrorsException(new RequiredValidationError("LoginId")); } // Check not trying to someone else's login id. if (_loginCredentialsQuery.DoCredentialsExist(new LoginCredentials { LoginId = loginId })) { throw new DuplicateUserException(); } // Update the credentials. credentials.LoginId = loginId; _loginCredentialsCommand.UpdateCredentials(employerId, credentials, employerId); } // If not wanting to use LinkedIn any more then remove the profile. if (!useLinkedInProfile) { _linkedInCommand.DeleteProfile(employerId); } } }
public ActionResult Account(Login loginModel, [Bind(Include = "RememberMe")] CheckBoxValue rememberMe) { try { // Process the post to check validations etc. loginModel.RememberMe = rememberMe != null && rememberMe.IsChecked; loginModel.Prepare(); loginModel.Validate(); Save(loginModel, new EmployerJoin(), false); // Authenticate. var result = _loginAuthenticationCommand.AuthenticateUser(new LoginCredentials { LoginId = loginModel.LoginId, PasswordHash = LoginCredentials.HashToString(loginModel.Password) }); switch (result.Status) { // Don't stop the user from purchasing if they need to change their password, they can do that next time they log in. case AuthenticationStatus.Authenticated: case AuthenticationStatus.AuthenticatedMustChangePassword: case AuthenticationStatus.AuthenticatedWithOverridePassword: // Log in. _authenticationManager.LogIn(HttpContext, result.User, result.Status); break; default: throw new AuthenticationFailedException(); } // Go to the next page. return(Next()); } catch (UserException ex) { ModelState.AddModelError(ex, new NewOrderErrorHandler()); } // Show the user the errors. var coupon = GetCoupon(Pageflow.CouponId); var order = PrepareOrder(Pageflow.ContactProductId, coupon, Pageflow.UseDiscount, Pageflow.CreditCard); return(AccountView(order, loginModel, null, false)); }
private void SaveHash(string password, IEnumerable <TextBox> textboxes) { _passwordHash = LoginCredentials.HashToString(password); txtHiddenPasswordHash.Value = _passwordHash; // Set the textbox value to a placeholder of the same length, so it looks to the user like // their password is saved, but it's not actually stored in the page for better security. var placeholder = new string(PasswordPlaceholderChar, password.Length); foreach (TextBox textbox in textboxes) { SetPasswordText(textbox, placeholder); } }
public static Custodian CreateTestCustodian(this ICustodianAccountsCommand custodianAccountsCommand, string loginId, string firstName, string lastName, Guid affiliateId) { var custodian = new Custodian { EmailAddress = new EmailAddress { Address = string.Format(EmailAddressFormat, loginId) }, FirstName = firstName, LastName = lastName, }; custodianAccountsCommand.CreateCustodian(custodian, new LoginCredentials { LoginId = loginId, PasswordHash = LoginCredentials.HashToString(DefaultPassword) }, affiliateId); return(custodian); }
public static Administrator CreateTestAdministrator(this IAdministratorAccountsCommand administratorAccountsCommand, string loginId, string firstName, string lastName) { var administrator = new Administrator { EmailAddress = new EmailAddress { Address = string.Format(EmailAddressFormat, loginId) }, FirstName = firstName, LastName = lastName, }; administratorAccountsCommand.CreateAdministrator(administrator, new LoginCredentials { LoginId = loginId, PasswordHash = LoginCredentials.HashToString(DefaultPassword) }); return(administrator); }
private void UpdatePassword(Guid userId, LoginCredentials credentials, string password, bool isGenerated) { // Change the credentials. credentials.PasswordHash = LoginCredentials.HashToString(password); credentials.MustChangePassword = isGenerated; _repository.UpdateCredentials(userId, credentials); // Fire events. var handlers = PasswordReset; if (handlers != null) { handlers(this, new PasswordResetEventArgs(userId, credentials.LoginId, password, isGenerated)); } }
protected override Member CreateMember() { // Crate a member with everything set. var member = new Member { Address = new Address { Location = _locationQuery.ResolveLocation(_locationQuery.GetCountry(Country), Location) }, DateOfBirth = new PartialDate(1970, 1), EmailAddresses = new[] { new EmailAddress { Address = PrimaryEmailAddress }, new EmailAddress { Address = SecondaryEmailAddress } }, EthnicStatus = EthnicStatus.Aboriginal, FirstName = FirstName, Gender = Gender.Male, LastName = LastName, PhoneNumbers = new[] { new PhoneNumber { Number = PrimaryPhoneNumber, Type = PhoneNumberType.Home }, new PhoneNumber { Number = SecondaryPhoneNumber, Type = PhoneNumberType.Work } }, VisibilitySettings = new VisibilitySettings(), IsActivated = true, IsEnabled = true, }; var credentials = new LoginCredentials { LoginId = PrimaryEmailAddress, PasswordHash = LoginCredentials.HashToString(Password) }; _memberAccountsCommand.CreateMember(member, credentials, null); return(member); }
public ActionResult ChangePassword(Guid id, CustodianLoginModel custodianLogin) { var custodian = _custodiansQuery.GetCustodian(id); if (custodian == null) { return(NotFound("custodian", "id", id)); } var credentials = _loginCredentialsQuery.GetCredentials(custodian.Id); if (credentials == null) { return(NotFound("custodian", "id", id)); } try { // Validate. custodianLogin.Validate(); // Update. credentials.PasswordHash = LoginCredentials.HashToString(custodianLogin.Password); _loginCredentialsCommand.UpdateCredentials(custodian.Id, credentials, User.Id().Value); const string message = "The password has been reset."; return(RedirectToRouteWithConfirmation(CustodiansRoutes.Edit, new { id }, message)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } custodianLogin.LoginId = credentials.LoginId; return(View("Edit", new CustodianUserModel { User = _custodiansQuery.GetCustodian(id), UserLogin = custodianLogin, Community = _communitiesQuery.GetCommunity(custodian.AffiliateId.Value), })); }
public ActionResult ChangePassword(Guid id, AdministratorLoginModel administratorLogin) { var administrator = _administratorsQuery.GetAdministrator(id); if (administrator == null) { return(NotFound("administrator", "id", id)); } var credentials = _loginCredentialsQuery.GetCredentials(id); if (credentials == null) { return(NotFound("administrator", "id", id)); } try { // Validate. administratorLogin.Validate(); // Update. credentials.PasswordHash = LoginCredentials.HashToString(administratorLogin.Password); _loginCredentialsCommand.UpdateCredentials(administrator.Id, credentials, User.Id().Value); const string message = "The password has been reset."; return(RedirectToRouteWithConfirmation(AdministratorsRoutes.Edit, new { id }, message)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } administratorLogin.LoginId = credentials.LoginId; return(View("Edit", new UserModel <Administrator, AdministratorLoginModel> { User = _administratorsQuery.GetAdministrator(id), UserLogin = administratorLogin, })); }
public void TestCreateUser() { // Create a member account. const string userId = "*****@*****.**"; _memberAccountsCommand.CreateTestMember(userId, false); // Authenticate the user, who is deactivated when first created. var credentials = new LoginCredentials { LoginId = userId, PasswordHash = LoginCredentials.HashToString("password") }; Assert.AreEqual(AuthenticationStatus.Deactivated, _loginAuthenticationCommand.AuthenticateUser(credentials).Status); var profile = _membersQuery.GetMember(userId); Assert.IsNotNull(profile); }
private void CreateAdministrator(CreateAdministratorModel model) { var administrator = new Administrator { EmailAddress = new EmailAddress { Address = model.EmailAddress, IsVerified = true }, FirstName = model.FirstName, LastName = model.LastName, }; var credentials = new LoginCredentials { LoginId = model.LoginId, PasswordHash = LoginCredentials.HashToString(model.Password), }; // Create the account. _administratorAccountsCommand.CreateAdministrator(administrator, credentials); }
void ICookieManager.CreatePersistantUserCookie(HttpContextBase context, UserType userType, LoginCredentials credentials, AuthenticationStatus status) { const int hoursInWeek = 24 * 7; // Set the user cookie. var domain = GetDomain(context.Request.Url.Host); context.Response.Cookies.SetCookie(UserCookieName, credentials.LoginId, domain, new TimeSpan(hoursInWeek, 0, 0)); // Set the password cookie. var persistPassword = !(status == AuthenticationStatus.AuthenticatedWithOverridePassword || userType == UserType.Administrator); if (!persistPassword) { ExpireCookie(context, domain, PasswordCookieName); if (domain != null) { ExpireCookie(context, null, PasswordCookieName); } } else if (credentials.Password.Length < 6 || credentials.Password.Substring(0, 5) != "sha1|") { // Compute the SHA1 sum of the hashed password, prefixed by a random salt and the expiry. var salt = ToBytes(Random.Next()); var utf8PasswordHash = Encoding.UTF8.GetBytes(LoginCredentials.HashToString(credentials.Password)); var expiry = DateTime.Now.ToUniversalTime().AddDays(7); var binaryExpiry = ToBytes(expiry.ToBinary()); var sha1 = SHA1.Create(); sha1.TransformBlock(salt, 0, salt.Length, salt, 0); sha1.TransformBlock(utf8PasswordHash, 0, utf8PasswordHash.Length, utf8PasswordHash, 0); sha1.TransformFinalBlock(binaryExpiry, 0, binaryExpiry.Length); context.Response.Cookies.SetCookie(PasswordCookieName, string.Format("sha1|{0}|{1:x}|{2}", Convert.ToBase64String(salt), expiry.ToBinary(), Convert.ToBase64String(sha1.Hash)), domain, expiry); } }
private void CreateEmployer(IOrganisation organisation, CreateEmployerModel model) { var employer = new Employer { Organisation = organisation, SubRole = model.SubRole, EmailAddress = new EmailAddress { Address = model.EmailAddress, IsVerified = true }, FirstName = model.FirstName, LastName = model.LastName, JobTitle = model.JobTitle, PhoneNumber = _phoneNumbersQuery.GetPhoneNumber(model.PhoneNumber, ActivityContext.Location.Country), }; if (model.IndustryId != null) { employer.Industries = new List <Industry> { _industriesQuery.GetIndustry(model.IndustryId.Value) } } ; // Create the account, where the password must be changed at next login. var credentials = new LoginCredentials { LoginId = model.LoginId, Password = model.Password, PasswordHash = LoginCredentials.HashToString(model.Password), MustChangePassword = true, }; _employerAccountsCommand.CreateEmployer(employer, credentials); var members = _accountReportsQuery.GetUsers(UserType.Member, DateTime.Now); _emailsCommand.TrySend(new NewEmployerWelcomeEmail(employer, model.LoginId, model.Password, members)); }
private void CreateCustodian(Community community, CreateCustodianModel model) { // For now use the old way of doing things. var custodian = new Custodian { EmailAddress = new EmailAddress { Address = model.EmailAddress }, FirstName = model.FirstName, LastName = model.LastName, }; var credentials = new LoginCredentials { LoginId = model.LoginId, PasswordHash = LoginCredentials.HashToString(model.Password), }; // Create the account. _custodianAccountsCommand.CreateCustodian(custodian, credentials, community.Id); }
private static Member CreateTestMember(this IMemberAccountsCommand memberAccountsCommand, bool createKnownInvalidMember, string emailAddress, string password, string firstName, string lastName, bool activated, Guid?affiliateId, DateTime?createTime, LocationReference location) { var member = new Member { EmailAddresses = new List <EmailAddress> { new EmailAddress { Address = emailAddress, IsVerified = true } }, IsActivated = activated, IsEnabled = true, PhoneNumbers = new List <PhoneNumber> { new PhoneNumber { Number = DefaultPhoneNumber, Type = PhoneNumberType.Mobile } }, FirstName = firstName, LastName = lastName, Gender = DefaultGender, DateOfBirth = DefaultDateOfBirth, }; if (createTime.HasValue) { member.CreatedTime = createTime.Value; } var credentials = new LoginCredentials { LoginId = emailAddress, PasswordHash = LoginCredentials.HashToString(password) }; // Deny public access to real name, because existing tests rely on this. Might need to change this later. member.VisibilitySettings = new VisibilitySettings(); member.VisibilitySettings.Personal.PublicVisibility &= ~PersonalVisibility.Name; if (location == null) { member.Address = new Address { Location = new LocationReference() }; LocationQuery.ResolvePostalSuburb(member.Address.Location, DefaultCountry, DefaultLocation); } else { member.Address = new Address { Location = location }; } if (createKnownInvalidMember) { CreateInvalidMember(member, credentials, affiliateId); } else { memberAccountsCommand.CreateMember(member, credentials, affiliateId); } return(member); }
private static void CreateTestEmployer(this IEmployerAccountsCommand employersCommand, Employer employer, string loginId) { employersCommand.CreateEmployer(employer, new LoginCredentials { LoginId = loginId, PasswordHash = LoginCredentials.HashToString(DefaultPassword) }); }
private AuthenticationResult AuthenticateUser(IRegisteredUser user, LoginCredentials storedCredentials, LoginCredentials credentials) { const string method = "AuthenticateUser"; // If the password hash has already been determined then use that. string passwordHash; if (!string.IsNullOrEmpty(credentials.PasswordHash)) { passwordHash = credentials.PasswordHash; } else { // Hash the password and check. if (credentials.Password.Length >= 5 && credentials.Password.Substring(0, 5) == "sha1|") { return(Sha1PasswordMatches(storedCredentials, credentials.Password) ? CreateResult(user, GetAuthenticationStatus(user, storedCredentials)) : CreateFailedResult(user)); } passwordHash = LoginCredentials.HashToString(credentials.Password); } var result = AuthenticateUser(user, storedCredentials, passwordHash); if (result.Status != AuthenticationStatus.Failed) { return(result); } // A better fix for 4246: if the original password doesn't work try trimming spaces from the end. if (!string.IsNullOrEmpty(credentials.Password)) { var trimmed = credentials.Password.TrimEnd(' '); if (trimmed != credentials.Password) { result = AuthenticateUser(user, storedCredentials, LoginCredentials.HashToString(trimmed)); if (result.Status != AuthenticationStatus.Failed) { return(result); } } } // Check to see whether the use of the override password is enabled. if (!_overridePasswordEnabled) { EventSource.Raise(Event.Trace, method, string.Format("Login failed for user {0} ({1}) (override password disabled).", storedCredentials.LoginId, user.Id)); return(result); } // Check against the override password. if (_overridePasswordHash != passwordHash) { EventSource.Raise(Event.Trace, method, string.Format("Login failed for user {0} ({1}).", storedCredentials.LoginId, user.Id)); return(result); } // An override login does not check the user flags. EventSource.Raise(Event.Trace, method, string.Format("User {0} ({1}) has logged in using override password!", storedCredentials.LoginId, user.Id)); return(new AuthenticationResult { Status = AuthenticationStatus.AuthenticatedWithOverridePassword, User = user }); }
public void TestHash() { Assert.IsTrue("password" != LoginCredentials.HashToString("password")); Assert.AreEqual(LoginCredentials.HashToString("password"), LoginCredentials.HashToString("password")); Assert.AreEqual("DMF1ucDxtqgxw5niaXcmYQ==", LoginCredentials.HashToString("a")); }
AuthenticationResult IAccountsManager.TryAutoLogIn(HttpContextBase context) { var credentials = _cookieManager.ParsePersistantUserCookie(context); if (string.IsNullOrEmpty(credentials.LoginId) || string.IsNullOrEmpty(credentials.Password)) { return new AuthenticationResult { Status = AuthenticationStatus.Failed } } ; // Authenticate. var result = _loginAuthenticationCommand.AuthenticateUser(new LoginCredentials { LoginId = credentials.LoginId, Password = credentials.Password }); switch (result.Status) { case AuthenticationStatus.Authenticated: // Automatically log in. result.Status = AuthenticationStatus.AuthenticatedAutomatically; _authenticationManager.LogIn(context, result.User, result.Status); break; default: // If it didn't work then ensure the cookies are removed. _cookieManager.DeletePersistantUserCookie(context); break; } return(result); } AuthenticationResult IAccountsManager.LogIn(HttpContextBase context, Login login) { // Process the post to check validations etc. login.Prepare(); login.Validate(); // Authenticate. var result = _loginAuthenticationCommand.AuthenticateUser(new LoginCredentials { LoginId = login.LoginId, PasswordHash = LoginCredentials.HashToString(login.Password) }); switch (result.Status) { case AuthenticationStatus.Authenticated: case AuthenticationStatus.AuthenticatedMustChangePassword: case AuthenticationStatus.AuthenticatedWithOverridePassword: case AuthenticationStatus.Deactivated: // Log in. _authenticationManager.LogIn(context, result.User, result.Status); // Remember me. if (login.RememberMe) { _cookieManager.CreatePersistantUserCookie(context, result.User.UserType, new LoginCredentials { LoginId = login.LoginId, Password = login.Password }, result.Status); } else { _cookieManager.DeletePersistantUserCookie(context); } // Vertical. SetVertical(result.User); break; } // Also log them in as a dev if they used the override password. if (result.Status == AuthenticationStatus.AuthenticatedWithOverridePassword) { _devAuthenticationManager.LogIn(context); } return(result); } void IAccountsManager.LogOut(HttpContextBase context) { // Maintain the vertical. Vertical vertical = null; var verticalId = ActivityContext.Current.Vertical.Id; if (verticalId != null) { vertical = _verticalsQuery.GetVertical(verticalId.Value); } // Clean out remember me and any external authentication cookie. _cookieManager.DeletePersistantUserCookie(context); _cookieManager.DeleteExternalCookie(context, vertical == null ? null : vertical.ExternalCookieDomain); // Log out. _authenticationManager.LogOut(context); // Clean up the session but don't abandon it. context.Session.Clear(); // Reset the vertical. if (vertical != null) { ActivityContext.Current.Set(vertical); } } Member IAccountsManager.Join(HttpContextBase context, MemberAccount account, AccountLoginCredentials accountCredentials, bool requiresActivation) { account.Prepare(); account.Validate(); accountCredentials.Prepare(); accountCredentials.Validate(); // Check for an existing login. if (_loginCredentialsQuery.DoCredentialsExist(new LoginCredentials { LoginId = accountCredentials.LoginId })) { throw new DuplicateUserException(); } // Create the member. var member = CreateMember(account, requiresActivation); var credentials = new LoginCredentials { LoginId = accountCredentials.LoginId, PasswordHash = LoginCredentials.HashToString(accountCredentials.Password), }; _memberAccountsCommand.CreateMember(member, credentials, GetMemberAffiliateId()); // Log the user in. _authenticationManager.LogIn(context, member, AuthenticationStatus.Authenticated); // Initialise. _referralsManager.CreateReferral(context.Request, member.Id); InitialiseMemberProfile(member.Id); return(member); } Employer IAccountsManager.Join(HttpContextBase context, EmployerAccount account, AccountLoginCredentials accountCredentials) { accountCredentials.Prepare(); accountCredentials.Validate(); // Check for an existing login. if (_loginCredentialsQuery.DoCredentialsExist(new LoginCredentials { LoginId = accountCredentials.LoginId })) { throw new DuplicateUserException(); } return(Join( context, account, e => _employerAccountsCommand.CreateEmployer(e, new LoginCredentials { LoginId = accountCredentials.LoginId, PasswordHash = LoginCredentials.HashToString(accountCredentials.Password) }))); } Employer IAccountsManager.Join(HttpContextBase context, EmployerAccount account, LinkedInProfile profile) { return(Join( context, account, e => _employerAccountsCommand.CreateEmployer(e, profile))); }
public ActionResult Account(Guid jobAdId, JobAdFeaturePack?featurePack, Login loginModel, [Bind(Include = "RememberMe")] CheckBoxValue rememberMe) { try { // Get the job ad. var anonymousUser = CurrentAnonymousUser; var jobAd = GetJobAd(anonymousUser.Id, jobAdId); if (jobAd == null) { return(NotFound("job ad", "id", jobAdId)); } // Process the post to check validations etc. loginModel.RememberMe = rememberMe != null && rememberMe.IsChecked; loginModel.Prepare(); loginModel.Validate(); // Authenticate. var result = _loginAuthenticationCommand.AuthenticateUser(new LoginCredentials { LoginId = loginModel.LoginId, PasswordHash = LoginCredentials.HashToString(loginModel.Password) }); switch (result.Status) { // Don't stop the user from purchasing if they need to change their password, they can do that next time they log in. case AuthenticationStatus.Authenticated: case AuthenticationStatus.AuthenticatedMustChangePassword: case AuthenticationStatus.AuthenticatedWithOverridePassword: // Log in. _authenticationManager.LogIn(HttpContext, result.User, result.Status); break; default: throw new AuthenticationFailedException(); } // Now that the user has logged in, transfer the job ad and publish it. var employer = (IEmployer)result.User; _employerJobAdsCommand.TransferJobAd(employer, jobAd); return(CheckPublish(employer, jobAd, featurePack)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } // Show the user the errors. return(View(new AccountModel { Login = loginModel, Join = new EmployerJoin(), AcceptTerms = false, Industries = _industriesQuery.GetIndustries() })); }