Exemple #1
0
        private void CreateAuthenticationCookie(HttpContextBase context, IRegisteredUser user, bool needsReset, DateTime issueDate, DateTime expiration)
        {
            var domain = GetDomain(context.Request.Url.Host);

            var ticket = new FormsAuthenticationTicket(
                1,
                user.Id.ToString("n"),
                issueDate,
                expiration,
                false,
                CreateAuthenticationUserData(user, needsReset),
                FormsAuthentication.FormsCookiePath);

            // Create the cookie.

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
            {
                HttpOnly = true,
                Secure   = false,
                Path     = FormsAuthentication.FormsCookiePath,
                Domain   = domain,
            };

            // Expire any existing cookies before adding the new one.

            if (domain != null)
            {
                ExpireCookie(context, null, FormsAuthentication.FormsCookieName);
            }
            context.Response.Cookies.Add(cookie);
        }
        private string GetContent(TemplateEmail templateEmail, IRegisteredUser member, JobAdEntry jobAd, string coverLetter)
        {
            var sb = new StringBuilder();

            sb.AppendLine("<p>");
            sb.AppendLine();
            sb.AppendLine("  Hi,");
            sb.AppendLine();
            sb.AppendLine("</p>");
            sb.AppendLine("<p>");
            sb.AppendLine("  We wanted to let you know that " + member.FullName + " has applied for the");
            sb.AppendLine("  " + jobAd.Title + " job " + (jobAd.Integration.ExternalReferenceId == null ? "" : " (ref# " + jobAd.Integration.ExternalReferenceId + ")"));
            sb.AppendLine("  on <a href=\"" + GetTinyUrl(templateEmail, false, "~/employers") + "\">LinkMe.com.au</a>.");
            sb.AppendLine("  You can also see their online resume");
            sb.AppendLine("  <a href=\"" + GetTinyUrl(templateEmail, true, "~/employers/candidates", "candidateId", member.Id.ToString()) + "\">here</a>.");
            sb.AppendLine("</p>");
            sb.AppendLine();
            sb.AppendLine("<p>");
            sb.AppendLine("  " + member.FirstName + " attached a cover letter:");
            sb.AppendLine("</p>");
            sb.AppendLine("<p style=\"padding-left:40px\">");
            sb.AppendLine(HtmlUtil.LineBreaksToHtml(HttpUtility.HtmlEncode(coverLetter)));
            sb.AppendLine("</p>");
            sb.AppendLine();
            sb.AppendLine("<br />");
            return(sb.ToString());
        }
Exemple #3
0
        private IRegisteredUser UpdateMember(IRegisteredUser user, Guid verticalId, ExternalUserData userData)
        {
            if (user is Member)
            {
                // User exists, but their details may have changed.

                var member = (Member)user;
                if (member.FirstName != userData.FirstName || member.LastName != userData.LastName || member.GetBestEmailAddress().Address != userData.EmailAddress)
                {
                    member.FirstName      = userData.FirstName;
                    member.LastName       = userData.LastName;
                    member.EmailAddresses = new List <EmailAddress> {
                        new EmailAddress {
                            Address = userData.EmailAddress, IsVerified = true
                        }
                    };
                    _memberAccountsCommand.UpdateMember(member);
                }

                // Associate them with the vertical if needed.

                if (verticalId != user.AffiliateId)
                {
                    _memberAffiliationsCommand.SetAffiliation(user.Id, verticalId);
                }
            }

            return(user);
        }
