Ejemplo n.º 1
0
def find_partner_from_email(partner_list, email):
    """
    Finds a possible partner based on the email domain.

    inputs:
    :partner_list: The partner list to compare the email against.
    :email: The email address the domain is needed for.

    outputs:
    A matching partner if there is one, otherwise None.

    """
    if not email or '@' not in email or not partner_list:
        return None
    email_domain = email.split('@')[-1]

    for partner in partner_list:
        url = get_domain(partner.uri)
        # Pass through get_domain() to strip subdomains
        email_domain = get_domain(email_domain)

        if email_domain and url and email_domain.lower() == url.lower():
            return partner

    return None
Ejemplo n.º 2
0
def find_partner_from_email(partner_list, email):
    """
    Finds a possible partner based on the email domain.

    inputs:
    :partner_list: The partner list to compare the email against.
    :email: The email address the domain is needed for.

    outputs:
    A matching partner if there is one, otherwise None.

    """
    if not email or '@' not in email or not partner_list:
        return None
    email_domain = email.split('@')[-1]

    for partner in partner_list:
        url = get_domain(partner.uri)
        # Pass through get_domain() to strip subdomains
        email_domain = get_domain(email_domain)

        if email_domain and url and email_domain.lower() == url.lower():
            return partner

    return None
Ejemplo n.º 3
0
def saved_searches(employer, company, candidate):
    """
    Function that gets employer's companies and those companies microsites.
    Will pull the domain out of the employer_microsites. Gathers the
    candidate's saved search urls and then will pull those urls
    out. Lastly, check to see if employer domains match up with
    candidate domains and return a list of urls.

    inputs:
    :employer:  The employer that is looking at candidate's page
    :candidate: The job seeker that shows up in employer's activitiy feed

    outputs:
                A list of candidate urls.
    """
    if employer not in company.admins.all():
        raise Http404

    employer_microsites = get_company_microsites(company)[0]
    candidate_searches = candidate.savedsearch_set.values_list('feed', flat=True)
    # Switch all company's microsites and candidate's saved searches to just
    # the domain so they can be easily compared.
    employer_domains = [get_domain(url).lower() for url in employer_microsites]
    candidate_domains = [get_domain(url).lower() for url in candidate_searches]

    return [url for url in candidate_domains if url in employer_domains]
Ejemplo n.º 4
0
def update_url_if_protected(url, user):
    """
    Adds a key that bypasses authorization on protected sites
    if the site is protected and the user has access to the site.

    """
    from seo.models import SeoSite

    search_domain = urlparse(url).netloc
    protected_domains = []
    for key in settings.PROTECTED_SITES.keys():
        try:
            protected_domains.append(SeoSite.objects.get(pk=key).domain)
        except SeoSite.DoesNotExist:
            pass

    cleaned_protected_domains = [get_domain(domain)
                                 for domain in protected_domains]

    if search_domain in cleaned_protected_domains:
        indx = cleaned_protected_domains.index(search_domain)
        groups = settings.PROTECTED_SITES[settings.PROTECTED_SITES.keys()[indx]]
        if list(set(groups) & set(user.groups.values_list('id', flat=True))):
            if '?' in url:
                url = "%s&key=%s" % (url, settings.SEARCH_API_KEY)
            else:
                url = "%s?key=%s" % (url, settings.SEARCH_API_KEY)

    return url
Ejemplo n.º 5
0
def update_url_if_protected(url, user):
    """
    Adds a key that bypasses authorization on protected sites
    if the site is protected and the user has access to the site.

    """
    from seo.models import SeoSite

    search_domain = urlparse(url).netloc
    protected_domains = []
    for key in settings.PROTECTED_SITES.keys():
        try:
            protected_domains.append(SeoSite.objects.get(pk=key).domain)
        except SeoSite.DoesNotExist:
            pass

    cleaned_protected_domains = [get_domain(domain)
                                 for domain in protected_domains]

    if search_domain in cleaned_protected_domains:
        indx = cleaned_protected_domains.index(search_domain)
        groups = settings.PROTECTED_SITES[settings.PROTECTED_SITES.keys()[indx]]
        if list(set(groups) & set(user.groups.values_list('id', flat=True))):
            if '?' in url:
                url = "%s&key=%s" % (url, settings.SEARCH_API_KEY)
            else:
                url = "%s?key=%s" % (url, settings.SEARCH_API_KEY)

    return url
