예제 #1
0
 def context(self, request, **kwargs):
     querystring = "?%s" % request.META.get('QUERY_STRING')
     if request.POST and self.submit_btn_name() in request.POST:
         # If data is being posted to this specific block, give the form
         # the opportunity to render any errors.
         return {
             'login_action': querystring,
             'login_form': CustomAuthForm(data=request.POST),
             'login_submit_btn_name': self.submit_btn_name()
         }
     return {
         'login_action': querystring,
         'login_form': CustomAuthForm(),
         'login_submit_btn_name': self.submit_btn_name()
     }
예제 #2
0
파일: models.py 프로젝트: zeus911/MyJobs
    def handle_post(self, request):
        """
        Logs a user in if it was a request to log a user in and
        the login attempt was successful.

        """
        # Confirm that the requst is a post, and that this form is
        # the intended recipient of the posted data.
        if not request.POST or self.submit_btn_name() not in request.POST:
            return None

        form = CustomAuthForm(data=request.POST)
        if form.is_valid():
            # Log in the user and redirect based on the success_url rules.
            expire_login(request, form.get_user())

            response = HttpResponseRedirect(success_url(request))
            response.set_cookie('myguid', form.get_user().user_guid,
                                expires=365*24*60*60, domain='.my.jobs')
            return response
        return None
예제 #3
0
    def test_lockout_message(self):
        """
        User should get a message when locked out.

        """
        self.company.password_expiration = True
        self.company.save()

        (self.alice, _) = User.objects.create_user(**{
            'email': '*****@*****.**', 'password1': '5UuYquA@'})
        self.alice.failed_login_count = 99999
        self.alice.save()

        form = CustomAuthForm(None, {
            'username': '******',
            'password': '******',
            })
        self.assertFalse(form.is_valid())
        self.assertTrue(any(
            'locked' in m
            for m in form.errors['username']))
예제 #4
0
    def handle_post(self, request):
        """
        Logs a user in if it was a request to log a user in and
        the login attempt was successful.

        """
        # Confirm that the requst is a post, and that this form is
        # the intended recipient of the posted data.
        if not request.POST or self.submit_btn_name() not in request.POST:
            return None

        form = CustomAuthForm(data=request.POST)
        if form.is_valid():
            # Log in the user and redirect based on the success_url rules.
            expire_login(request, form.get_user())

            response = HttpResponseRedirect(success_url(request))
            response.set_cookie('myguid',
                                form.get_user().user_guid,
                                expires=365 * 24 * 60 * 60,
                                domain='.my.jobs')
            return response
        return None
예제 #5
0
def activate(request, activation_key):
    """
    Activates user and returns a boolean to activated. Activated is passed
    into the template to display an appropriate message if the activation
    passes or fails.

    Inputs:
    :activation_key: string representing an activation key for a user
    """
    logged_in = True
    if request.user.is_anonymous():
        logged_in = False
    activated = ActivationProfile.objects.activate_user(activation_key)

    loginform = 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")

    ctx = {
        'activated': activated,
        'logged_in': logged_in,
        'loginform': loginform,
        'name_form': name_form,
        'phone_form': phone_form,
        'address_form': address_form,
        'work_form': work_form,
        'education_form': education_form,
        'num_modules': len(settings.PROFILE_COMPLETION_MODULES)
    }
    return render_to_response('registration/activate.html',
                              ctx,
                              context_instance=RequestContext(request))