Exemple #4
0
        private void SetUserVertical(IRegisteredUser user)
        {
            // Only try to set the current vertical if it hasn't already been set.
            // This ensures that if a user comes in through a vertical channel then
            // the web site remains within that vertical channel, even if the user
            // is associated with a different vertical.

            var communityContext = ActivityContext.Current.Community;

            if (communityContext.IsSet)
            {
                return;
            }

            // Check whether the member has an affiliate.
            // If so, then set the request context to it.

            var affiliateId = user.AffiliateId;

            if (affiliateId == null)
            {
                return;
            }

            var vertical = _verticalsQuery.GetVertical(affiliateId.Value);

            if (vertical != null)
            {
                ActivityContext.Current.Set(vertical);
            }
        }
        private string GetContent(TemplateEmail templateEmail, IRegisteredUser employer, int quantity)
        {
            var sb = new StringBuilder();

            sb.AppendLine("<p>Hi " + employer.FirstName + "</p>");
            sb.AppendLine("<p>");
            sb.AppendLine("  Thank you for using LinkMe for your candidate sourcing");
            sb.AppendLine("  - our records show that you have " + quantity + " contact credits");
            sb.AppendLine("  left in your account that are due to expire in one month.");
            sb.AppendLine("</p>");
            sb.AppendLine("<p>");
            sb.AppendLine("  To use the remaining contact credits,");
            sb.AppendLine("  or to purchase further credits, please");
            sb.AppendLine("  <a href=\"" + GetTinyUrl(templateEmail, true, "~/employers/login") + "\">log in</a>");
            sb.AppendLine("  to LinkMe to search for and");
            sb.AppendLine("  contact candidates that are available for your current opportunities.");
            sb.AppendLine("</p>");
            sb.AppendLine("<p>");
            sb.AppendLine("  To discuss further purchase options,");
            sb.AppendLine("  please contact me on 1800 LINK ME at your earliest convenience.");
            sb.AppendLine("</p>");
            sb.AppendLine("<p>");
            sb.AppendLine("  We look forward to seeing you on our site again soon.");
            sb.AppendLine("</p>");
            return(sb.ToString());
        }
Exemple #6
0
        private static string GetInvitationAcceptedHtml(this Invitation invitation, IRegisteredUser inviter, string format)
        {
            var profileUrl      = NavigationManager.GetUrlForPage <ViewFriend>(ViewFriend.FriendIdParameter, invitation.InviterId.ToString()).ToString();
            var inviterNameHtml = HttpUtility.HtmlEncode(inviter.FullName);

            return(string.Format(format, profileUrl, inviterNameHtml, inviterNameHtml.GetNamePossessiveSuffix()));
        }
        void IAccountVerificationsCommand.StopActivationWorkflow(IRegisteredUser user)
        {
            // Only supported for members at the moment.

            var member = user as IMember;

            if (member == null)
            {
                return;
            }

            var service = _activationEmailManager.Create();

            try
            {
                service.StopSending(member.Id);
            }
            catch (Exception)
            {
                _activationEmailManager.Abort(service);
                throw;
            }

            _activationEmailManager.Close(service);
        }
Exemple #8
0
 private static string CreateAuthenticationUserData(IRegisteredUser user, bool needsReset)
 {
     return(((int)user.UserType).ToString()
            + UserDataSeparator + user.FullName
            + UserDataSeparator + needsReset
            + UserDataSeparator + user.IsActivated);
 }
        public static void MockContext(this ViewController controller, IRegisteredUser user)
        {
            var identity = new RegisteredUserIdentity(user.Id, user.UserType, user.IsActivated)
            {
                FullName = user.FullName, NeedsReset = false, User = user
            };
            var principal = new RegisteredUserPrincipal(identity);

            var mockContext = new Mock <HttpContextBase>();

            mockContext.SetupGet(c => c.User).Returns(principal);

            var mockRequest = new Mock <HttpRequestBase>();

            mockRequest.SetupGet(r => r.Headers).Returns(new NameValueCollection {
                { "X-Rewrite-URL", "/" }
            });
            mockContext.SetupGet(c => c.Request).Returns(mockRequest.Object);

            var mockResponse = new HttpResponseWrapper(new HttpResponse(new StringWriter()));

            mockContext.SetupGet(c => c.Response).Returns(mockResponse);

            var mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext.SetupGet(c => c.HttpContext).Returns(mockContext.Object);

            controller.ControllerContext = mockControllerContext.Object;
        }