Ejemplo n.º 6
0
def candidate_information(request):
    """
    Sends user info, primary name, and searches to candidate_information.html.
    Gathers the employer's (request.user) companies and microsites and puts
    the microsites' domains in a list for further checking and logic,
    see helpers.py.

    """
    user_id = get_int_or_none(request.REQUEST.get('user'))
    company = get_company(request)

    if not user_id or not company:
        raise Http404

    # user gets pulled out from id
    try:
        candidate = User.objects.get(id=user_id)
    except User.DoesNotExist:
        raise Http404

    if not candidate.opt_in_employers:
        raise Http404

    urls = saved_searches(request.user, company, candidate)
    actions = analytics(request.user, company, candidate)
    actions = get_analytics_counts(actions)

    if not urls and not actions:
        raise Http404

    manager = PrimaryNameProfileUnitManager(order=['employmenthistory',
                                                   'education',
                                                   'militaryservice'])
    models = manager.displayed_units(candidate.profileunits_set.all())

    primary_name = getattr(manager, 'primary_name', 'Name not given')

    coming_from = {'path': 'view'}

    searches = candidate.savedsearch_set.all()
    searches = [search for search in searches
                if get_domain(search.feed).lower() in urls]

    modified_url = remove_param_from_url(request.build_absolute_uri(), 'user')
    query_string = "?%s" % urlparse(modified_url).query

    data_dict = {
        'user_info': models,
        'company_id': company.pk,
        'primary_name': primary_name,
        'the_user': candidate,
        'searches': searches,
        'coming_from': coming_from,
        'query_string': query_string,
        'actions': actions,
    }

    return render_to_response('mydashboard/candidate_information.html',
                              data_dict, RequestContext(request))
Ejemplo n.º 7
0
    def registration_source(self):
        from seo.models import SeoSite

        domain = get_domain(self.source)
        # Use __iendswith because we strip subdomains in get_domain but
        # the subdomain will still be present in SeoSite.domain.
        try:
            return SeoSite.objects.filter(domain__iendswith=domain)[0]
        except (IndexError, ValueError):
            return None
Ejemplo n.º 8
0
    def clean_email_domain(self):
        # TODO: Finish after MX Records are sorted out
        # Determine if the company actually has permission to use the domain.
        domains = self.canonical_company.get_seo_sites().values_list('domain',
                                                                     flat=True)
        domains = [get_domain(domain) for domain in domains]
        domains.append('my.jobs')
        if self.email_domain not in domains:
            raise ValidationError('You can only send emails from a domain '
                                  'that is associated with your company.')

        # Ensure that we have an MX record for the domain.
        if not can_send_email(self.email_domain):
            raise ValidationError('You do not currently have the ability '
                                  'to send emails from this domain.')
        return self.email_domain