예제 #6
0
def sso_authorize(request):
    """
    Authorizes specific web sites to utilize an existing My.jobs account

    Required on HTTP GET:
    :auth_callback: GET parameter - Desired return url when authorization
        succeeds

    Required on HTTP POST:
    :auth_callback: POST parameter, copy of :auth_callback: GET parameter
    """
    # Common between GET and POST, callback is required.
    auth_callback = request.GET.get('auth_callback') or \
        request.POST.get('auth_callback')
    data = {'auth_callback': auth_callback}

    if auth_callback:
        auth_callback = unquote(auth_callback)
        auth_callback = urlparse.urlparse(auth_callback)
        if not auth_callback.netloc:
            # If the base url of the callback is not truthy, the url
            # must be malformed somehow
            raise Http404
    else:
        raise Http404

    if request.method == 'GET':
        # Initial view after being redirected from an external site
        data['auth_callback_short'] = auth_callback.netloc

        if not request.user.is_anonymous():
            # Process logged in users first; Certain criteria may cause the
            # user to be logged out.
            good_key = request.session.get('key')
            test_key = request.GET.get('key')
            if good_key:
                # The current user already has a key available.
                if test_key:
                    # The remote site has provided a key; the user has
                    # potentially already authorized this site.
                    if test_key == good_key:
                        if request.user.authorizedclient_set.filter(
                                site=auth_callback.netloc):
                            # The user has authorized this site; Reset the
                            # current session expiry, add the key to the
                            # callback url, and redirect to it.
                            request.session.set_expiry(None)

                            q = urlparse.parse_qs(auth_callback.query)
                            q.update({'key': good_key})
                            auth_callback = auth_callback._replace(
                                query=urlencode(q))
                            return redirect(urlparse.urlunparse(auth_callback))
                        else:
                            # The user at one time authorized this site but it
                            # was revoked (potential future functionality?).
                            # Ask for authorization again.
                            return render_to_response('mysignon/sso_auth.html',
                                                      data,
                                                      RequestContext(request))
                    else:
                        # The key provided does not match the user's key; Log
                        # the user out. It may be a different user's key.
                        logout(request)
                else:
                    # No key was provided; Proceed to authorization normally.
                    return render_to_response('mysignon/sso_auth.html', data,
                                              RequestContext(request))
            else:
                # The user has no key; Create one.
                request.session['key'] = AuthorizedClient.create_key(
                    request.user)
                if test_key:
                    # A key was provided, but the current user did not have one
                    # until now. Log out the user.
                    logout(request)
                else:
                    # No key was provided; Proceed to authorization.
                    return render_to_response('mysignon/sso_auth.html', data,
                                              RequestContext(request))

        # Only anonymous users can reach this point. This is not inside an else
        # block so that it can catch users who were logged out above.
        login_form = CustomAuthForm(auto_id=True)
        login_form.fields.pop('remember_me')
        data['login_form'] = login_form
        return render_to_response('mysignon/sso_auth.html', data,
                                  RequestContext(request))

    else:
        # Form was posted.
        action = request.POST.get('action')
        if action == 'login':
            login_form = CustomAuthForm(data=request.POST, auto_id=False)
            login_form.fields.pop('remember_me')
            if login_form.is_valid():
                user = authenticate(
                    username=login_form.cleaned_data['username'],
                    password=login_form.cleaned_data['password'])
                login(request, user)
                request.session.set_expiry(None)
                # User was logged in. Fall through to code common to
                # preauthenticated users
            else:
                if request.is_ajax():
                    return HttpResponse(
                        json.dumps({'errors': login_form.errors.items()}))
                else:
                    data['login_form'] = login_form
                    data['auth_callback_short'] = auth_callback.netloc

                    return render_to_response('mysignon/sso_auth.html', data,
                                              RequestContext(request))

        # Ensure that an AuthorizedClient instance exists for the current user
        # and the site that is requesting authorization.
        request.user.authorizedclient_set.get_or_create(
            site=auth_callback.netloc)

        # Ensure that the current user has a key.
        if not request.session.get('key'):
            request.session['key'] = AuthorizedClient.create_key(request.user)

        # Add the user's key to the callback url and redirect to it.
        q = urlparse.parse_qs(auth_callback.query)
        q.update({'key': request.session.get('key')})
        auth_callback = auth_callback._replace(query=urlencode(q))
        auth_callback = urlparse.urlunparse(auth_callback)
        if request.is_ajax():

            return HttpResponse(json.dumps({'url': auth_callback}))
        else:
            return redirect(auth_callback)
