Beispiel #1
0
def get_more_details_after_social_auth(request):
    """Get more details after a social authentication, especially requested username.

    Reference: https://github.com/omab/django-social-auth/blob/master/example/app/views.py
    """
    logger = logging.getLogger("apps.accounts.views.get_more_details_after_social_auth")
    logger.debug("entry.")

    # -------------------------------------------------------------------------
    #   We have received some 3rd party authentication details, where the
    #   user is authenticated there. However, the username on that service
    #   may not be available on our service due to the use of vanity
    #   URLs and other 3rd party services.
    #
    #   For example, 'account' is a reserved word and a Facebook user with
    #   this username would need to be prompted to enter a new username.
    # -------------------------------------------------------------------------
    pipeline_data_name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline')
    pipeline_data = request.session.get(pipeline_data_name, None)
    pipeline_kwargs = pipeline_data["kwargs"]
    pipeline_details = pipeline_kwargs["details"]
    backend = pipeline_data["backend"]
    username = pipeline_details["username"]
    if is_username_available(username):
        logger.debug("username '%s' on backend '%s' is avilable here, so no need to prompt for more details." % (username, backend))
        request.session['saved_username'] = username
        return redirect('socialauth_complete', backend=backend)

    # -------------------------------------------------------------------------
    #   At this stage the username is not available.
    #   -   If this is a POST the user is submitting a new possible
    #       username.
    #   -   Else this is a GET, meaning we need to tell the user
    #       what's gone wrong.
    # -------------------------------------------------------------------------
    form = None
    show_error_message_on_new_form = False
    if request.method == 'POST':
        logger.debug("POST.")
        form = GetMoreDetailsAfterSocialAuthForm(request.POST)
        if form.is_valid():
            logger.debug("Form is valid.")
            username = form.cleaned_data['username'].lower()
            if not is_username_available(username):
                logger.debug("username is not available.")
                form.errors['username'] = ["The username \"%s\" is also not available, sorry! Please choose another username for use on Ohyoushould." % username]
            else:
                logger.debug("username is available.")
                request.session['saved_username'] = username
                return redirect('socialauth_complete', backend=backend)
    else:
        logger.debug("GET.")
        show_error_message_on_new_form = True

    data = {}
    # -------------------------------------------------------------------------
    #   Populate form for Account registration.
    # -------------------------------------------------------------------------
    if form is None:
        logger.debug("no previous form present.")
        form_initial = {"username": username}
        form = GetMoreDetailsAfterSocialAuthForm(initial = form_initial)
        if show_error_message_on_new_form:
            logger.debug("need to show error message on a new form.")
            form.errors['username'] = ["The username \"%s\" is not available, sorry! Please choose another username for use on Ohyoushould." % username]
    data['form'] = form
    # -------------------------------------------------------------------------

    # -------------------------------------------------------------------------
    #   Get and render form errors, if any.
    # -------------------------------------------------------------------------
    if form.errors:
        logger.debug("Form has some errors.")
        data["are_any_errors"] = True
        error_output = []
        for (field_name, errors) in form.errors.items():
            field_object = form.fields[field_name]
            if len(errors) == 1:
                error_output.append(r"- **%s**: %s" % (field_object.label, errors[0]))
            else:
                for error in errors:
                    error_output.append(r"- **%s**: %s" % (field_object.label, error))
        data["all_errors_description"] = markdown2.markdown('\n'.join(error_output),
                                                            extras=["cuddled-lists"])
    else:
        logger.debug("Form does not have any errors.")
        data["are_any_errors"] = False
    # -------------------------------------------------------------------------
    logger.debug("data:\n%s" % (pprint.pformat(data), ))
    return render_to_response('accounts/get_more_details_after_social_auth.html',
                              data,
                              RequestContext(request))
Beispiel #2
0
def register(request):
    logger = logging.getLogger("apps.accounts.views.register")
    logger.debug("entry.")

    form = None
    if request.method == 'POST':
        logger.debug("POST")
        form = RegisterForm(request.POST)
        if form.is_valid():
            # ----------------------------------------------------------------
            #   Form is valid so parse values from it.
            # ----------------------------------------------------------------
            logger.debug("POST is valid")
            username = form.cleaned_data['username'].lower()
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            password = form.cleaned_data['password']
            confirm_password = form.cleaned_data['confirm_password']
            email = form.cleaned_data['email']
            logger.debug("username: %s, email: %s" % (username, email))
            # ----------------------------------------------------------------

            # ----------------------------------------------------------------
            #   Password must be correctly entered twice.
            # ----------------------------------------------------------------
            if password != confirm_password:
                logger.debug("password incorrectly entered twice.")
                form.errors['password'] = ["You did not enter in your password twice exactly the same. Please enter and confirm your password again."]
                form.errors['confirm_password'] = ["You did not enter in your password twice exactly the same. Please enter and confirm your password again."]
            elif not is_username_available(username):
                logger.debug("username is not available.")
                form.errors['username'] = ["The username \"%s\" is not available. Please choose another username." % username]
            else:
                # ------------------------------------------------------------
                #   Create and login as new user.
                #
                #   Note the gotcha that after creating a user we must
                #   authenticate it before calling login(). See the
                #   'User authentication in Django' section of the manual ->
                #   login() for more details.
                # ------------------------------------------------------------
                user = User.objects.create_user(username = username, email = email, password = password)
                user.first_name = first_name
                user.last_name = last_name
                user.save()
                user = authenticate(username=username, password=password)
                login(request, user) # sets up session for us
                return HttpResponseRedirect(reverse('apps.profiles.views.read_profile_no_username'))
                # ------------------------------------------------------------
    data = {}
    # -------------------------------------------------------------------------
    #   Populate form for Account registration.
    # -------------------------------------------------------------------------
    if form is None:
        logger.debug("no previous form present.")
        form_initial = {"username": "",
                        "first_name": "",
                        "last_name": "",
                        "password": "",
                        "confirm_password": "",
                        "email": ""}
        form = RegisterForm(initial = form_initial)
    data['form'] = form
    # -------------------------------------------------------------------------

    # -------------------------------------------------------------------------
    #   Get and render form errors, if any.
    # -------------------------------------------------------------------------
    if form.errors:
        logger.debug("Form has some errors.")
        data["are_any_errors"] = True
        error_output = []
        for (field_name, errors) in form.errors.items():
            field_object = form.fields[field_name]
            if len(errors) == 1:
                error_output.append(r"- **%s**: %s" % (field_object.label, errors[0]))
            else:
                for error in errors:
                    error_output.append(r"- **%s**: %s" % (field_object.label, error))
        data["all_errors_description"] = markdown2.markdown('\n'.join(error_output),
                                                            extras=["cuddled-lists"])
    else:
        logger.debug("Form does not have any errors.")
        data["are_any_errors"] = False
    # -------------------------------------------------------------------------

    logger.debug("rendering response...")
    return render_to_response('accounts/register.html',
                              data,
                              context_instance = RequestContext(request))