Ejemplo n.º 9
0
def home(request):
    """
    The home page view receives 2 separate Ajax requests, one for the
    registration form and another for the initial profile information form. If
    everything checks out alright and the form saves with no errors, it returns
    a simple string, 'valid', as an HTTP Response, which the front end
    recognizes as a signal to continue with the account creation process. If an
    error occurs, this triggers the jQuery to update the page. The form
    instances with errors must be passed back to the form template it was
    originally from.

    """
    registration_form = RegistrationForm(auto_id=False)
    login_form = CustomAuthForm(auto_id=False)

    name_form = InitialNameForm(prefix="name")
    education_form = InitialEducationForm(prefix="edu")
    phone_form = InitialPhoneForm(prefix="ph")
    work_form = InitialWorkForm(prefix="work")
    address_form = InitialAddressForm(prefix="addr")
    nexturl = request.GET.get('next')
    title_template = get_title_template(nexturl)
    if nexturl:
        nexturl = urllib2.unquote(nexturl)
        nexturl = urllib2.quote(nexturl.encode('utf8'))

    last_ms = request.COOKIES.get('lastmicrosite')
    site_name = ''
    logo_url = ''
    show_registration = True
    if last_ms:
        try:
            last_ms = get_domain(last_ms)
            custom_page = CustomHomepage.objects.get(domain=last_ms)
            logo_url = custom_page.logo_url
            show_registration = custom_page.show_signup_form
            site_name = custom_page.name

        except CustomHomepage.DoesNotExist:
            pass

    data_dict = {'num_modules': len(settings.PROFILE_COMPLETION_MODULES),
                 'registrationform': registration_form,
                 'loginform': login_form,
                 'name_form': name_form,
                 'phone_form': phone_form,
                 'address_form': address_form,
                 'work_form': work_form,
                 'education_form': education_form,
                 'nexturl': nexturl,
                 'logo_url': logo_url,
                 'show_registration': show_registration,
                 'site_name': site_name,
                 'logo_template': title_template,
                 }

    if request.method == "POST":
        if request.POST.get('action') == "register":
            registration_form = RegistrationForm(request.POST, auto_id=False)
            if registration_form.is_valid():
                new_user, created = User.objects.create_user(
                    request=request,
                    send_email=True,
                    **registration_form.cleaned_data)
                user_cache = authenticate(
                    username=registration_form.cleaned_data['email'],
                    password=registration_form.cleaned_data['password1'])
                expire_login(request, user_cache)
                # pass in gravatar url once user is logged in. Image generated
                # on AJAX success
                html = render_to_response('includes/account-page-2.html',
                                          data_dict, RequestContext(request))
                data = {'gravatar_url': new_user.get_gravatar_url(size=100),
                        'html': html.content}
                response = HttpResponse(json.dumps(data))
                response.set_cookie('myguid', new_user.user_guid,
                                    expires=365*24*60*60, domain='.my.jobs')
                return response
            else:
                return HttpResponse(json.dumps(
                    {'errors': registration_form.errors.items()}))

        elif request.POST.get('action') == "login":
            login_form = CustomAuthForm(data=request.POST)
            if login_form.is_valid():
                expire_login(request, login_form.get_user())

                url = request.POST.get('nexturl')

                # Boolean for activation login page to show initial forms
                # again or not
                has_units = False
                if len(login_form.get_user().profileunits_set.all()) > 0:
                    has_units = True

                response_data = {
                    'validation': 'valid', 'url': url,
                    'units': has_units,
                    'gravatar_url': login_form.get_user().get_gravatar_url(
                        size=100)}
                response = HttpResponse(json.dumps(response_data))
                response.set_cookie('myguid', login_form.get_user().user_guid,
                                    expires=365*24*60*60, domain='.my.jobs')
                return response
            else:
                return HttpResponse(json.dumps({'errors':
                                                login_form.errors.items()}))

        elif request.POST.get('action') == "save_profile":
            name_form = InitialNameForm(request.POST, prefix="name",
                                        user=request.user)
            if not name_form.changed_data:
                name_form = InitialNameForm(prefix="name")

            education_form = InitialEducationForm(request.POST, prefix="edu",
                                                  user=request.user)
            if not education_form.changed_data:
                education_form = InitialEducationForm(prefix="edu")

            phone_form = InitialPhoneForm(request.POST, prefix="ph",
                                          user=request.user)
            if not phone_form.changed_data:
                phone_form = InitialPhoneForm(prefix="ph")

            work_form = InitialWorkForm(request.POST, prefix="work",
                                        user=request.user)
            if not work_form.changed_data:
                work_form = InitialWorkForm(prefix="work")

            address_form = InitialAddressForm(request.POST, prefix="addr",
                                              user=request.user)
            if not address_form.changed_data:
                address_form = InitialAddressForm(prefix="addr")

            forms = [name_form, education_form, phone_form, work_form,
                     address_form]
            valid_forms = [form for form in forms if form.is_valid()]
            invalid_forms = []
            for form in forms:
                if form.changed_data and not form.is_valid():
                    invalid_forms.append(form)

            if not invalid_forms:
                for form in valid_forms:
                    if form.changed_data:
                        form.save(commit=False)
                        form.user = request.user
                        form.save_m2m()
                return HttpResponse('valid')
            else:
                return render_to_response('includes/initial-profile-form.html',
                                          {'name_form': name_form,
                                           'phone_form': phone_form,
                                           'address_form': address_form,
                                           'work_form': work_form,
                                           'education_form': education_form},
                                          context_instance=RequestContext(
                                              request))

    return render_to_response('index.html', data_dict, RequestContext(request))