예제 #7
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))
예제 #8
0
파일: views.py 프로젝트: kepinq/MyJobs
def sso_authorize(request):
    """
    Authorizes specific web sites to utilize an existing My.jobs account

    Required on HTTP GET:
    :auth_callback: GET parameter - Desired return url when authorization
        succeeds

    Required on HTTP POST:
    :auth_callback: POST parameter, copy of :auth_callback: GET parameter
    """
    # Common between GET and POST, callback is required.
    auth_callback = request.GET.get('auth_callback') or \
        request.POST.get('auth_callback')
    data = {'auth_callback': auth_callback}

    if auth_callback:
        auth_callback = unquote(auth_callback)
        auth_callback = urlparse.urlparse(auth_callback)
        if not auth_callback.netloc:
            # If the base url of the callback is not truthy, the url
            # must be malformed somehow
            raise Http404("mysignon.views.sso_authorize: bad callback")
    else:
        raise Http404("mysignon.views.sso_authorize: no callback")

    if request.method == 'GET':
        # Initial view after being redirected from an external site
        data['auth_callback_short'] = auth_callback.netloc

        if not request.user.is_anonymous():
            # Process logged in users first; Certain criteria may cause the
            # user to be logged out.
            good_key = request.session.get('key')
            test_key = request.GET.get('key')
            if good_key:
                # The current user already has a key available.
                if test_key:
                    # The remote site has provided a key; the user has
                    # potentially already authorized this site.
                    if test_key == good_key:
                        if request.user.authorizedclient_set.filter(
                                site=auth_callback.netloc):
                            # The user has authorized this site; Reset the
                            # current session expiry, add the key to the
                            # callback url, and redirect to it.
                            request.session.set_expiry(None)

                            q = urlparse.parse_qs(auth_callback.query)
                            q.update({'key': good_key})
                            auth_callback = auth_callback._replace(
                                query=urlencode(q))
                            return redirect(urlparse.urlunparse(auth_callback))
                        else:
                            # The user at one time authorized this site but it
                            # was revoked (potential future functionality?).
                            # Ask for authorization again.
                            return render_to_response('mysignon/sso_auth.html',
                                                      data,
                                                      RequestContext(request))
                    else:
                        # The key provided does not match the user's key; Log
                        # the user out. It may be a different user's key.
                        logout(request)
                else:
                    # No key was provided; Proceed to authorization normally.
                    return render_to_response('mysignon/sso_auth.html',
                                              data,
                                              RequestContext(request))
            else:
                # The user has no key; Create one.
                request.session['key'] = AuthorizedClient.create_key(
                    request.user)
                if test_key:
                    # A key was provided, but the current user did not have one
                    # until now. Log out the user.
                    logout(request)
                else:
                    # No key was provided; Proceed to authorization.
                    return render_to_response('mysignon/sso_auth.html',
                                              data,
                                              RequestContext(request))

        # Only anonymous users can reach this point. This is not inside an else
        # block so that it can catch users who were logged out above.
        login_form = CustomAuthForm(auto_id=True)
        login_form.fields.pop('remember_me')
        data['login_form'] = login_form
        return render_to_response('mysignon/sso_auth.html',
                                  data,
                                  RequestContext(request))

    else:
        # Form was posted.
        action = request.POST.get('action')
        if action == 'login':
            login_form = CustomAuthForm(data=request.POST, auto_id=False)
            login_form.fields.pop('remember_me')
            if login_form.is_valid():
                user = authenticate(
                    username=login_form.cleaned_data['username'],
                    password=login_form.cleaned_data['password'])
                login(request, user)
                request.session.set_expiry(None)
                # User was logged in. Fall through to code common to
                # preauthenticated users
            else:
                if request.is_ajax():
                    return HttpResponse(json.dumps(
                        {'errors': login_form.errors.items()}))
                else:
                    data['login_form'] = login_form
                    data['auth_callback_short'] = auth_callback.netloc

                    return render_to_response('mysignon/sso_auth.html', data,
                                              RequestContext(request))

        # Ensure that an AuthorizedClient instance exists for the current user
        # and the site that is requesting authorization.
        request.user.authorizedclient_set.get_or_create(site=auth_callback.netloc)

        # Ensure that the current user has a key.
        if not request.session.get('key'):
            request.session['key'] = AuthorizedClient.create_key(request.user)

        # Add the user's key to the callback url and redirect to it.
        q = urlparse.parse_qs(auth_callback.query)
        q.update({'key': request.session.get('key')})
        auth_callback = auth_callback._replace(query=urlencode(q))
        auth_callback = urlparse.urlunparse(auth_callback)
        if request.is_ajax():

            return HttpResponse(json.dumps({'url': auth_callback}))
        else:
            return redirect(auth_callback)
예제 #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)
                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))