Example #1
0
def rolling_deadline_end(request, id, extra_context = None):
    if request.method == "POST":
        try:
            event = Event.objects.get(pk=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        else:
            if not event.is_rolling_deadline():
                raise Http403('You cannot end anything other than a rolling deadline.')
            if is_recruiter(event.owner):
                if not is_recruiter(request.user) or request.user.recruiter.employer != event.owner.recruiter.employer:
                    raise Http403('You are not allowed to end this rolling deadline.')
            elif is_campus_org(event.owner):
                if not is_campus_org(request.user) or request.user.campusorg != event.owner.campusorg:
                    raise Http403('You are not allowed to end this rolling deadline.')
            event.end_datetime = datetime.now()-timedelta(minutes=1)
            event.save()
            return HttpResponse()
    else:
        try:
            event = Event.objects.get(id=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        context = {'event':event}
        context.update(extra_context or {})
        return context
Example #2
0
def admin_of_event(event, user):
    if is_recruiter(event.owner):
        return is_recruiter(
            user) and user.recruiter.employer == event.owner.recruiter.employer
    elif is_campus_org(event.owner):
        return is_campus_org(user) and user.campusorg == event.owner.campusorg
    return False
Example #3
0
def rolling_deadline_end(request, id, extra_context=None):
    if request.method == "POST":
        try:
            event = Event.objects.get(pk=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        else:
            if not event.is_rolling_deadline():
                raise Http403(
                    'You cannot end anything other than a rolling deadline.')
            if is_recruiter(event.owner):
                if not is_recruiter(
                        request.user
                ) or request.user.recruiter.employer != event.owner.recruiter.employer:
                    raise Http403(
                        'You are not allowed to end this rolling deadline.')
            elif is_campus_org(event.owner):
                if not is_campus_org(
                        request.user
                ) or request.user.campusorg != event.owner.campusorg:
                    raise Http403(
                        'You are not allowed to end this rolling deadline.')
            event.end_datetime = datetime.now() - timedelta(minutes=1)
            event.save()
            return HttpResponse()
    else:
        try:
            event = Event.objects.get(id=id)
        except Event.DoesNotExist:
            raise Http404("Event with id '%s' does not exist." % id)
        context = {'event': event}
        context.update(extra_context or {})
        return context
Example #4
0
def event_new(request, form_class=None, extra_context=None):
    context = {}
    if is_recruiter(request.user):
        employer = request.user.recruiter.employer
        form_class = EventForm
    elif is_campus_org(request.user):
        form_class = CampusOrgEventForm
        context['max_industries'] = s.EP_MAX_INDUSTRIES
    if request.method == 'POST':
        form = form_class(data=request.POST)
        if form.is_valid():
            event = form.save(commit=False)
            event.owner = request.user
            event.save()
            form.save_m2m()
            if event.type.name == "Rolling Deadline":
                event.start_datetime = datetime.now() - timedelta(weeks=1)
                event.end_datetime = datetime.now() + timedelta(weeks=1000)
                event.save()
            elif event.type.name == "Hard Deadline":
                event.start_datetime = event.end_datetime
                event.save()
            if is_recruiter(request.user):
                event.attending_employers.add(employer)
                # Update index
                employer.save()
            notify_about_event(event, "new_event",
                               event.attending_employers.all())
            # Update index
            event.save()
            return HttpResponseRedirect(
                reverse('event_page',
                        kwargs={
                            'id': event.id,
                            'slug': event.slug
                        }))
    else:
        form = form_class(
            initial={
                'start_datetime': datetime.now() + timedelta(minutes=30),
                'end_datetime': datetime.now() +
                timedelta(hours=1, minutes=30),
            })
    context['hours'] = map(lambda x, y: str(x) + y,
                           [12] + range(1, 13) + range(1, 12),
                           ['am'] * 12 + ['pm'] * 12)
    context['form'] = form
    context['today'] = datetime.now().strftime('%m/%d/%Y')
    context['event_scheduler_date'] = datetime.now().strftime('%m/%d/%Y')
    context.update(extra_context or {})
    return context
Example #5
0
def get_audiences(user):
    if is_student(user):
        return [
            core_enums.ALL, core_enums.AUTHENTICATED,
            core_enums.ANONYMOUS_AND_STUDENTS, core_enums.STUDENT
        ]
    elif is_recruiter(user):
        return [
            core_enums.ALL, core_enums.AUTHENTICATED,
            core_enums.ANONYMOUS_AND_EMPLOYERS, core_enums.EMPLOYER,
            core_enums.CAMPUS_ORGS_AND_EMPLOYERS
        ]
    elif is_campus_org(user):
        return [
            core_enums.ALL, core_enums.AUTHENTICATED,
            core_enums.ANONYMOUS_AND_CAMPUS_ORGS, core_enums.CAMPUS_ORG,
            core_enums.CAMPUS_ORGS_AND_EMPLOYERS
        ]
    else:
        return [
            core_enums.ALL, core_enums.ANONYMOUS,
            core_enums.ANONYMOUS_AND_CAMPUS_ORGS,
            core_enums.ANONYMOUS_AND_EMPLOYERS,
            core_enums.ANONYMOUS_AND_STUDENTS
        ]
Example #6
0
def warnings(request):
    warnings = []
    if is_recruiter(request.user) and EmployerSubscription.objects.filter(
            employer=request.user.recruiter.employer).exists():
        employer_subscription = request.user.recruiter.employer.employersubscription
        subscription_path = reverse("subscriptions")
        if employer_subscription.expired():
            if request.get_full_path() != subscription_path:
                if employer_subscription.subscription.uid == s.EVENT_SUBSCRIPTION_UID:
                    warnings.append(
                        "Your {0} has expired. Please host another campus event or <a href='{1}'>upgrade now</a> to regain access."
                        .format(employer_subscription.subscription,
                                subscription_path))
                else:
                    warnings.append(
                        "Your {0} has expired. Please <a href='{1}'>renew it</a> to regain access."
                        .format(employer_subscription.subscription,
                                subscription_path))
            else:
                if employer_subscription.subscription.uid == s.EVENT_SUBSCRIPTION_UID:
                    warnings.append(
                        "Your {0} has expired. Please host another campus event or upgrade now to regain access."
                        .format(employer_subscription.subscription))
                else:
                    warnings.append(
                        "Your {0} has expired. Please renew it to regain access."
                        .format(employer_subscription.subscription))
    return {'warnings': warnings}
Example #7
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     if not view_func == serve and not view_func == debug_media and is_recruiter(request.user):
         customer = request.user.recruiter.employer.get_customer()
         request.META['customer'] = customer
         has_at_least_premium_var = has_at_least_premium(customer)
         request.META['has_at_least_premium'] = has_at_least_premium_var
         request.META['can_upgrade'] = not has_at_least_premium_var
Example #8
0
def caution(request):
    cautions = []
    if (
        is_recruiter(request.user)
        and EmployerSubscription.objects.filter(employer=request.user.recruiter.employer).exists()
    ):
        employer_subscription = request.user.recruiter.employer.employersubscription
        subscription_path = reverse("subscriptions")
        if employer_subscription.in_grace_period():
            action_wording = "Renew now"
            if employer_subscription.subscription.uid == s.EVENT_SUBSCRIPTION_UID:
                action_wording = "Upgrade now"
            if request.get_full_path() != subscription_path:
                cautions.append(
                    "Your {2} has expired - you have {0} of access left. <a href='{1}'>{3}</a>.".format(
                        employer_subscription.time_left(),
                        subscription_path,
                        employer_subscription.subscription,
                        action_wording,
                    )
                )
            else:
                cautions.append(
                    "Your {1} has expired - you have {0} of access left. {2}.".format(
                        employer_subscription.time_left(), employer_subscription.subscription, action_wording
                    )
                )
    return {"cautions": cautions}
Example #9
0
def event_rsvp(request, event_id):
    try:
        event = Event.objects.get(pk=event_id)
    except:
        raise Http404("Event with id '%s' does not exist." % event_id)
    else:
        # if method is GET then get a list of RSVPed students
        if request.method == 'GET' and is_campus_org(request.user) or is_recruiter(request.user):
            data = map(lambda n: {'id': n.student.id, 'email': n.student.user.email}, event.rsvp_set.all())
            return HttpResponse(simplejson.dumps(data), mimetype="application/json")
        # if POST then record student's RSVP
        elif request.method == 'POST' and is_student(request.user):
            isAttending = request.POST.get('attending', 'true')
            isAttending = True if isAttending=='true' else False
            rsvp, created = RSVP.objects.get_or_create(student=request.user.student, event=event)
            rsvp.attending = isAttending
            rsvp.save()
            if isAttending:
                DroppedResume.objects.get_or_create(event=event, student=request.user.student)
            if request.is_ajax():
                return HttpResponse()
            else:
                return redirect(reverse('event_page',kwargs={'id':id,'slug':event.slug}))
        else:
            raise Http403("You do not have access to this view.")
Example #10
0
def events(request, category, extra_context=None):
    context = {'category':category}
    if category=="past":
        context['past'] = True
    if category=="archived":
        context['archived'] = True
    # We do a special thing for upcoming events to display them as "Today", "Tomorrow", "This week"
    if category=="upcoming":
        context.update(event_filtering_helper(category, request))
    else:
        events_exist, events = event_filtering_helper(category, request)
        context['events_exist'] = events_exist
        context['events'] = events
    if request.is_ajax():
        template = loader.get_template("event_filtering_results.html")
        response = HttpResponse(template.render(RequestContext(request, context)))
        # Need the no-store header because of chrome history api bug
        # see http://stackoverflow.com/questions/8240710/chrome-history-api-problems
        response['Cache-Control'] = "no-store"
        return response
    else:
        if request.GET.has_key("query"):
            context['initial_state'] = simplejson.dumps(request.GET)
            context['event_filtering_form'] = EventFilteringForm(request.GET)
        else:
            context['event_filtering_form'] = EventFilteringForm()
        if is_campus_org(request.user) or is_recruiter(request.user):
            template = "events_employer_campus_org.html"
        elif is_student(request.user):
            if not request.user.student.profile_created:
                return redirect('student_profile')
            template = "events_student.html"
    return render_to_response(template, context, context_instance=RequestContext(request) )
Example #11
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     if not view_func == serve and not view_func == debug_media and is_recruiter(
             request.user):
         customer = request.user.recruiter.employer.get_customer()
         request.META['customer'] = customer
         has_at_least_premium_var = has_at_least_premium(customer)
         request.META['has_at_least_premium'] = has_at_least_premium_var
         request.META['can_upgrade'] = not has_at_least_premium_var
Example #12
0
def get_audiences(user):
    if is_student(user):
        return [core_enums.ALL, core_enums.AUTHENTICATED, core_enums.ANONYMOUS_AND_STUDENTS, core_enums.STUDENT]
    elif is_recruiter(user):
        return [core_enums.ALL, core_enums.AUTHENTICATED, core_enums.ANONYMOUS_AND_EMPLOYERS, core_enums.EMPLOYER, core_enums.CAMPUS_ORGS_AND_EMPLOYERS]
    elif is_campus_org(user):
        return [core_enums.ALL, core_enums.AUTHENTICATED, core_enums.ANONYMOUS_AND_CAMPUS_ORGS, core_enums.CAMPUS_ORG, core_enums.CAMPUS_ORGS_AND_EMPLOYERS]
    else:
        return [core_enums.ALL, core_enums.ANONYMOUS, core_enums.ANONYMOUS_AND_CAMPUS_ORGS, core_enums.ANONYMOUS_AND_EMPLOYERS, core_enums.ANONYMOUS_AND_STUDENTS]
Example #13
0
def events_check_short_slug_uniqueness(request):
    if not request.GET.has_key("short_slug"):
        raise Http400("Request GET is missing the short_slug.")
    data = {'used':False}
    if is_campus_org(request.user):
        if Event.objects.filter(short_slug = request.GET['short_slug'], owner=request.user).exists():
            data['used'] = True
    elif is_recruiter(request.user):
        if Event.objects.filter(short_slug = request.GET['short_slug'], owner__recruiter__employer=request.user.recruiter.employer).exists():
            data['used'] = True
    return HttpResponse(simplejson.dumps(data), mimetype="application/json")
Example #14
0
def event_edit(request, id=None, extra_context=None):
    try:
        event = Event.objects.get(pk=id)
    except Event.DoesNotExist:
        raise Http404("Event with id '%s' does not exist." % id)

    context = {'event': event}
    if not admin_of_event(event, request.user):
        raise Http403('You are not allowed to edit this event.')
    if is_recruiter(event.owner):
        form_class = EventForm
    elif is_campus_org(event.owner):
        context['max_industries'] = s.EP_MAX_INDUSTRIES
        context['attending_employers'] = event.attending_employers
        form_class = CampusOrgEventForm
    if request.method == 'POST':
        form = form_class(request.POST, instance=event)
        if form.is_valid():
            event = form.save(commit=False)
            event.edits.add(Edit.objects.create(user=request.user))
            for employer in event.attending_employers.all():
                event.previously_attending_employers.add(employer)
            event.save()
            form.save_m2m()
            # Update index
            event.save()
            notify_about_event(event, "new_event", [
                e for e in list(event.attending_employers.all())
                if e not in list(event.previously_attending_employers.all())
            ])
            return HttpResponseRedirect(
                reverse('event_page',
                        kwargs={
                            'id': event.id,
                            'slug': event.slug
                        }))
    else:
        form = form_class(instance=event)
    context['edit'] = True
    context['hours'] = map(lambda x, y: str(x) + y,
                           [12] + range(1, 13) + range(1, 12),
                           ['am'] * 12 + ['pm'] * 12)
    context['form'] = form
    context['today'] = datetime.now().strftime('%m/%d/%Y')
    if event.type.name == "Hard Deadline":
        context['event_scheduler_date'] = event.end_datetime.strftime(
            '%m/%d/%Y')
    elif event.type.name == "Rolling Deadline":
        context['event_scheduler_date'] = datetime.now().strftime('%m/%d/%Y')
    else:
        context['event_scheduler_date'] = event.start_datetime.strftime(
            '%m/%d/%Y')
    context.update(extra_context or {})
    return context
Example #15
0
def tutorial(request, slug, extra_context = None):
    tutorial = get_object_or_404(Tutorial, slug=slug)
    context = {
       'tutorial':tutorial,
       'TEMPLATE': 'tutorials/%s.html' % tutorial.slug.replace("-", "_")
    }
    if is_recruiter(request.user):
        context['other_recruiters'] = request.user.recruiter.employer.recruiter_set.exclude(id=request.user.recruiter.id)
    
    context.update(extra_context or {})
    return context
Example #16
0
def event_new(request, form_class=None, extra_context=None):
    context = {}
    if is_recruiter(request.user):
        employer = request.user.recruiter.employer
        form_class = EventForm
    elif is_campus_org(request.user):
        form_class = CampusOrgEventForm
        context['max_industries'] = s.EP_MAX_INDUSTRIES
    if request.method == 'POST':
        form = form_class(data=request.POST)
        if form.is_valid():
            event = form.save(commit=False)
            event.owner = request.user
            event.save()
            form.save_m2m()
            if event.type.name == "Rolling Deadline":
                event.start_datetime = datetime.now() - timedelta(weeks=1)
                event.end_datetime = datetime.now() + timedelta(weeks=1000)
                event.save()
            elif event.type.name == "Hard Deadline":
                event.start_datetime = event.end_datetime
                event.save()
            if is_recruiter(request.user):
                event.attending_employers.add(employer)
                # Update index
                employer.save()
            notify_about_event(event, "new_event", event.attending_employers.all())
            # Update index
            event.save()
            return HttpResponseRedirect(reverse('event_page', kwargs={'id':event.id, 'slug':event.slug}))
    else:
        form = form_class(initial={
            'start_datetime': datetime.now() + timedelta(minutes=30),
            'end_datetime': datetime.now() + timedelta(hours=1, minutes=30),
        })
    context['hours'] = map(lambda x,y: str(x) + y, [12] + range(1,13) + range(1,12), ['am']*12 + ['pm']*12)
    context['form'] = form
    context['today'] = datetime.now().strftime('%m/%d/%Y')
    context['event_scheduler_date'] = datetime.now().strftime('%m/%d/%Y')
    context.update(extra_context or {})
    return context
Example #17
0
def employer_profile_preview(request, slug, extra_context=None):
    try:
        employer = Employer.objects.get(slug=slug)
    except Employer.DoesNotExist:
        raise Http404("Employer with slug %s does not exist" % slug)
    if is_student(request.user):
        return HttpResponseRedirect("%s?id=%s" % (reverse("employers"), employer.id))
    elif is_recruiter(request.user):
        context = {"employer": employer}
        context.update(get_employer_upcoming_events_context(employer, request.user))
        context.update(extra_context or {})
        return context
Example #18
0
def employer_profile_preview(request, slug, extra_context=None):
    try:
        employer = Employer.objects.get(slug=slug)
    except Employer.DoesNotExist:
        raise Http404("Employer with slug %s does not exist" % slug)
    if is_student(request.user):
        return HttpResponseRedirect("%s?id=%s" % (reverse("employers"), employer.id))
    elif is_recruiter(request.user):
        context = {'employer':employer}
        context.update(get_employer_upcoming_events_context(employer, request.user))
        context.update(extra_context or {})
        return context
Example #19
0
def tutorial(request, slug, extra_context=None):
    tutorial = get_object_or_404(Tutorial, slug=slug)
    context = {
        'tutorial': tutorial,
        'TEMPLATE': 'tutorials/%s.html' % tutorial.slug.replace("-", "_")
    }
    if is_recruiter(request.user):
        context[
            'other_recruiters'] = request.user.recruiter.employer.recruiter_set.exclude(
                id=request.user.recruiter.id)

    context.update(extra_context or {})
    return context
Example #20
0
def check_employer_campus_org_slug_uniqueness(request):
    if not request.GET.has_key("slug"):
        raise Http400("Request GET is missing the slug.")
    data = False
    campusorg = None
    employer = None
    if is_campus_org(request.user):
        campusorg = request.user.campusorg
    elif is_recruiter(request.user):
        employer = request.user.recruiter.employer
    if not employer_campus_org_slug_exists(request.GET["slug"], campusorg=campusorg, employer=employer):
        data = True
    return HttpResponse(simplejson.dumps(data), mimetype="application/json")
Example #21
0
def events_check_short_slug_uniqueness(request):
    if not request.GET.has_key("short_slug"):
        raise Http400("Request GET is missing the short_slug.")
    data = {'used': False}
    if is_campus_org(request.user):
        if Event.objects.filter(short_slug=request.GET['short_slug'],
                                owner=request.user).exists():
            data['used'] = True
    elif is_recruiter(request.user):
        if Event.objects.filter(short_slug=request.GET['short_slug'],
                                owner__recruiter__employer=request.user.
                                recruiter.employer).exists():
            data['used'] = True
    return HttpResponse(simplejson.dumps(data), mimetype="application/json")
Example #22
0
def home(request, extra_context=None):
    context = {}
    page_messages = { 'profile-saved': messages.profile_saved }
    msg = request.GET.get('msg', None)
    if msg:
        context.update(msg = page_messages.get(msg))
    if request.user.is_staff:
        return HttpResponseRedirect(reverse("login"))

    if request.user.is_authenticated():
        context['recent_events'] = get_recent_events(request.user);
        if is_student(request.user):
            if not request.user.student.profile_created:
                return redirect('student_profile')
            subscriptions = [employer.id for employer in request.user.student.subscriptions.all()]
            event_sqs = get_upcoming_events_sqs(request.user).filter(SQ(attending_employers__in=subscriptions) | SQ(invitees=request.user.id))
            context.update(get_categorized_events_context(len(event_sqs)>0, event_sqs, request.user))
            context['has_subscriptions'] = len(subscriptions) > 0
            context['TEMPLATE'] = 'student_home.html'
        else:
            context.update(get_upcoming_events_context(request.user))
            if is_recruiter(request.user):
                context.update({
                    'search_form': StudentSearchForm(),
                    'notices': Notice.objects.notices_for(request.user),
                    'unseen_notice_num': Notice.objects.unseen_count_for(request.user),
                    'subscribers': Student.objects.filter(subscriptions__in=[request.user.recruiter.employer]).count()
                });
                print context
                context['TEMPLATE'] = 'employer_home.html'
            elif is_campus_org(request.user):
                context.update({
                    'notices': Notice.objects.notices_for(request.user),
                    'unseen_notice_num': Notice.objects.unseen_count_for(request.user),
                });
                context['TEMPLATE'] = 'campus_org_home.html'
        context.update(extra_context or {})
        return context
    request.session.set_test_cookie()
    context.update({
        'login_form': AuthenticationForm,
        'action': request.REQUEST.get('action', ''),
        'TEMPLATE': 'anonymous_home.html'
    })
    event_kwargs = {}
    event_kwargs['end_datetime__gt'] = datetime.now()
    events = Event.objects.filter(**event_kwargs).order_by("end_datetime")
    context['events'] = list(events)[:3]
    context.update(extra_context or {})
    return context
Example #23
0
def check_employer_campus_org_slug_uniqueness(request):
    if not request.GET.has_key("slug"):
        raise Http400("Request GET is missing the slug.")
    data = False
    campusorg = None
    employer = None
    if is_campus_org(request.user):
        campusorg = request.user.campusorg
    elif is_recruiter(request.user):
        employer = request.user.recruiter.employer
    if not employer_campus_org_slug_exists(
            request.GET["slug"], campusorg=campusorg, employer=employer):
        data = True
    return HttpResponse(simplejson.dumps(data), mimetype="application/json")
Example #24
0
def event_edit(request, id=None, extra_context=None):
    try:
        event = Event.objects.get(pk=id)
    except Event.DoesNotExist:
        raise Http404("Event with id '%s' does not exist." % id)
    
    context = {'event': event}
    if not admin_of_event(event, request.user):
        raise Http403('You are not allowed to edit this event.')  
    if is_recruiter(event.owner):
        form_class = EventForm
    elif is_campus_org(event.owner):
        context['max_industries'] = s.EP_MAX_INDUSTRIES
        context['attending_employers'] = event.attending_employers
        form_class = CampusOrgEventForm
    if request.method == 'POST':
        form = form_class(request.POST, instance=event)
        if form.is_valid():
            event = form.save(commit=False)
            event.edits.add(Edit.objects.create(user=request.user))
            for employer in event.attending_employers.all():
                event.previously_attending_employers.add(employer)
            event.save()
            form.save_m2m()
            # Update index
            event.save()
            notify_about_event(event, "new_event", [e for e in list(event.attending_employers.all()) if e not in list(event.previously_attending_employers.all())])
            return HttpResponseRedirect(reverse('event_page', kwargs={'id':event.id, 'slug':event.slug}))
    else:
        form = form_class(instance=event)
    context['edit'] = True
    context['hours'] = map(lambda x,y: str(x) + y, [12] + range(1,13) + range(1,12), ['am']*12 + ['pm']*12)
    context['form'] = form
    context['today'] = datetime.now().strftime('%m/%d/%Y')
    if event.type.name == "Hard Deadline":
        context['event_scheduler_date'] = event.end_datetime.strftime('%m/%d/%Y')
    elif event.type.name == "Rolling Deadline":
        context['event_scheduler_date'] = datetime.now().strftime('%m/%d/%Y')
    else:
        context['event_scheduler_date'] =  event.start_datetime.strftime('%m/%d/%Y')
    context.update(extra_context or {})
    return context
Example #25
0
def event_rsvp(request, event_id):
    try:
        event = Event.objects.get(pk=event_id)
    except:
        raise Http404("Event with id '%s' does not exist." % event_id)
    else:
        # if method is GET then get a list of RSVPed students
        if request.method == 'GET' and is_campus_org(
                request.user) or is_recruiter(request.user):
            data = map(
                lambda n: {
                    'id': n.student.id,
                    'email': n.student.user.email
                }, event.rsvp_set.all())
            return HttpResponse(simplejson.dumps(data),
                                mimetype="application/json")
        # if POST then record student's RSVP
        elif request.method == 'POST' and is_student(request.user):
            isAttending = request.POST.get('attending', 'true')
            isAttending = True if isAttending == 'true' else False
            rsvp, created = RSVP.objects.get_or_create(
                student=request.user.student, event=event)
            rsvp.attending = isAttending
            rsvp.save()
            if isAttending:
                DroppedResume.objects.get_or_create(
                    event=event, student=request.user.student)
            if request.is_ajax():
                return HttpResponse()
            else:
                return redirect(
                    reverse('event_page',
                            kwargs={
                                'id': id,
                                'slug': event.slug
                            }))
        else:
            raise Http403("You do not have access to this view.")
Example #26
0
def caution(request):
    cautions = []
    if is_recruiter(request.user) and EmployerSubscription.objects.filter(
            employer=request.user.recruiter.employer).exists():
        employer_subscription = request.user.recruiter.employer.employersubscription
        subscription_path = reverse("subscriptions")
        if employer_subscription.in_grace_period():
            action_wording = "Renew now"
            if employer_subscription.subscription.uid == s.EVENT_SUBSCRIPTION_UID:
                action_wording = "Upgrade now"
            if request.get_full_path() != subscription_path:
                cautions.append(
                    "Your {2} has expired - you have {0} of access left. <a href='{1}'>{3}</a>."
                    .format(employer_subscription.time_left(),
                            subscription_path,
                            employer_subscription.subscription,
                            action_wording))
            else:
                cautions.append(
                    "Your {1} has expired - you have {0} of access left. {2}.".
                    format(employer_subscription.time_left(),
                           employer_subscription.subscription, action_wording))
    return {'cautions': cautions}
Example #27
0
def events(request, category, extra_context=None):
    context = {'category': category}
    if category == "past":
        context['past'] = True
    if category == "archived":
        context['archived'] = True
    # We do a special thing for upcoming events to display them as "Today", "Tomorrow", "This week"
    if category == "upcoming":
        context.update(event_filtering_helper(category, request))
    else:
        events_exist, events = event_filtering_helper(category, request)
        context['events_exist'] = events_exist
        context['events'] = events
    if request.is_ajax():
        template = loader.get_template("event_filtering_results.html")
        response = HttpResponse(
            template.render(RequestContext(request, context)))
        # Need the no-store header because of chrome history api bug
        # see http://stackoverflow.com/questions/8240710/chrome-history-api-problems
        response['Cache-Control'] = "no-store"
        return response
    else:
        if request.GET.has_key("query"):
            context['initial_state'] = simplejson.dumps(request.GET)
            context['event_filtering_form'] = EventFilteringForm(request.GET)
        else:
            context['event_filtering_form'] = EventFilteringForm()
        if is_campus_org(request.user) or is_recruiter(request.user):
            template = "events_employer_campus_org.html"
        elif is_student(request.user):
            if not request.user.student.profile_created:
                return redirect('student_profile')
            template = "events_student.html"
    return render_to_response(template,
                              context,
                              context_instance=RequestContext(request))
Example #28
0
def warnings(request):
    warnings = []
    if (
        is_recruiter(request.user)
        and EmployerSubscription.objects.filter(employer=request.user.recruiter.employer).exists()
    ):
        employer_subscription = request.user.recruiter.employer.employersubscription
        subscription_path = reverse("subscriptions")
        if employer_subscription.expired():
            if request.get_full_path() != subscription_path:
                if employer_subscription.subscription.uid == s.EVENT_SUBSCRIPTION_UID:
                    warnings.append(
                        "Your {0} has expired. Please host another campus event or <a href='{1}'>upgrade now</a> to regain access.".format(
                            employer_subscription.subscription, subscription_path
                        )
                    )
                else:
                    warnings.append(
                        "Your {0} has expired. Please <a href='{1}'>renew it</a> to regain access.".format(
                            employer_subscription.subscription, subscription_path
                        )
                    )
            else:
                if employer_subscription.subscription.uid == s.EVENT_SUBSCRIPTION_UID:
                    warnings.append(
                        "Your {0} has expired. Please host another campus event or upgrade now to regain access.".format(
                            employer_subscription.subscription
                        )
                    )
                else:
                    warnings.append(
                        "Your {0} has expired. Please renew it to regain access.".format(
                            employer_subscription.subscription
                        )
                    )
    return {"warnings": warnings}
Example #29
0
from core.decorators import render_to
from core.file_utils import find_first_file
from core.management.commands.zip_resumes import zip_resumes
from core.models import Edit
from core.view_helpers import english_join
from employer.decorators import is_recruiter
from employer.models import Recruiter
from events.forms import EventForm, CampusOrgEventForm, EventExportForm, EventFilteringForm, EventUploadRecruitersForm
from events.models import Attendee, Event, Invitee, RSVP, DroppedResume, notify_about_event
from events.view_helpers import event_map, event_filtering_helper, get_event_schedule, get_attendees, get_invitees, get_rsvps, get_no_rsvps, get_dropped_resumes, export_event_list_csv, export_event_list_text
from notification import models as notification
from student.decorators import is_student
from student.models import Student


@user_passes_test(lambda x: is_recruiter(x) or is_campus_org(x))
def download_event_participant_resumes(request, event_id, extra_context=None):
    event = Event.objects.get(id=event_id)
    event_participant_resumes_directory_name = "%s (%d) All Participants" % (event.name, event.id)
    event_resumes_dir = "%sevent_resumes/" % (s.ZIPPED_RESUMES_DIRECTORY)
    if not os.path.exists(event_resumes_dir):
        os.makedirs(event_resumes_dir)
    file_path = find_first_file(event_resumes_dir, "%s.*.zip" % re.escape(event_participant_resumes_directory_name))
    if file_path:
        mimetype = "application/zip"
        response = HttpResponse(file(file_path, "rb").read(), mimetype=mimetype)
        filename = file_path.split("/")[-1]
        response["Content-Disposition"] = 'attachment; filename="%s.zip"' % filename
        return response
    else:
        zip_resumes()
Example #30
0
def event_page(request, id, slug, extra_context=None):
    if is_student(request.user) and not request.user.student.profile_created:
        return redirect('student_profile')
    try:
        event = Event.objects.get(pk=id)
    except:
        raise Http404("Event with id '%s' does not exist." % id)
    if not event.is_public:
        if not request.user.is_authenticated():
            raise Http403("This event is private. You do not have permission to view it.")
        elif is_campus_org(request.user):
            if request.user != event.owner:
                raise Http403("This event is private. You do not have permission to view it.")
        elif is_recruiter(request.user):
            if request.user != event.owner and request.user.recruiter.employer not in event.attending_employers.all():
                raise Http403("This event is private. You do not have permission to view it.")
        elif is_student(request.user):
            try:
                Invitee.objects.get(event=event, student=request.user.student)
            except:
                raise Http403("This event is private. You do not have permission to view it.")

    current_site = Site.objects.get(id=s.SITE_ID)

    page_url = 'http://' + current_site.domain + event.get_absolute_url()
    #google_description is the description + stuff to link back to umeqo
    google_description = event.description + '\n\nRSVP and more at %s' % page_url
    
    context = {
        'page_url': page_url,
        'DOMAIN': current_site.domain,
        'current_site':"http://" + current_site.domain,
        'google_description': google_description
    }
        
    if len(event.audience.all()) > 0:
        context['audience'] = event.audience.all()
    
    if is_campus_org(event.owner):
        context['campus_org_event'] = True
        context['attending_employers'] = event.attending_employers
        if is_campus_org(request.user):
            context['can_edit'] = (event.owner == request.user)
            context['show_admin'] = (event.owner == request.user)
            context['recruiters_with_access'] = map(lambda x: {'name':"%s %s" % (x.first_name, x.last_name), 'email': x.email}, User.objects.filter(recruiter__employer__in=event.attending_employers.all()).order_by("first_name"))
        elif is_recruiter(request.user):
            context['show_admin'] = request.user.recruiter.employer in event.attending_employers.all()
    elif is_recruiter(event.owner):
        if is_recruiter(request.user):
            context['can_edit'] = request.user.recruiter in event.owner.recruiter.employer.recruiter_set.all()
            context['show_admin'] = request.user.recruiter in event.owner.recruiter.employer.recruiter_set.all()
    
    if context.has_key('show_admin'):
        attendees = get_attendees(event)
        rsvps =  get_rsvps(event)
        context['invitees'] = get_invitees(event)
        
        if event.is_drop:
            dropped_resumes = get_dropped_resumes(event)
        else:
            dropped_resumes = []

        if not event.is_public:
            no_rsvps = get_no_rsvps(event)
        else:
            no_rsvps = []
            
        context.update({
        'rsvps':rsvps,
        'no_rsvps': no_rsvps,
        'dropped_resumes': dropped_resumes,
        'attendees': attendees
        });
    
    # Increase the view count if we're not admin, a campus org or a recruiter (aka for now just student & anonymous)
    if not is_campus_org(request.user) and not is_recruiter(request.user) and not request.user.is_staff:
        event.view_count += 1
        event.save()
    
    if is_student(request.user):
        responded, attending, dropped_resume, attended, event = event_map(event, request.user)
        context['responded'] = responded
        context['attending'] = attending
        context['dropped_resume'] = dropped_resume
        context['attended'] = attended
    else:
        context['email_delivery_type'] = core_enums.EMAIL
    context['event'] = event
    context.update(extra_context or {})
    return context
Example #31
0
            )

            send_email(subject, body, recipients)

            data = {"name": new_employer.name, "id": new_employer.id}
        else:
            data = {"errors": form.errors}
        return HttpResponse(simplejson.dumps(data), mimetype="application/json")
    else:
        form = form_class()
    context = {"form": form}
    context.update(extra_context or {})
    return context


@user_passes_test(lambda x: is_student(x) or is_recruiter(x))
@render_to("employer_profile_preview.html")
def employer_profile_preview(request, slug, extra_context=None):
    try:
        employer = Employer.objects.get(slug=slug)
    except Employer.DoesNotExist:
        raise Http404("Employer with slug %s does not exist" % slug)
    if is_student(request.user):
        return HttpResponseRedirect("%s?id=%s" % (reverse("employers"), employer.id))
    elif is_recruiter(request.user):
        context = {"employer": employer}
        context.update(get_employer_upcoming_events_context(employer, request.user))
        context.update(extra_context or {})
        return context

Example #32
0
def get_upcoming_events_sqs(user):
    events = get_user_events_sqs(user).filter(end_datetime__gte=datetime.now())
    # TODO - figure out why this is here
    if is_campus_org(user) or is_recruiter(user):
        events = events.filter(archived=False)
    return events
Example #33
0
def get_past_events_sqs(user):
    events = get_user_events_sqs(user).filter(end_datetime__lt=datetime.now()).order_by("-end_datetime")
    if is_recruiter(user) or is_campus_org(user):
        events = events.filter(archived=False)
    return events
Example #34
0
def get_cancelled_events_sqs(user):
    events = get_user_events_sqs(user).filter(cancelled=True).order_by("-end_datetime")
    if is_recruiter(user) or is_campus_org(user):
        events = events.filter(archived=False)
    return events
Example #35
0
def event_upload_recruiters_list(request, form_class = EventUploadRecruitersForm, extra_context=None):
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        data = {}
        if form.is_valid():
            event_id = form.cleaned_data.get('event_id', '')

            try:
                event = Event.objects.get(id=event_id)
            except Event.DoesNotExist:
                raise Http404("The event with event id %s does not exist" % event_id)

            if request.user != event.owner:
                raise Http403("You must be the event owner in order to perform this action.")

            open_csv_file = csv.DictReader(request.FILES['csv_file'])

            for i, fieldname in enumerate(open_csv_file.fieldnames):
                open_csv_file.fieldnames[i] = fieldname.lower()

            recipients = [mail_tuple[1] for mail_tuple in s.MANAGERS]
            context = Context({})
            context.update(get_basic_email_context())
             
            event.attending_employers.clear()

            def send_event_company_representative_access_instructions():
                context['event'] = event

                text_body = render_to_string('recruiter_event_participant_access_instructions.txt', context)
                html_body = render_to_string('recruiter_event_participant_access_instructions.html', context)
            
                subject = ''.join(render_to_string('email_subject.txt', {
                    'message': "%s Student Browsing Instructions" % event.name
                }, context).splitlines())
                            
                send_email(subject, text_body, recipients, html_body)

            for row in open_csv_file:
                email = row.get('email', '')
                user = None
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    password = User.objects.make_random_password()
                    email = row['email'].lower()
                    user = User.objects.create(first_name = row['first name'],
                                               last_name  = row['last name'],
                                               email      = email,
                                               username   = email,
                        )
                    user.set_password(password)
                    user.save()
                    user.userattributes.is_verified = True
                    user.userattributes.save()
                    employer, created = Employer.objects.get_or_create(name=row['employer'])
                    if created:
                        recipients = [mail_tuple[1] for mail_tuple in s.MANAGERS]
                        context = Context({'first_name'   : request.user.first_name,
                                           'last_name'    : request.user.last_name,
                                           'email'        : request.user.email,
                                           'new_employer' : employer})
                        context.update(get_basic_email_context())
                         
                        body = render_to_string('employer_new_email_body.txt', context)
                                                
                        subject = ''.join(render_to_string('email_admin_subject.txt', {
                            'message': "New Employer: %s" % employer 
                        }, context).splitlines())
                                        
                        send_email(subject, body, recipients)
                    Recruiter.objects.create(employer=employer, user=user)
                    event.attending_employers.add(employer)

                    recipients = [user.email]
                    context.update({
                        "first_name": user.first_name,
                        "email": user.email,
                        "username": user.email,
                        "password": password,
                        "has_account": False,
                    })

                    send_event_company_representative_access_instructions()

                else:
                    if is_recruiter(user):
                        if not user.recruiter.employer in event.attending_employers.all():
                            employer = user.recruiter.employer
                            event.attending_employers.add(employer)

                            recipients = [user.email]
                            context.update({
                                "first_name": user.first_name,
                                "email": user.email,
                                "has_account": True,
                            })

                            send_event_company_representative_access_instructions()
                    else:
                        context.update({
                            "first_name": row.get("first name", ""),
                            "last_name": row.get("last name", ""),
                            "email": row.get("email", ""),
                            "supposed_employer": row.get("employer","")
                        })    

                        body = render_to_string('attending_recruiter_problem.txt', context)
                        
                        subject = ''.join(render_to_string('email_admin_subject.txt', {
                            'message': "%s has a problem with a recruiter" % event.name
                        }, context).splitlines())
                                    
                        send_email(subject, body, recipients)
        else:
            data['errors'] = form.errors
        return HttpResponse(simplejson.dumps(data), mimetype="application/json")
    else:
        form = form_class(initial={'event_id':request.GET['event_id']});
    context = {'form': form, 'TEMPLATE':'event_upload_recruiters_list.html'}
    context.update(extra_context or {}) 
    return context
Example #36
0
def admin_of_event(event, user):
    if is_recruiter(event.owner):
        return is_recruiter(user) and user.recruiter.employer == event.owner.recruiter.employer
    elif is_campus_org(event.owner):
        return is_campus_org(user) and user.campusorg == event.owner.campusorg
    return False
Example #37
0
            }, context).splitlines())
                            
            send_email(subject, body, recipients)
            
            data = {"name": new_employer.name, "id": new_employer.id}
        else:
            data = {'errors': form.errors }
        return HttpResponse(simplejson.dumps(data), mimetype="application/json")
    else:
        form = form_class()
    context = {'form': form }
    context.update(extra_context or {}) 
    return context


