/// <summary>
        /// Authenticate a user by email address.
        /// </summary>
        /// <param name="emailAddress"></param>
        /// <returns></returns>
        private bool AuthenticateUser(string emailAddress)
        {
            // check user exist in the JXT Next database
            Telerik.Sitefinity.Security.Model.User existingUser = SitefinityHelper.GetUserByEmail(emailAddress);
            var memberResponse = _blConnector.GetMemberByEmail(emailAddress);

            if (memberResponse.Member == null)
            {
                UserProfileManager userProfileManager = UserProfileManager.GetManager();
                UserProfile        profile            = userProfileManager.GetUserProfile(existingUser.Id, typeof(SitefinityProfile).FullName);
                var fName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "FirstName");
                var lName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "LastName");
                JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
                {
                    Email     = emailAddress,
                    FirstName = fName.ToString(),
                    LastName  = lName.ToString(),
                    Password  = existingUser.Password
                };

                if (_blConnector.MemberRegister(memberReg, out string errorMessage))
                {
                    Log.Write("User created JXT next DB" + existingUser.Email, ConfigurationPolicy.ErrorLog);
                }
            }
            // end of the code for the user check in the JXT Next DB
            var userManager = UserManager.GetManager();

            SecurityManager.AuthenticateUser(userManager.Provider.Name, emailAddress, false, out User user);

            return(user != null);
        }
        /// <summary>
        /// Create user from the LinkedIn profile data.
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        private bool CreateUserFromLinkedInProfileData(string accessToken)
        {
            // get the email address from the profile
            var emailAddress = LinkedInHelper.GetProfileEmailAddress(accessToken);

            if (string.IsNullOrEmpty(emailAddress))
            {
                Log.Write("LinkedIn: Email address not present in the response.");

                return(false);
            }

            // if an account already exist then authenticate
            var existingUser = SitefinityHelper.GetUserByEmail(emailAddress);

            if (existingUser != null)
            {
                if (!AuthenticateUser(emailAddress))
                {
                    Log.Write("LinkedIn: Unable to authenticate user using the email address.");

                    return(false);
                }

                return(true);
            }

            // at this point create a new account

            var profile = LinkedInHelper.GetProfile(accessToken);

            var membershipCreateStatus = SitefinityHelper.CreateUser(
                emailAddress,
                System.Web.Security.Membership.GeneratePassword(12, 2),
                profile.FirstName,
                profile.LastName,
                emailAddress,
                null,
                null,
                null,
                true,
                true
                );

            if (membershipCreateStatus != MembershipCreateStatus.Success)
            {
                Log.Write("LinkedIn: Unable to create user account.");

                return(false);
            }

            if (!AuthenticateUser(emailAddress))
            {
                Log.Write("LinkedIn: Unable to authenticate user using the email address after registration.");

                return(false);
            }

            return(true);
        }