Exemple #10
0
        void IAuthenticationManager.UpdateUser(HttpContextBase context, IRegisteredUser user, bool needsReset)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            // Update the ASP.NET stuff.

            var identity = (RegisteredUserIdentity)context.User.Identity;

            if (identity.Id != user.Id)
            {
                throw new ArgumentException("The user is not the same as the currently authenticated user.");
            }
            identity.FullName   = user.FullName;
            identity.NeedsReset = needsReset;
            identity.User       = user;

            // Update the cookies.

            try
            {
                _cookieManager.UpdateAuthenticationCookie(context, user, identity.NeedsReset);
            }
            catch (Exception)
            {
                NavigationManager.Redirect(NavigationManager.GetLogOutUrl());
            }
        }
Exemple #11
0
        void IAuthenticationManager.LogIn(HttpContextBase context, IRegisteredUser user, AuthenticationStatus status)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            // Do the HTTP stuff.

            _cookieManager.CreateAuthenticationCookie(context, user);

            // Do the ASP.NET stuff.

            var identity = new RegisteredUserIdentity(user.Id, user.UserType, user.IsActivated)
            {
                FullName   = user.FullName,
                NeedsReset = false,
                User       = user
            };

            // Record it.

            _userSessionsCommand.CreateUserLogin(new UserLogin
            {
                UserId               = user.Id,
                SessionId            = GetSessionId(user.Id, context.Request.UserHostAddress, context.Session),
                IpAddress            = context.Request.UserHostAddress,
                AuthenticationStatus = status
            });
            context.User = new RegisteredUserPrincipal(identity);
        }
        protected void AssertOrganisationCreditUsage <T>(Organisation organisation, IRegisteredUser employer, bool hasExercisedCredit, params UsedOn[] usedOns)
            where T : Credit
        {
            Get(GetCreditsUsageUrl(organisation));

            var nodes = Browser.CurrentHtml.DocumentNode.SelectNodes("//table[@class='list']/tbody/tr");

            if (hasExercisedCredit)
            {
                Assert.IsTrue(nodes != null && nodes.Count == usedOns.Length);

                foreach (var node in nodes)
                {
                    Assert.AreEqual(_creditsQuery.GetCredit <T>().ShortDescription, node.SelectSingleNode("td[position()=2]").InnerText);
                    Assert.AreEqual(employer.FullName, node.SelectSingleNode("td[position()=3]/a").InnerText);
                    Assert.IsTrue((from u in usedOns where u.Name == node.SelectSingleNode("td[position()=4]/a").InnerText select u).Any());
                }

                AssertPageDoesNotContain("This organisation has not had any credits used.");
            }
            else
            {
                Assert.IsTrue(nodes == null || nodes.Count == 0);
                AssertPageContains("This organisation has not had any credits used.");
            }
        }
Exemple #13
0
        private void TestCannotAccess(string path, IRegisteredUser user)
        {
            LogIn(user);
            var url = new ReadOnlyApplicationUrl(path);

            Get(url);

            switch (user.UserType)
            {
            case UserType.Member:
                AssertUrl(LoggedInMemberHomeUrl);
                break;

            case UserType.Employer:
                AssertUrl(LoggedInEmployerHomeUrl);
                break;

            case UserType.Administrator:
                AssertUrl(LoggedInAdministratorHomeUrl);
                break;

            default:
                AssertUrl(LoggedInCustodianHomeUrl);
                break;
            }
        }
Exemple #14
0
        private bool MatchAccount(IRegisteredUser member, Community community, ConvertModel convertModel)
        {
            // Must be an exact match.

            if (member.AffiliateId != community.Id ||
                member.FirstName != convertModel.FirstName ||
                member.LastName != convertModel.LastName)
            {
                return(false);
            }

            // Job title and company must be part of the resume titles and companies.

            var candidate = _candidatesQuery.GetCandidate(member.Id);

            if (candidate == null || candidate.ResumeId == null)
            {
                return(false);
            }

            var resume = _resumesQuery.GetResume(candidate.ResumeId.Value);

            if (resume == null || resume.Jobs == null || resume.Jobs.Count == 0)
            {
                return(false);
            }

            return(resume.Jobs.Any(j => !string.IsNullOrEmpty(j.Title) && j.Title.Contains(convertModel.JobTitle)) &&
                   resume.Jobs.Any(j => !string.IsNullOrEmpty(j.Company) && j.Company.Contains(convertModel.JobCompany)));
        }