@user_passes_test(lambda x: is_student(x) or is_recruiter(x))
@render_to("employer_profile_preview.html")
def employer_profile_preview(request, slug, extra_context=None):
    try:
        employer = Employer.objects.get(slug=slug)
    except Employer.DoesNotExist:
        raise Http404("Employer with slug %s does not exist" % slug)
    if is_student(request.user):
        return HttpResponseRedirect("%s?id=%s" % (reverse("employers"), employer.id))
    elif is_recruiter(request.user):
        context = {'employer':employer}
        context.update(get_employer_upcoming_events_context(employer, request.user))
        context.update(extra_context or {})
        return context

Example #38
0
from core.decorators import render_to
from core.file_utils import find_first_file
from core.management.commands.zip_resumes import zip_resumes
from core.models import Edit
from core.view_helpers import english_join
from employer.decorators import is_recruiter
from employer.models import Recruiter
from events.forms import EventForm, CampusOrgEventForm, EventExportForm, EventFilteringForm, EventUploadRecruitersForm
from events.models import Attendee, Event, Invitee, RSVP, DroppedResume, notify_about_event
from events.view_helpers import event_map, event_filtering_helper, get_event_schedule, get_attendees, get_invitees, get_rsvps, get_no_rsvps, get_dropped_resumes, export_event_list_csv, export_event_list_text
from notification import models as notification
from student.decorators import is_student
from student.models import Student