Ejemplo n.º 10
0
def dashboard(request, template="mydashboard/mydashboard.html",
              extra_context=None):
    """
    Returns a list of candidates who created a saved search for one of the
    microsites within the company microsite list or with the company name like
    jobs.jobs/company_name/careers for example between the given (optional)
    dates

    Inputs:
    :company:               company.id that is associated with request.user

    Returns:
    :render_to_response:    renders template with context dict

    """
    if hasattr(mail, 'outbox'):
        solr = settings.TEST_SOLR_INSTANCE
    else:
        solr = settings.SOLR

    company = get_company(request)
    if not company:
        raise Http404

    user_solr = Solr(solr['current'])
    facet_solr = Solr(solr['current'])

    # Add join only if we're using facets, not if we're simply searching.
    query_params = {'search', 'company'}
    if not query_params.issuperset({q_key for q_key in request.GET.keys()
                                    if q_key not in ['querystring_key',
                                                     'date_end', 'date_start',
                                                     'page']}):
        user_solr = user_solr.add_join(from_field='ProfileUnits_user_id',
                                       to_field='User_id')
    facet_solr = facet_solr.add_join(from_field='User_id',
                                     to_field='ProfileUnits_user_id')
    facet_solr = facet_solr.rows_to_fetch(0)

    authorized_microsites, buids = get_company_microsites(company)

    admins = CompanyUser.objects.filter(company=company.id)

    # Removes main user from admin list to display other admins
    admins = admins.exclude(user=request.user)
    requested_microsite = request.REQUEST.get('microsite', '')
    requested_date_button = request.REQUEST.get('date_button', False)    
    candidates_page = request.REQUEST.get('page', 1)    
          
    # the url value for 'All' in the select box is company name
    # which then gets replaced with all microsite urls for that company
    site_name = ''
    if requested_microsite != '':
        active_microsites = authorized_microsites.filter(
            domain__startswith=requested_microsite)
        user_solr, facet_solr = filter_by_domain(requested_microsite,
                                                 user_solr, facet_solr)
    else:
        active_microsites = authorized_microsites
        site_name = company.name
    if not site_name:
        try:
            site_name = active_microsites[0]
        except IndexError:
            site_name = ''
    active_microsites = set(active_microsites)

    rng, date_start, date_end, date_display = filter_by_date(request)
    user_solr = user_solr.add_filter_query(rng)
    facet_solr = facet_solr.add_query(rng)

    if request.GET.get('search', False):
        user_solr = user_solr.add_query("%s" % request.GET['search'])
        facet_solr = facet_solr.add_query("%s" % request.GET['search'])

    user_solr, facet_solr = filter_by_microsite(company, user_solr, facet_solr)

    (user_solr, facet_solr, filters) = apply_facets_and_filters(
        request, user_solr, facet_solr)

    solr_results = user_solr.rows_to_fetch(100).search()

    # List of dashboard widgets to display.
    dashboard_widgets = ["home_views", "search_views", "job_views",
                         "apply_clicks", "candidates", "search",
                         "applied_filters", "filters"]

    # Date button highlighting
    if 'today' in request.REQUEST:
        requested_date_button = 'today'
    elif 'seven_days' in request.REQUEST:
        requested_date_button = 'seven_days'
    elif 'thirty_days' in request.REQUEST:
        requested_date_button = 'thirty_days'

    url = request.build_absolute_uri()
    facets = parse_facets(facet_solr.search(), request)

    context = {
        'admin_you': request.user,
        'applied_filters': filters,
        'candidates_page': candidates_page,
        'company_admins': admins,
        'company_id': company.id,
        'company_microsites': authorized_microsites,
        'company_name': company.name,
        'dashboard_widgets': dashboard_widgets,
        'date_button': requested_date_button,
        'date_display': date_display,
        'date_end': date_end,
        'date_start': date_start,
        'date_submit_url': url,
        'facets': facets,
        'site_name': site_name,
        'view_name': 'Company Dashboard',
    }

    results = solr_results.docs

    facet_var_map = {
        'home': 'home',
        'listing': 'job_view',
        'results': 'search',
        'redirect': 'apply',
    }
    analytics_solr = Solr(solr['current']).add_facet_field(
        'page_category')
    if requested_microsite:
        analytics_solr = analytics_solr.add_query('domain:%s' %
                                                  requested_microsite)
    else:
        analytics_solr = analytics_solr.add_query('company_id:%d' % company.pk)

    rng = filter_by_date(request, field='view_date')[0]
    analytics_solr = analytics_solr.add_filter_query(rng)

    all_results = analytics_solr.rows_to_fetch(0).search()
    analytics_facets = all_results.facets.get('facet_fields', {}).get(
        'page_category', [])
    facet_dict = sequence_to_dict(analytics_facets)
    for key in facet_dict.keys():
        context_key = 'total_%s' % facet_var_map.get(key, '')
        context[context_key] = facet_dict[key]

    analytics_solr = analytics_solr.add_filter_query('User_id:[* TO *]')
    analytics_solr = analytics_solr.add_facet_field('domain')

    auth_results = analytics_solr.search()
    analytics_facet_list = auth_results.facets.get(
        'facet_fields', {}).get('domain', [])

    analytics_facets = sequence_to_dict(analytics_facet_list)
    analytics_facets = [domain for domain in analytics_facets.items()
                        if domain[0] in active_microsites]

    results += auth_results.docs

    candidates = dict_to_object(results)

    domains = [get_domain(c.SavedSearch_feed) for c in candidates
               if hasattr(c, 'SavedSearch_feed')]
    search_facets = [(domain, domains.count(domain)) for domain in set(domains)]

    domain_facets = {}
    for domain, group in groupby(analytics_facets + search_facets,
                                 key=lambda x: x[0]):
        domain_facets[domain] = sum(item[1] for item in group)

    candidate_list = sorted(candidates,
                            key=lambda y: y.SavedSearch_created_on
                            if hasattr(y, 'SavedSearch_created_on')
                            else y.view_date,
                            reverse=True)

    context['domain_facets'] = domain_facets
    context['candidates'] = candidate_list
    context['total_candidates'] = len([x for x in groupby(
        candidate_list, key=lambda y: y.User_id)])

    if extra_context is not None:
        context.update(extra_context)
    return render_to_response(template, context,
                              context_instance=RequestContext(request))