Exemple #15
0
        private void AssertCanSetBrand(IRegisteredUser member, VerticalTestData data)
        {
            // Login and go to the visibility page.

            LogIn(member);
            GetPage <VisibilitySettingsBasic>();

            // The style atribute is set on the containing div so the control will always be "visible", ie contained within the page.

            Assert.AreEqual(_communityCheckBox.IsVisible, member.AffiliateId != null);

            if (member.AffiliateId != null)
            {
                // Should be able to see the community controls.

                AssertPageContains("You joined through " + data.Name);
                AssertPageContains(new ApplicationUrl(data.CandidateImageUrl).PathAndQuery);
            }
            else
            {
                AssertPageDoesNotContain(data.Name);
                AssertPageDoesNotContain(new ApplicationUrl(data.CandidateImageUrl).PathAndQuery);
            }

            // Log out.

            LogOut();
        }
Exemple #16
0
 private static AuthenticationResult CreateFailedResult(IRegisteredUser user)
 {
     return(new AuthenticationResult
     {
         User = user,
         Status = AuthenticationStatus.Failed,
     });
 }
Exemple #17
0
 private static AuthenticationResult CreateResult(IRegisteredUser user, AuthenticationStatus status)
 {
     return(new AuthenticationResult
     {
         User = user,
         Status = status,
     });
 }
Exemple #18
0
        void ICookieManager.UpdateAuthenticationCookie(HttpContextBase context, IRegisteredUser user, bool needsReset)
        {
            // Update the authentication ticket without extending its expiration time.

            var ticket = GetAuthenticationTicket(context);

            CreateAuthenticationCookie(context, user, needsReset, ticket.IssueDate, ticket.Expiration);
        }
Exemple #19
0
        private static ReadOnlyUrl AssertResume(XmlNode xmlResume, IRegisteredUser member)
        {
            var url = new ReadOnlyApplicationUrl(true, "~/resume/" + member.Id.ToString("n") + "/file/rtf");

            Assert.AreEqual(url.AbsoluteUri.ToLower(), xmlResume.Attributes["uri"].Value.ToLower());
            Assert.AreEqual(member.LastName + "_" + member.FirstName + "_LinkMeCV.doc", xmlResume.Attributes["name"].Value);
            return(url);
        }
        private void AssertVerifiedDetails(Organisation organisation, IRegisteredUser accountManager, ICommunicationRecipient verifiedBy)
        {
            Assert.AreEqual(organisation.ParentFullName ?? "", _parentFullNameTextBox.Text);
            Assert.AreEqual(organisation.Name, _nameTextBox.Text);
            Assert.AreEqual(organisation.Address == null || organisation.Address.Location == null ? string.Empty : organisation.Address.Location.ToString(), _locationTextBox.Text);

            Assert.AreEqual(accountManager.FullName + (accountManager.IsEnabled ? "" : " (disabled)"), _accountManagerIdDropDownList.SelectedItem.Text);
            AssertPageContains("Verified by " + verifiedBy.FullName);
        }
Exemple #21
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var status = AuthenticationStatus.Failed;

            if (!String.IsNullOrEmpty(Username) && !String.IsNullOrEmpty(Password))
            {
                var result = _loginAuthenticationCommand.AuthenticateUser(new LoginCredentials {
                    LoginId = Username, Password = Password
                });
                _currentUser = result.User;
                status       = result.Status;

                if (result.User != null)
                {
                    switch (result.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                    case AuthenticationStatus.AuthenticatedMustChangePassword:
                    case AuthenticationStatus.AuthenticatedWithOverridePassword:
                    case AuthenticationStatus.Deactivated:
                        _authenticationManager.LogIn(new HttpContextWrapper(HttpContext.Current), _currentUser, AuthenticationStatus.Authenticated);
                        break;

                    default:
                        _currentUser = null;
                        break;
                    }
                }
            }

            if (_currentUser != null)
            {
                _userSessionsCommand.CreateUserLogin(new UserLogin {
                    UserId = _currentUser.Id, IpAddress = Request.UserHostAddress, AuthenticationStatus = status
                });

                // This specific page is like a vertical landing page, so set the context.

                var vertical = _verticalsQuery.GetVertical(VerticalName);
                if (vertical != null)
                {
                    ActivityContext.Current.Set(vertical);
                }

                // Redirect to the appropriate page.

                ReadOnlyUrl referrer     = null;
                var         refParameter = Request.QueryString["ref"];
                if (refParameter != null)
                {
                    referrer = new ReadOnlyApplicationUrl(refParameter);
                }
                NavigationManager.Redirect(referrer ?? SearchRoutes.Search.GenerateUrl());
            }
        }