@user_passes_test(lambda x: is_recruiter(x) or is_campus_org(x))
def download_event_participant_resumes(request, event_id, extra_context=None):
    event = Event.objects.get(id=event_id)
    event_participant_resumes_directory_name = "%s (%d) All Participants" % (
        event.name, event.id)
    event_resumes_dir = "%sevent_resumes/" % (s.ZIPPED_RESUMES_DIRECTORY)
    if not os.path.exists(event_resumes_dir):
        os.makedirs(event_resumes_dir)
    file_path = find_first_file(
        event_resumes_dir,
        "%s.*.zip" % re.escape(event_participant_resumes_directory_name))
    if file_path:
        mimetype = "application/zip"
        response = HttpResponse(file(file_path, "rb").read(),
                                mimetype=mimetype)
        filename = file_path.split("/")[-1]
Example #39
0
def event_page(request, id, slug, extra_context=None):
    if is_student(request.user) and not request.user.student.profile_created:
        return redirect('student_profile')
    try:
        event = Event.objects.get(pk=id)
    except:
        raise Http404("Event with id '%s' does not exist." % id)
    if not event.is_public:
        if not request.user.is_authenticated():
            raise Http403(
                "This event is private. You do not have permission to view it."
            )
        elif is_campus_org(request.user):
            if request.user != event.owner:
                raise Http403(
                    "This event is private. You do not have permission to view it."
                )
        elif is_recruiter(request.user):
            if request.user != event.owner and request.user.recruiter.employer not in event.attending_employers.all(
            ):
                raise Http403(
                    "This event is private. You do not have permission to view it."
                )
        elif is_student(request.user):
            try:
                Invitee.objects.get(event=event, student=request.user.student)
            except:
                raise Http403(
                    "This event is private. You do not have permission to view it."
                )

    current_site = Site.objects.get(id=s.SITE_ID)

    page_url = 'http://' + current_site.domain + event.get_absolute_url()
    #google_description is the description + stuff to link back to umeqo
    google_description = event.description + '\n\nRSVP and more at %s' % page_url

    context = {
        'page_url': page_url,
        'DOMAIN': current_site.domain,
        'current_site': "http://" + current_site.domain,
        'google_description': google_description
    }

    if len(event.audience.all()) > 0:
        context['audience'] = event.audience.all()

    if is_campus_org(event.owner):
        context['campus_org_event'] = True
        context['attending_employers'] = event.attending_employers
        if is_campus_org(request.user):
            context['can_edit'] = (event.owner == request.user)
            context['show_admin'] = (event.owner == request.user)
            context['recruiters_with_access'] = map(
                lambda x: {
                    'name': "%s %s" % (x.first_name, x.last_name),
                    'email': x.email
                },
                User.objects.filter(
                    recruiter__employer__in=event.attending_employers.all()).
                order_by("first_name"))
        elif is_recruiter(request.user):
            context[
                'show_admin'] = request.user.recruiter.employer in event.attending_employers.all(
                )
    elif is_recruiter(event.owner):
        if is_recruiter(request.user):
            context[
                'can_edit'] = request.user.recruiter in event.owner.recruiter.employer.recruiter_set.all(
                )
            context[
                'show_admin'] = request.user.recruiter in event.owner.recruiter.employer.recruiter_set.all(
                )

    if context.has_key('show_admin'):
        attendees = get_attendees(event)
        rsvps = get_rsvps(event)
        context['invitees'] = get_invitees(event)

        if event.is_drop:
            dropped_resumes = get_dropped_resumes(event)
        else:
            dropped_resumes = []

        if not event.is_public:
            no_rsvps = get_no_rsvps(event)
        else:
            no_rsvps = []

        context.update({
            'rsvps': rsvps,
            'no_rsvps': no_rsvps,
            'dropped_resumes': dropped_resumes,
            'attendees': attendees
        })

    # Increase the view count if we're not admin, a campus org or a recruiter (aka for now just student & anonymous)
    if not is_campus_org(request.user) and not is_recruiter(
            request.user) and not request.user.is_staff:
        event.view_count += 1
        event.save()

    if is_student(request.user):
        responded, attending, dropped_resume, attended, event = event_map(
            event, request.user)
        context['responded'] = responded
        context['attending'] = attending
        context['dropped_resume'] = dropped_resume
        context['attended'] = attended
    else:
        context['email_delivery_type'] = core_enums.EMAIL
    context['event'] = event
    context.update(extra_context or {})
    return context