Ejemplo n.º 11
0
def home(request):
    """
    The home page view receives 2 separate Ajax requests, one for the
    registration form and another for the initial profile information form. If
    everything checks out alright and the form saves with no errors, it returns
    a simple string, 'valid', as an HTTP Response, which the front end
    recognizes as a signal to continue with the account creation process. If an
    error occurs, this triggers the jQuery to update the page. The form
    instances with errors must be passed back to the form template it was
    originally from.

    """
    registration_form = RegistrationForm(auto_id=False)
    login_form = CustomAuthForm(auto_id=False)

    name_form = InitialNameForm(prefix="name")
    education_form = InitialEducationForm(prefix="edu")
    phone_form = InitialPhoneForm(prefix="ph")
    work_form = InitialWorkForm(prefix="work")
    address_form = InitialAddressForm(prefix="addr")
    nexturl = request.GET.get('next')
    title_template = get_title_template(nexturl)
    if nexturl:
        nexturl = urllib2.unquote(nexturl)
        nexturl = urllib2.quote(nexturl.encode('utf8'))

    last_ms = request.COOKIES.get('lastmicrosite')
    site_name = ''
    logo_url = ''
    show_registration = True
    if last_ms:
        try:
            last_ms = get_domain(last_ms)
            custom_page = CustomHomepage.objects.get(domain=last_ms)
            logo_url = custom_page.logo_url
            show_registration = custom_page.show_signup_form
            site_name = custom_page.name

        except CustomHomepage.DoesNotExist:
            pass

    data_dict = {
        'num_modules': len(settings.PROFILE_COMPLETION_MODULES),
        'registrationform': registration_form,
        'loginform': login_form,
        'name_form': name_form,
        'phone_form': phone_form,
        'address_form': address_form,
        'work_form': work_form,
        'education_form': education_form,
        'nexturl': nexturl,
        'logo_url': logo_url,
        'show_registration': show_registration,
        'site_name': site_name,
        'logo_template': title_template,
    }

    if request.method == "POST":
        if request.POST.get('action') == "register":
            registration_form = RegistrationForm(request.POST, auto_id=False)
            if registration_form.is_valid():
                new_user, created = User.objects.create_user(
                    request=request,
                    send_email=True,
                    **registration_form.cleaned_data)
                user_cache = authenticate(
                    username=registration_form.cleaned_data['email'],
                    password=registration_form.cleaned_data['password1'])
                expire_login(request, user_cache)
                ctx = {}
                ctx['success'] = True
                response = HttpResponse(json.dumps(ctx))
                response.set_cookie('myguid',
                                    new_user.user_guid,
                                    expires=365 * 24 * 60 * 60,
                                    domain='.my.jobs')
                response.delete_cookie('loggedout')
                return response
            else:
                return HttpResponse(
                    json.dumps({'errors': registration_form.errors.items()}))

        elif request.POST.get('action') == "login":
            login_form = CustomAuthForm(data=request.POST)
            if login_form.is_valid():
                expire_login(request, login_form.get_user())

                url = request.POST.get('nexturl')

                # Boolean for activation login page to show initial forms
                # again or not
                has_units = False
                if len(login_form.get_user().profileunits_set.all()) > 0:
                    has_units = True

                response_data = {
                    'validation':
                    'valid',
                    'url':
                    url,
                    'units':
                    has_units,
                    'gravatar_url':
                    login_form.get_user().get_gravatar_url(size=100)
                }
                response = HttpResponse(json.dumps(response_data))
                response.set_cookie('myguid',
                                    login_form.get_user().user_guid,
                                    expires=365 * 24 * 60 * 60,
                                    domain='.my.jobs')
                response.delete_cookie('loggedout')
                return response
            else:
                return HttpResponse(
                    json.dumps({'errors': login_form.errors.items()}))

        elif request.POST.get('action') == "save_profile":
            name_form = InitialNameForm(request.POST,
                                        prefix="name",
                                        user=request.user)
            if not name_form.changed_data:
                name_form = InitialNameForm(prefix="name")

            education_form = InitialEducationForm(request.POST,
                                                  prefix="edu",
                                                  user=request.user)
            if not education_form.changed_data:
                education_form = InitialEducationForm(prefix="edu")

            phone_form = InitialPhoneForm(request.POST,
                                          prefix="ph",
                                          user=request.user)
            if not phone_form.changed_data:
                phone_form = InitialPhoneForm(prefix="ph")

            work_form = InitialWorkForm(request.POST,
                                        prefix="work",
                                        user=request.user)
            if not work_form.changed_data:
                work_form = InitialWorkForm(prefix="work")

            address_form = InitialAddressForm(request.POST,
                                              prefix="addr",
                                              user=request.user)
            if not address_form.changed_data:
                address_form = InitialAddressForm(prefix="addr")

            forms = [
                name_form, education_form, phone_form, work_form, address_form
            ]
            valid_forms = [form for form in forms if form.is_valid()]
            invalid_forms = []
            for form in forms:
                if form.changed_data and not form.is_valid():
                    invalid_forms.append(form)

            if not invalid_forms:
                for form in valid_forms:
                    if form.changed_data:
                        form.save(commit=False)
                        form.user = request.user
                        form.save_m2m()
                return HttpResponse('valid')
            else:
                return render_to_response(
                    'includes/initial-profile-form.html', {
                        'name_form': name_form,
                        'phone_form': phone_form,
                        'address_form': address_form,
                        'work_form': work_form,
                        'education_form': education_form
                    },
                    context_instance=RequestContext(request))

    return render_to_response('index.html', data_dict, RequestContext(request))