Exemplo n.º 3
0
        // GET: JobDetails
        public ActionResult Index(int?jobId)
        {
            JobDetailsViewModel viewModel = new JobDetailsViewModel();

            if (jobId.HasValue)
            {
                // Get job source or url referral

                string UrlReferral = string.Empty;
                if (!string.IsNullOrWhiteSpace(Request.QueryString["source"]))
                {
                    UrlReferral = Request.QueryString["source"];
                }
                else
                {
                    UrlReferral = this.GetCookieDomain(Request.Cookies["JobsViewed"], jobId.Value);
                }

                viewModel.UrlReferral = UrlReferral;
                Log.Write($" viewModel.UrlReferral  : " + viewModel.UrlReferral, ConfigurationPolicy.ErrorLog);

                IGetJobListingRequest jobListingRequest = new JXTNext_GetJobListingRequest {
                    JobID = jobId.Value
                };
                IGetJobListingResponse jobListingResponse = _BLConnector.GuestGetJob(jobListingRequest);

                if (jobListingResponse.Job != null && !jobListingResponse.Job.IsDeleted)
                {
                    viewModel.JobDetails = jobListingResponse.Job;

                    // Getting Consultant Avatar Image Url from Sitefinity
                    viewModel.ApplicationEmail = jobListingResponse.Job.CustomData["ApplicationMethod.ApplicationEmail"];
                    var user = SitefinityHelper.GetUserByEmail(jobListingResponse.Job.CustomData["ApplicationMethod.ApplicationEmail"]);
                    if (user != null && user.Id != Guid.Empty)
                    {
                        viewModel.ApplicationAvatarImageUrl = SitefinityHelper.GetUserAvatarUrlById(user.Id);
                    }

                    if (this.Model.IsJobApplyAvailable())
                    {
                        viewModel.JobApplyAvailable = true;
                    }

                    // Processing Classifications
                    OrderedDictionary classifOrdDict = new OrderedDictionary();
                    classifOrdDict.Add(jobListingResponse.Job.CustomData["Classifications[0].Filters[0].ExternalReference"], jobListingResponse.Job.CustomData["Classifications[0].Filters[0].Value"]);
                    string parentClassificationsKey = "Classifications[0].Filters[0].SubLevel[0]";
                    JobDetailsViewModel.ProcessCustomData(parentClassificationsKey, jobListingResponse.Job.CustomData, classifOrdDict);
                    OrderedDictionary classifParentIdsOrdDict = new OrderedDictionary();
                    JobDetailsViewModel.AppendParentIds(classifOrdDict, classifParentIdsOrdDict);

                    var bull = jobListingResponse.Job.CustomData["Bulletpoints.BulletPoint1"];

                    // Processing Locations
                    OrderedDictionary locOrdDict = new OrderedDictionary();
                    locOrdDict.Add(jobListingResponse.Job.CustomData["CountryLocationArea[0].Filters[0].ExternalReference"], jobListingResponse.Job.CustomData["CountryLocationArea[0].Filters[0].Value"]);
                    string parentLocKey = "CountryLocationArea[0].Filters[0].SubLevel[0]";
                    JobDetailsViewModel.ProcessCustomData(parentLocKey, jobListingResponse.Job.CustomData, locOrdDict);
                    OrderedDictionary locParentIdsOrdDict = new OrderedDictionary();
                    JobDetailsViewModel.AppendParentIds(locOrdDict, locParentIdsOrdDict);

                    DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(ConversionHelper.GetDateTimeFromUnix(jobListingResponse.Job.DateCreated), TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time"));
                    DateTime utcTime   = ConversionHelper.GetDateTimeFromUnix(jobListingResponse.Job.DateCreated);
                    DateTime elocalTime;
                    DateTime eutcTime = new DateTime();
                    TimeSpan offset   = localTime - utcTime;
                    TimeSpan eoffset  = new TimeSpan();


                    if (jobListingResponse.Job.ExpiryDate.HasValue)
                    {
                        elocalTime = TimeZoneInfo.ConvertTimeFromUtc(ConversionHelper.GetDateTimeFromUnix(jobListingResponse.Job.ExpiryDate.Value), TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time"));
                        eutcTime   = ConversionHelper.GetDateTimeFromUnix(jobListingResponse.Job.ExpiryDate.Value);
                        eoffset    = elocalTime - eutcTime;
                    }

                    viewModel.Classifications         = classifParentIdsOrdDict;
                    viewModel.Locations               = locParentIdsOrdDict;
                    viewModel.ClassificationsRootName = "Classifications";
                    viewModel.LocationsRootName       = "CountryLocationArea";
                    var siteSettingsHelper = new SiteSettingsHelper();
                    viewModel.JobCurrencySymbol = siteSettingsHelper.GetJobCurrencySymbol();

                    // Getting the SEO route name for classifications
                    List <string> seoString = new List <string>();
                    foreach (var key in classifParentIdsOrdDict.Keys)
                    {
                        string value     = classifParentIdsOrdDict[key].ToString();
                        string SEOString = Regex.Replace(value, @"([^\w]+)", "-");
                        seoString.Add(SEOString);
                    }

                    viewModel.ClassificationsSEORouteName = jobListingResponse.Job.ClassificationURL;

                    ViewBag.CssClass = this.CssClass;
                    ViewBag.JobApplicationPageUrl = SfPageHelper.GetPageUrlById(JobApplicationPageId.IsNullOrWhitespace() ? Guid.Empty : new Guid(JobApplicationPageId));
                    ViewBag.JobResultsPageUrl     = SfPageHelper.GetPageUrlById(JobResultsPageId.IsNullOrWhitespace() ? Guid.Empty : new Guid(JobResultsPageId));
                    ViewBag.EmailJobPageUrl       = SfPageHelper.GetPageUrlById(EmailJobPageId.IsNullOrWhitespace() ? Guid.Empty : new Guid(EmailJobPageId));
                    ViewBag.GoogleForJobs         = ReplaceToken(GoogleForJobsTemplate, JsonConvert.SerializeObject(new
                    {
                        CurrencySymbol        = "$",
                        SalaryLowerBand       = jobListingResponse.Job.CustomData.ContainsKey("Salaries[0].Filters[0].Min") ? jobListingResponse.Job.CustomData["Salaries[0].Filters[0].Min"] : null,
                        SalaryUpperBand       = jobListingResponse.Job.CustomData.ContainsKey("Salaries[0].Filters[0].Max") ? jobListingResponse.Job.CustomData["Salaries[0].Filters[0].Max"] : null,
                        FullDescription       = jobListingResponse.Job.Description,
                        Description           = jobListingResponse.Job.ShortDescription,
                        AdvertiserCompanyName = jobListingResponse.Job.CustomData.ContainsKey("CompanyName") ? jobListingResponse.Job.CustomData["CompanyName"] : null,
                        ProfessionName        = jobListingResponse.Job.CustomData.ContainsKey("Classifications[0].Filters[0].Value") ? jobListingResponse.Job.CustomData["Classifications[0].Filters[0].Value"] : null,
                        LocationName          = jobListingResponse.Job.CustomData.ContainsKey("CountryLocationArea[0].Filters[0].Value") ? jobListingResponse.Job.CustomData["CountryLocationArea[0].Filters[0].Value"] : null,
                        AreaName   = jobListingResponse.Job.CustomData.ContainsKey("CountryLocationArea[0].Filters[0].SubLevel[0].Value") ? jobListingResponse.Job.CustomData["CountryLocationArea[0].Filters[0].SubLevel[0].Value"] : null,
                        JobName    = jobListingResponse.Job.Title,
                        DatePosted = string.Format("|{0}+{1}|", utcTime.ToString("yyyy-MM-ddThh:mm:ss"), offset.Hours.ToString("00") + ":" + offset.Minutes.ToString("00")),
                        ExpiryDate = (jobListingResponse.Job.ExpiryDate.HasValue) ? string.Format("|{0}+{1}|", eutcTime.ToString("yyyy-MM-ddThh:mm:ss"), eoffset.Hours.ToString("00") + ":" + eoffset.Minutes.ToString("00")) : string.Empty,
                        Address    = jobListingResponse.Job.Address
                    }));
                    var fullTemplateName = this.templateNamePrefix + this.TemplateName;
                    // If it is null make sure that pass empty string , because html attrubutes will not work properly.
                    viewModel.JobDetails.Address           = viewModel.JobDetails.Address == null ? "" : viewModel.JobDetails.Address;
                    viewModel.JobDetails.AddressLatitude   = viewModel.JobDetails.AddressLatitude == null ? "" : viewModel.JobDetails.AddressLatitude;
                    viewModel.JobDetails.AddressLongtitude = viewModel.JobDetails.AddressLongtitude == null ? "" : viewModel.JobDetails.AddressLongtitude;

                    #region Check job already applied
                    ViewBag.IsJobApplied = false;
                    JXTNext_MemberAppliedJobResponse response = _BLConnector.MemberAppliedJobsGet() as JXTNext_MemberAppliedJobResponse;
                    if (response.Success)
                    {
                        foreach (var item in response.MemberAppliedJobs)
                        {
                            if (item.JobId == jobId.Value)
                            {
                                ViewBag.IsJobApplied = true;
                                break;
                            }
                        }
                    }
                    #endregion
                    var meta = new System.Web.UI.HtmlControls.HtmlMeta();
                    meta.Attributes.Add("property", "og:title");
                    meta.Content = jobListingResponse.Job.Title;

                    // Get the current page handler in order to access the page header
                    var pageHandler = this.HttpContext.CurrentHandler.GetPageHandler();
                    pageHandler.Header.Controls.Add(meta);
                    return(View(fullTemplateName, viewModel));
                }
                else
                {
                    if (jobListingResponse.Job != null && jobListingResponse.Job.IsDeleted)
                    {
                        return(Content("This Job is no longer available!"));
                    }
                    else
                    {
                        return(Content("No job has been found"));
                    }
                }
            }

            return(Content("No job has been selected"));
        }
Exemplo n.º 4
0
        public string GetOverrideEmail(ref JobApplicationStatus status, ref ApplicantInfo applicantInfo, bool isSocialMedia = false)
        {
            string ovverideEmail = null;

            if (SitefinityHelper.IsUserLoggedIn()) // User already logged in
            {
                var currUser = SitefinityHelper.GetUserById(ClaimsManager.GetCurrentIdentity().UserId);
                if (currUser != null)
                {
                    Log.Write("User is already logged In " + currUser.Email, ConfigurationPolicy.ErrorLog);
                    return(currUser.Email);
                }
            }

            // User not looged in
            if (!string.IsNullOrEmpty(applicantInfo.Email))
            {
                Telerik.Sitefinity.Security.Model.User existingUser = SitefinityHelper.GetUserByEmail(applicantInfo.Email);

                if (existingUser != null)
                {
                    #region Entered Email exists in Sitefinity User list
                    Log.Write("User is already exists in portal " + existingUser.Email, ConfigurationPolicy.ErrorLog);
                    ovverideEmail = existingUser.Email;
                    // check user exists in the JXT next DB
                    var memberResponse = _blConnector.GetMemberByEmail(applicantInfo.Email);
                    if (memberResponse.Member == null)
                    {
                        UserProfileManager userProfileManager = UserProfileManager.GetManager();
                        UserProfile        profile            = userProfileManager.GetUserProfile(existingUser.Id, typeof(SitefinityProfile).FullName);
                        var fName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "FirstName");
                        var lName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "LastName");
                        JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
                        {
                            Email     = existingUser.Email,
                            FirstName = fName.ToString(),
                            LastName  = lName.ToString(),
                            Password  = existingUser.Password
                        };

                        if (_blConnector.MemberRegister(memberReg, out string errorMessage))
                        {
                            Log.Write("User created JXT next DB" + existingUser.Email, ConfigurationPolicy.ErrorLog);
                        }
                    }
                    return(ovverideEmail);

                    #endregion
                }
                else
                {
                    #region Entered email does not exists in sitefinity User list
                    var membershipCreateStatus = SitefinityHelper.CreateUser(applicantInfo.Email, applicantInfo.Password, applicantInfo.FirstName, applicantInfo.LastName, applicantInfo.Email, applicantInfo.PhoneNumber,
                                                                             null, null, true, true);
                    applicantInfo.IsNewUser = true;
                    if (membershipCreateStatus != MembershipCreateStatus.Success)
                    {
                        Log.Write("User is created in portal " + existingUser.Email, ConfigurationPolicy.ErrorLog);
                        status = JobApplicationStatus.NotAbleToCreateUser;
                        return(ovverideEmail);
                    }
                    else
                    {
                        //instantiate the Sitefinity user manager
                        //if you have multiple providers you have to pass the provider name as parameter in GetManager("ProviderName") in your case it will be the asp.net membership provider user
                        UserManager userManager = UserManager.GetManager();
                        if (userManager.ValidateUser(applicantInfo.Email, applicantInfo.Password))
                        {
                            //if you need to get the user instance use the out parameter
                            Telerik.Sitefinity.Security.Model.User userToAuthenticate = null;
                            SecurityManager.AuthenticateUser(userManager.Provider.Name, applicantInfo.Email, applicantInfo.Password, false, out userToAuthenticate);
                            if (userToAuthenticate == null)
                            {
                                status = JobApplicationStatus.NotAbleToLoginCreatedUser;
                                return(ovverideEmail);
                            }
                            else
                            {
                                ovverideEmail = userToAuthenticate.Email;
                            }
                        }
                    }
                    #endregion
                }
            }

            return(ovverideEmail);
        }
        private CreateJobApplicationResponse CreateJobApplication(
            SocialMediaProcessedResponse result,
            JobDetailsModel jobDetails,
            ApplicantInfo applicantInfo,
            string overrideEmail)
        {
            // Gather Attachments
            Guid identifier = Guid.NewGuid();
            JobApplicationAttachmentUploadItem uploadItem = new JobApplicationAttachmentUploadItem()
            {
                Id               = identifier.ToString(),
                AttachmentType   = JobApplicationAttachmentType.Resume,
                FileName         = result.FileName,
                FileStream       = result.FileStream,
                PathToAttachment = identifier.ToString() + "_" + result.FileName,
                Status           = "Ready"
            };



            // End code for fetch job details
            Log.Write("overrideEmail uploadItem object created", ConfigurationPolicy.ErrorLog);
            List <JobApplicationAttachmentUploadItem> attachments = new List <JobApplicationAttachmentUploadItem>();

            attachments.Add(uploadItem);
            Log.Write("overrideEmail uploadItem attachment added", ConfigurationPolicy.ErrorLog);
            string resumeAttachmentPath = JobApplicationAttachmentUploadItem.GetAttachmentPath(attachments, JobApplicationAttachmentType.Resume);

            Log.Write("After resume GetAttachmentPath", ConfigurationPolicy.ErrorLog);
            string coverletterAttachmentPath = JobApplicationAttachmentUploadItem.GetAttachmentPath(attachments, JobApplicationAttachmentType.Coverletter);

            Log.Write("After cover letter GetAttachmentPath", ConfigurationPolicy.ErrorLog);

            string htmlEmailContent           = this.GetEmailHtmlContent(this.EmailTemplateId);
            string htmlEmailSubject           = this.GetEmailSubject(this.EmailTemplateId);
            string htmlAdvertiserEmailContent = this.GetEmailHtmlContent(this.AdvertiserEmailTemplateId);
            string htmlAdvertiserEmailSubject = this.GetEmailSubject(this.AdvertiserEmailTemplateId);

            Log.Write("After GetHtmlEmailContent", ConfigurationPolicy.ErrorLog);
            // Email notification settings


            List <dynamic> emailAttachments = new List <dynamic>();

            foreach (var item in attachments)
            {
                dynamic emailAttachment = new ExpandoObject();
                emailAttachment.FileStream = item.FileStream;
                emailAttachment.FileName   = item.FileName;
                emailAttachments.Add(emailAttachment);
            }

            EmailNotificationSettings advertiserEmailNotificationSettings = (this.AdvertiserEmailTemplateId != null) ?
                                                                            _createAdvertiserEmailTemplate(
                new JobApplicationEmailTemplateModel()
            {
                FromFirstName = result.FirstName,
                FromLastName  = result.LastName,
                FromEmail     = overrideEmail,
                ToFirstName   = jobDetails.ContactDetails.GetFirstName(),
                ToLastName    = jobDetails.ContactDetails.GetLastName(),
                ToEmail       = jobDetails.ApplicationEmail,
                Subject       = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.AdvertiserEmailTemplateId),
                HtmlContent   = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.AdvertiserEmailTemplateId),
                Attachments   = emailAttachments
            }) : null;



            EmailNotificationSettings emailNotificationSettings = (this.EmailTemplateId != null) ?
                                                                  _createApplicantEmailTemplate(
                new JobApplicationEmailTemplateModel()
            {
                FromFirstName = this.EmailTemplateSenderName,
                FromLastName  = null,
                FromEmail     = this.EmailTemplateSenderEmailAddress,
                ToFirstName   = SitefinityHelper.GetUserFirstNameById(SitefinityHelper.GetUserByEmail(overrideEmail).Id),
                ToLastName    = null,
                ToEmail       = overrideEmail,
                Subject       = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.EmailTemplateId),
                HtmlContent   = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.EmailTemplateId),
                Attachments   = null
            }) : null;


            EmailNotificationSettings registrationNotificationsSettings = (applicantInfo.IsNewUser && this.RegistrationEmailTemplateId != null) ?
                                                                          _createRegistrationEmailTemplate(
                new JobApplicationEmailTemplateModel()
            {
                FromFirstName = this.EmailTemplateSenderName,
                FromLastName  = null,
                FromEmail     = this.EmailTemplateSenderEmailAddress,
                ToFirstName   = applicantInfo.FirstName,
                ToLastName    = null,
                ToEmail       = applicantInfo.Email,
                Subject       = SitefinityHelper.GetCurrentSiteEmailTemplateTitle(this.RegistrationEmailTemplateId),
                HtmlContent   = SitefinityHelper.GetCurrentSiteEmailTemplateHtmlContent(this.RegistrationEmailTemplateId),
                Attachments   = null
            }) : null;


            Log.Write("emailNotificationSettings after: ", ConfigurationPolicy.ErrorLog);

            Log.Write("BL response before: ", ConfigurationPolicy.ErrorLog);

            //Create Application
            var response = _blConnector.MemberCreateJobApplication(
                new JXTNext_MemberApplicationRequest
            {
                ApplyResourceID               = result.JobId.Value,
                MemberID                      = 2,
                ResumePath                    = resumeAttachmentPath,
                CoverletterPath               = coverletterAttachmentPath,
                EmailNotification             = emailNotificationSettings,
                AdvertiserEmailNotification   = advertiserEmailNotificationSettings,
                AdvertiserName                = jobDetails.ContactDetails,
                CompanyName                   = jobDetails.CompanyName,
                UrlReferral                   = result.UrlReferral,
                RegistrationEmailNotification = registrationNotificationsSettings
            },
                overrideEmail);

            Log.Write("BL response after: ", ConfigurationPolicy.ErrorLog);

            var createJobApplicationResponse = new CreateJobApplicationResponse {
                MemberApplicationResponse = response
            };

            if (response.Success && response.ApplicationID.HasValue)
            {
                Log.Write("BL response in: ", ConfigurationPolicy.ErrorLog);
                var hasFailedUpload = _jobApplicationService.UploadFiles(attachments);
                Log.Write("file upload is : " + hasFailedUpload, ConfigurationPolicy.ErrorLog);
                if (hasFailedUpload)
                {
                    createJobApplicationResponse.FilesUploaded = false;
                    createJobApplicationResponse.Status        = JobApplicationStatus.Technical_Issue; // Unable to attach files
                    createJobApplicationResponse.Message       = "Unable to attach files to application";
                }
                else
                {
                    createJobApplicationResponse.FilesUploaded = true;
                    createJobApplicationResponse.Status        = JobApplicationStatus.Applied_Successful;
                    createJobApplicationResponse.Message       = "Your application was successfully processed.";
                }
            }
            else
            {
                if (response.Errors.FirstOrDefault().ToLower().Contains("already exists"))
                {
                    createJobApplicationResponse.Status  = JobApplicationStatus.Already_Applied;
                    createJobApplicationResponse.Message = "You have already applied to this job.";
                }
                else
                {
                    createJobApplicationResponse.Status  = JobApplicationStatus.Technical_Issue;
                    createJobApplicationResponse.Message = response.Errors.FirstOrDefault();
                }
            }

            return(createJobApplicationResponse);
        }