Example #40
0
def event_upload_recruiters_list(request,
                                 form_class=EventUploadRecruitersForm,
                                 extra_context=None):
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        data = {}
        if form.is_valid():
            event_id = form.cleaned_data.get('event_id', '')

            try:
                event = Event.objects.get(id=event_id)
            except Event.DoesNotExist:
                raise Http404("The event with event id %s does not exist" %
                              event_id)

            if request.user != event.owner:
                raise Http403(
                    "You must be the event owner in order to perform this action."
                )

            open_csv_file = csv.DictReader(request.FILES['csv_file'])

            for i, fieldname in enumerate(open_csv_file.fieldnames):
                open_csv_file.fieldnames[i] = fieldname.lower()

            recipients = [mail_tuple[1] for mail_tuple in s.MANAGERS]
            context = Context({})
            context.update(get_basic_email_context())

            event.attending_employers.clear()

            def send_event_company_representative_access_instructions():
                context['event'] = event

                text_body = render_to_string(
                    'recruiter_event_participant_access_instructions.txt',
                    context)
                html_body = render_to_string(
                    'recruiter_event_participant_access_instructions.html',
                    context)

                subject = ''.join(
                    render_to_string('email_subject.txt', {
                        'message':
                        "%s Student Browsing Instructions" % event.name
                    }, context).splitlines())

                send_email(subject, text_body, recipients, html_body)

            for row in open_csv_file:
                email = row.get('email', '')
                user = None
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    password = User.objects.make_random_password()
                    email = row['email'].lower()
                    user = User.objects.create(
                        first_name=row['first name'],
                        last_name=row['last name'],
                        email=email,
                        username=email,
                    )
                    user.set_password(password)
                    user.save()
                    user.userattributes.is_verified = True
                    user.userattributes.save()
                    employer, created = Employer.objects.get_or_create(
                        name=row['employer'])
                    if created:
                        recipients = [
                            mail_tuple[1] for mail_tuple in s.MANAGERS
                        ]
                        context = Context({
                            'first_name': request.user.first_name,
                            'last_name': request.user.last_name,
                            'email': request.user.email,
                            'new_employer': employer
                        })
                        context.update(get_basic_email_context())

                        body = render_to_string('employer_new_email_body.txt',
                                                context)

                        subject = ''.join(
                            render_to_string(
                                'email_admin_subject.txt', {
                                    'message': "New Employer: %s" % employer
                                }, context).splitlines())

                        send_email(subject, body, recipients)
                    Recruiter.objects.create(employer=employer, user=user)
                    event.attending_employers.add(employer)

                    recipients = [user.email]
                    context.update({
                        "first_name": user.first_name,
                        "email": user.email,
                        "username": user.email,
                        "password": password,
                        "has_account": False,
                    })

                    send_event_company_representative_access_instructions()

                else:
                    if is_recruiter(user):
                        if not user.recruiter.employer in event.attending_employers.all(
                        ):
                            employer = user.recruiter.employer
                            event.attending_employers.add(employer)

                            recipients = [user.email]
                            context.update({
                                "first_name": user.first_name,
                                "email": user.email,
                                "has_account": True,
                            })

                            send_event_company_representative_access_instructions(
                            )
                    else:
                        context.update({
                            "first_name":
                            row.get("first name", ""),
                            "last_name":
                            row.get("last name", ""),
                            "email":
                            row.get("email", ""),
                            "supposed_employer":
                            row.get("employer", "")
                        })

                        body = render_to_string(
                            'attending_recruiter_problem.txt', context)

                        subject = ''.join(
                            render_to_string(
                                'email_admin_subject.txt', {
                                    'message':
                                    "%s has a problem with a recruiter" %
                                    event.name
                                }, context).splitlines())

                        send_email(subject, body, recipients)
        else:
            data['errors'] = form.errors
        return HttpResponse(simplejson.dumps(data),
                            mimetype="application/json")
    else:
        form = form_class(initial={'event_id': request.GET['event_id']})
    context = {'form': form, 'TEMPLATE': 'event_upload_recruiters_list.html'}
    context.update(extra_context or {})
    return context