Exemple #22
0
        /// <summary>
        /// try to find and check registered user
        /// </summary>
        public IRegisteredUser SignInUser(RegisterUserViewModel user)
        {
            IRegisteredUser user2 = userRepository.FindItemByKey(user.Email);

            if (user2 != null && user2.Email == user.Email && user.Password == user2.Password)
            {
                return(user2);
            }
            return(null);
        }
Exemple #23
0
        public ActionResult NewPassword(NewPasswordModel newPassword)
        {
            try
            {
                // Make sure everything is in order.

                newPassword.Validate();

                // First look for the login id.

                IRegisteredUser user   = null;
                var             userId = _loginCredentialsQuery.GetUserId(newPassword.LoginId);
                if (userId != null)
                {
                    user = _usersQuery.GetUser(userId.Value);
                }
                else
                {
                    // Look for an employer treating it as an email address.

                    var employers = _employersQuery.GetEmployers(newPassword.LoginId);
                    if (employers.Count > 1)
                    {
                        ModelState.AddModelError(string.Format("There is more than one user with the specified email address. Please enter one of the usernames or <a href=\"{0}\">contact us</a> for assistance.", SupportRoutes.ContactUs.GenerateUrl()));
                        return(View("NewPasswordSent", newPassword));
                    }

                    if (employers.Count == 1)
                    {
                        user = employers[0];
                    }
                }

                if (user == null || user.UserType == UserType.Administrator)
                {
                    ModelState.AddModelError("The user cannot be found. Please try again.");
                }
                else
                {
                    // Now reset the password.

                    var credentials = _loginCredentialsQuery.GetCredentials(user.Id);
                    _loginCredentialsCommand.ResetPassword(user.Id, credentials);

                    return(View("NewPasswordSent", newPassword));
                }
            }
            catch (UserException ex)
            {
                ModelState.AddModelError(ex, new StandardErrorHandler());
            }

            return(View(newPassword));
        }
 private void _view_Loading(object sender, EventArgs e)
 {
     if (!String.IsNullOrEmpty(_view.UserKey))
     {
         IRegisteredUser user = bl.GetUser(_view.UserKey);
         if (user != null)
         {
             _view.UserEmail = user.Email;
         }
     }
 }
        private static AuthenticationResult AuthenticateUser(IRegisteredUser user, ExternalCredentials storedCredentials, ExternalCredentials credentials)
        {
            const string method = "AuthenticateUser";

            // If the password hash has already been determined then use that.

            if (storedCredentials.ProviderId == credentials.ProviderId && storedCredentials.ExternalId == credentials.ExternalId)
            {
                return(CreateResult(user, GetAuthenticationStatus(user, storedCredentials)));
            }

            EventSource.Raise(Event.Trace, method, string.Format("External authentication failed for user {0} ({1}).", storedCredentials.ExternalId, user.Id));
            return(CreateFailedResult(user));
        }
Exemple #26
0
 private void AssertActivationLink(IRegisteredUser user, bool expectLogin, string definition, ReadOnlyUrl expectedUrl, ReadOnlyUrl link)
 {
     _userAccountsCommand.DeactivateUserAccount(user, Guid.NewGuid());
     Assert.IsFalse(_membersQuery.GetMember(user.Id).IsActivated);
     if (expectLogin)
     {
         AssertLink(definition, user, expectedUrl, link);
     }
     else
     {
         AssertLink(definition, expectedUrl, link);
     }
     Assert.IsTrue(_membersQuery.GetMember(user.Id).IsActivated);
 }