Example #41
0
def home(request, extra_context=None):
    context = {}
    page_messages = {'profile-saved': messages.profile_saved}
    msg = request.GET.get('msg', None)
    if msg:
        context.update(msg=page_messages.get(msg))
    if request.user.is_staff:
        return HttpResponseRedirect(reverse("login"))

    if request.user.is_authenticated():
        context['recent_events'] = get_recent_events(request.user)
        if is_student(request.user):
            if not request.user.student.profile_created:
                return redirect('student_profile')
            subscriptions = [
                employer.id
                for employer in request.user.student.subscriptions.all()
            ]
            event_sqs = get_upcoming_events_sqs(request.user).filter(
                SQ(attending_employers__in=subscriptions)
                | SQ(invitees=request.user.id))
            context.update(
                get_categorized_events_context(
                    len(event_sqs) > 0, event_sqs, request.user))
            context['has_subscriptions'] = len(subscriptions) > 0
            context['TEMPLATE'] = 'student_home.html'
        else:
            context.update(get_upcoming_events_context(request.user))
            if is_recruiter(request.user):
                context.update({
                    'search_form':
                    StudentSearchForm(),
                    'notices':
                    Notice.objects.notices_for(request.user),
                    'unseen_notice_num':
                    Notice.objects.unseen_count_for(request.user),
                    'subscribers':
                    Student.objects.filter(
                        subscriptions__in=[request.user.recruiter.employer
                                           ]).count()
                })
                print context
                context['TEMPLATE'] = 'employer_home.html'
            elif is_campus_org(request.user):
                context.update({
                    'notices':
                    Notice.objects.notices_for(request.user),
                    'unseen_notice_num':
                    Notice.objects.unseen_count_for(request.user),
                })
                context['TEMPLATE'] = 'campus_org_home.html'
        context.update(extra_context or {})
        return context
    request.session.set_test_cookie()
    context.update({
        'login_form': AuthenticationForm,
        'action': request.REQUEST.get('action', ''),
        'TEMPLATE': 'anonymous_home.html'
    })
    event_kwargs = {}
    event_kwargs['end_datetime__gt'] = datetime.now()
    events = Event.objects.filter(**event_kwargs).order_by("end_datetime")
    context['events'] = list(events)[:3]
    context.update(extra_context or {})
    return context