Exemple #27
0
        private void SetVertical(IRegisteredUser user)
        {
            switch (user.UserType)
            {
            case UserType.Member:
            case UserType.Custodian:
                SetUserVertical(user);
                break;

            case UserType.Employer:
                SetEmployerVertical(user);
                break;
            }
        }
        private void TestInvite(IRegisteredUser inviter, IMember invitee)
        {
            Assert.IsNull(_memberContactsQuery.GetRepresentativeContact(inviter.Id));
            Assert.AreEqual(0, _memberContactsQuery.GetRepresenteeContacts(invitee.Id).Count);

            LogIn(inviter);

            // Invite.

            GetPage <RepresentativePopupContents>(
                RepresentativePopupContents.InviteeIdParameter, invitee.Id.ToString(),
                RepresentativePopupContents.SendInvitationParameter, "true",
                RepresentativePopupContents.MessageParameter, Message);

            GetPage <ViewRepresentative>();
            AssertNoRepresentative();

            GetPage <Invitations>();
            AssertPageContains(invitee.FullName);

            AssertInvitation(inviter.Id, invitee.Id, Message);

            // Accept.

            LogOut();
            LogIn(invitee);

            GetPage <Invitations>();
            AssertPageContains(inviter.FullName);
            AssertPageContains("has asked you to be their representative");

            _btnAccept.Click();
            AssertPage <Invitations>();
            var url = NavigationManager.GetUrlForPage <ViewFriend>(ViewFriend.FriendIdParameter, inviter.Id.ToString());

            AssertPageContains(string.Format("You are now <a href=\"{0}\">{1}</a>{2} representative.", url.PathAndQuery, inviter.FullName, inviter.FullName.GetNamePossessiveSuffix()), true);

            Assert.IsNull(_memberFriendsQuery.GetRepresentativeInvitation(inviter.Id, invitee.Id));
            Assert.IsNull(_memberFriendsQuery.GetRepresentativeInvitationByInviter(inviter.Id));
            Assert.AreEqual(0, _memberFriendsQuery.GetRepresentativeInvitations(invitee.Id, invitee.GetBestEmailAddress().Address).Count);

            Assert.AreEqual(invitee.Id, _memberContactsQuery.GetRepresentativeContact(inviter.Id));
            Assert.AreEqual(1, _memberContactsQuery.GetRepresenteeContacts(invitee.Id).Count);
            Assert.AreEqual(inviter.Id, _memberContactsQuery.GetRepresenteeContacts(invitee.Id)[0]);

            // Should also be friends.

            Assert.AreEqual(true, _memberContactsQuery.AreFirstDegreeContacts(inviter.Id, invitee.Id));
        }
Exemple #29
0
        private void AssertBrand(IRegisteredUser member, VerticalTestData memberCommunityTestData, VerticalTestData communityData, bool showCommunity)
        {
            // Look for the brand if appropriate.

            if (member.AffiliateId != null && showCommunity)
            {
                var imageUrl = new ReadOnlyApplicationUrl(memberCommunityTestData.CandidateImageUrl);
                AssertPageContains(imageUrl.FileName);
            }
            else
            {
                var imageUrl = new ReadOnlyApplicationUrl(communityData.CandidateImageUrl);
                AssertPageDoesNotContain(imageUrl.FileName);
            }
        }
        private static string CreateExpiredCookieValue(IRegisteredUser member)
        {
            var issueDate      = DateTime.Now.AddYears(-2);
            var expirationDate = DateTime.Now.AddYears(-1);

            var ticket = new FormsAuthenticationTicket(
                1,
                member.Id.ToString("n"),
                issueDate,
                expirationDate,
                false,
                CreateAuthenticationUserData(member, false),
                FormsAuthentication.FormsCookiePath);

            return(FormsAuthentication.Encrypt(ticket));
        }