Exemple #1
0
def changeopenid_success(request, identity_url, openid_response):
    logging.error('never tested this worflow')
    openid_ = from_openid_response(openid_response)
    is_exist = True
    try:
        uassoc = UserAssociation.objects.get(openid_url__exact=identity_url)
    except:
        is_exist = False
        
    if not is_exist:
        try:
            uassoc = UserAssociation.objects.get(
                    user__username__exact=request.user.username
            )
            uassoc.openid_url = identity_url
            uassoc.save()
        except:
            uassoc = UserAssociation(user=request.user, 
                    openid_url=identity_url)
            uassoc.save()
    elif uassoc.user.username != request.user.username:
        return changeopenid_failure(request, 
                _('This OpenID is already associated with another account.'))

    request.session['openids'] = []
    request.session['openids'].append(openid_)

    msg = _("OpenID %s is now associated with your account." % identity_url) 
    redirect = "%s?msg=%s" % (
            reverse('user_account_settings'), 
            urlquote_plus(msg))
    return HttpResponseRedirect(redirect)
Exemple #2
0
def changeopenid_success(request, identity_url, openid_response):
    openid_ = from_openid_response(openid_response)
    is_exist = True
    try:
        uassoc = UserAssociation.objects.get(openid_url__exact=identity_url)
    except:
        is_exist = False

    if not is_exist:
        try:
            uassoc = UserAssociation.objects.get(user__username__exact=request.user.username)
            uassoc.openid_url = identity_url
            uassoc.save()
        except:
            uassoc = UserAssociation(user=request.user, openid_url=identity_url)
            uassoc.save()
    elif uassoc.user.username != request.user.username:
        return changeopenid_failure(request, _("This OpenID is already associated with another account."))

    request.session["openids"] = []
    request.session["openids"].append(openid_)

    msg = _("OpenID %s is now associated with your account." % identity_url)
    redirect = "%s?msg=%s" % (reverse("user_account_settings"), urlquote_plus(msg))
    return HttpResponseRedirect(redirect)
Exemple #3
0
def associate_success(
    request, identity_url, openid_response, redirect_field_name=REDIRECT_FIELD_NAME, send_email=True, **kwargs
):
    """ 
    function used when new openid association success. redirect the user
    """
    openid_ = from_openid_response(openid_response)
    openids = request.session.get("openids", [])
    openids.append(openid_)
    request.session["openids"] = openids
    uassoc = UserAssociation(openid_url=str(openid_), user_id=request.user.id)
    uassoc.save(send_email=send_email)

    redirect_to = request.GET.get(redirect_field_name, "")
    if not redirect_to or "//" in redirect_to or " " in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
    return HttpResponseRedirect(redirect_to)
Exemple #4
0
    def save(self, u):
        u.first_name = self.cleaned_data['firstname']
        u.last_name = self.cleaned_data['lastname']
        u.email = self.cleaned_data['email']
        if self.cleaned_data['password1']:
            u.set_password(self.cleaned_data['password1'])
        u.save()

        # for some strange reason (primary key == openid_url != int?), a new
        # item is created when saving an existing one, so delete the old
        try:
            UserAssociation.objects.get(user=u).delete()
        except UserAssociation.DoesNotExist:
            pass
        finally:
            ua = UserAssociation(openid_url=self.cleaned_data['openid_url'],
                                 user=u)
            ua.save()
Exemple #5
0
def associate_success(
    request, identity_url, openid_response, redirect_field_name=REDIRECT_FIELD_NAME, send_email=True, **kwargs
):

    openid_ = from_openid_response(openid_response)
    openids = request.session.get("openids", [])
    openids.append(openid_)
    request.session["openids"] = openids
    uassoc = UserAssociation(openid_url=str(openid_), user_id=request.user.id)
    uassoc.save(send_email=send_email)
    redirect_to = "/accounts/openid/associate"
    nb_associated_openids, associated_openids = get_associate_openid(request.user)
    msg = ["Your Openid has been added"]
    return render_to_response(
        "authopenid/associate.html",
        {"associated_openids": associated_openids, "nb_associated_openids": nb_associated_openids, "msg": msg},
        context_instance=RequestContext(request),
    )
Exemple #6
0
def associate_success(request, identity_url, openid_response,
        redirect_field_name=REDIRECT_FIELD_NAME, send_email=True, **kwargs):
    """
    function used when new openid association success. redirect the user
    """
    openid_ = from_openid_response(openid_response)
    openids = request.session.get('openids', [])
    openids.append(openid_)
    request.session['openids'] = openids
    uassoc = UserAssociation(
                openid_url=str(openid_),
                user_id=request.user.id
    )
    uassoc.save(send_email=send_email)

    redirect_to = request.GET.get(redirect_field_name, '')
    if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL
    return HttpResponseRedirect(redirect_to)
Exemple #7
0
    def save(self, u):
        u.first_name=self.cleaned_data['firstname']
        u.last_name=self.cleaned_data['lastname']
        u.email=self.cleaned_data['email']
        if self.cleaned_data['password1']:
            u.set_password(self.cleaned_data['password1'])
        u.save()

        # for some strange reason (primary key == openid_url != int?), a new
        # item is created when saving an existing one, so delete the old
        try:
            UserAssociation.objects.get(user=u).delete()
        except UserAssociation.DoesNotExist:
            pass
        finally:
            ua = UserAssociation(
                openid_url=self.cleaned_data['openid_url'],
                user=u
            )
            ua.save()
Exemple #8
0
def associate_success(request,
                      identity_url,
                      openid_response,
                      redirect_field_name=REDIRECT_FIELD_NAME,
                      send_email=True,
                      **kwargs):

    openid_ = from_openid_response(openid_response)
    openids = request.session.get('openids', [])
    openids.append(openid_)
    request.session['openids'] = openids
    uassoc = UserAssociation(openid_url=str(openid_), user_id=request.user.id)
    uassoc.save(send_email=send_email)
    redirect_to = '/accounts/openid/associate'
    nb_associated_openids, associated_openids = get_associate_openid(
        request.user)
    msg = ["Your Openid has been added"]
    return render_to_response("authopenid/associate.html", {
        'associated_openids': associated_openids,
        'nb_associated_openids': nb_associated_openids,
        'msg': msg
    },
                              context_instance=RequestContext(request))
Exemple #9
0
def register(request):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    url : /complete/

    template : authopenid/complete.html
    """

    is_redirect = False
    next = clean_next(request.GET.get('next'))
    openid_ = request.session.get('openid', None)
    if not openid_:
        return HttpResponseRedirect(reverse('user_signin') + next)

    nickname = openid_.sreg.get('nickname', '')
    email = openid_.sreg.get('email', '')
    
    form1 = OpenidRegisterForm(initial={
        'next': next,
        'username': nickname,
        'email': email,
    }) 
    form2 = OpenidVerifyForm(initial={
        'next': next,
        'username': nickname,
    })
    
    if request.POST:
        just_completed = False
        if 'bnewaccount' in request.POST.keys():
            form1 = OpenidRegisterForm(request.POST)
            if form1.is_valid():
                next = clean_next(form1.cleaned_data.get('next'))
                is_redirect = True
                tmp_pwd = User.objects.make_random_password()
                user_ = User.objects.create_user(form1.cleaned_data['username'],
                         form1.cleaned_data['email'], tmp_pwd)
                
                # make association with openid
                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                    
                # login 
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user_)
        elif 'bverify' in request.POST.keys():
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                is_redirect = True
                next = clean_next(form2.cleaned_data.get('next'))
                user_ = form2.get_user()

                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                login(request, user_)
        
        # redirect, can redirect only if forms are valid.
        if is_redirect:
            return HttpResponseRedirect(next) 
    
    return render('authopenid/complete.html', {
        'form1': form1,
        'form2': form2,
        'nickname': nickname,
        'email': email
    }, context_instance=RequestContext(request))
Exemple #10
0
def register(request):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    url : /complete/

    template : authopenid/complete.html
    """

    is_redirect = False
    next = clean_next(request.GET.get("next"))
    openid_ = request.session.get("openid", None)
    if not openid_:
        return HttpResponseRedirect(reverse("user_signin") + next)

    nickname = openid_.sreg.get("nickname", "")
    email = openid_.sreg.get("email", "")

    form1 = OpenidRegisterForm(initial={"next": next, "username": nickname, "email": email})
    form2 = OpenidVerifyForm(initial={"next": next, "username": nickname})

    user_ = None
    if request.POST:
        just_completed = False
        if "bnewaccount" in request.POST.keys():
            form1 = OpenidRegisterForm(request.POST)
            if form1.is_valid():
                next = clean_next(form1.cleaned_data.get("next"))
                is_redirect = True
                tmp_pwd = User.objects.make_random_password()
                user_ = User.objects.create_user(form1.cleaned_data["username"], form1.cleaned_data["email"], tmp_pwd)

                # make association with openid
                uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id)
                uassoc.save()

                # login
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user_)
        elif "bverify" in request.POST.keys():
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                is_redirect = True
                next = clean_next(form2.cleaned_data.get("next"))
                user_ = form2.get_user()

                uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id)
                uassoc.save()
                login(request, user_)

        # check if we need to post a question that was added anonymously
        # this needs to be a function call becase this is also done
        # if user just logged in and did not need to create the new account

        if user_ != None and settings.EMAIL_VALIDATION == "on":
            send_new_email_key(user_, nomessage=True)
            output = validation_email_sent(request)
            set_email_validation_message(user_)  # message set after generating view
            return output
        elif user_.is_authenticated():
            return HttpResponseRedirect("/")
        else:
            raise server_error("")

    openid_str = str(openid_)
    bits = openid_str.split("/")
    base_url = bits[2]  # assume this is base url
    url_bits = base_url.split(".")
    provider_name = url_bits[-2].lower()

    providers = {
        "yahoo": '<font color="purple">Yahoo!</font>',
        "flickr": '<font color="#0063dc">flick</font><font color="#ff0084">r</font>&trade;',
        "google": "Google&trade;",
        "aol": '<font color="#31658e">AOL</font>',
    }
    if provider_name not in providers:
        provider_logo = provider_name
    else:
        provider_logo = providers[provider_name]

    return render(
        "authopenid/complete.html",
        {"form1": form1, "form2": form2, "provider": provider_logo, "nickname": nickname, "email": email},
        context_instance=RequestContext(request),
    )
Exemple #11
0
def register(request,
             template_name='authopenid/complete.html',
             redirect_field_name=REDIRECT_FIELD_NAME,
             register_form=OpenidRegisterForm,
             auth_form=AuthenticationForm,
             register_account=register_account,
             send_email=True,
             extra_context=None):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    :attr request: request object
    :attr template_name: string, name of template to use, 
    'authopenid/complete.html' by default
    :attr redirect_field_name: string, field name used for redirect. by default 
    'next'
    :attr register_form: form use to create a new account. By default 
    `OpenidRegisterForm`
    :attr auth_form: form object used for legacy authentification. 
    by default `OpenidVerifyForm` form auser auth contrib.
    :attr register_account: callback used to create a new account from openid. 
    It take the register_form as param.
    :attr send_email: boolean, by default True. If True, an email will be sent 
    to the user.
    :attr extra_context: A dictionary of variables to add to the template 
    context. Any callable object in this dictionary will be called to produce 
    the end result which appears in the context.
    """
    is_redirect = False
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    openid_ = request.session.get('openid', None)
    if openid_ is None or not openid_:
        return HttpResponseRedirect(
            "%s?%s" % (reverse('user_signin'),
                       urllib.urlencode({redirect_field_name: redirect_to})))

    nickname = ''
    email = ''
    if openid_.sreg is not None:
        nickname = openid_.sreg.get('nickname', '')
        email = openid_.sreg.get('email', '')
    if openid_.ax is not None and not nickname or not email:
        if openid_.ax.get('http://schema.openid.net/namePerson/friendly',
                          False):
            nickname = openid_.ax.get(
                'http://schema.openid.net/namePerson/friendly')[0]
        if openid_.ax.get('http://schema.openid.net/contact/email', False):
            email = openid_.ax.get('http://schema.openid.net/contact/email')[0]

    form1 = register_form(initial={
        'username': nickname,
        'email': email,
    })
    form2 = auth_form(initial={
        'username': nickname,
    })

    if request.POST:
        user_ = None
        if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        if 'email' in request.POST.keys():
            form1 = register_form(data=request.POST)
            if form1.is_valid():
                user_ = register_account(form1, openid_)
        else:
            form2 = auth_form(data=request.POST)
            if form2.is_valid():
                user_ = form2.get_user()
        if user_ is not None:
            # associate the user to openid
            uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id)
            uassoc.save(send_email=send_email)
            login(request, user_)
            return HttpResponseRedirect(redirect_to)

    return render(template_name, {
        'form1': form1,
        'form2': form2,
        redirect_field_name: redirect_to,
        'nickname': nickname,
        'email': email
    },
                  context_instance=_build_context(request,
                                                  extra_context=extra_context))
Exemple #12
0
def register(request, template_name='authopenid/complete.html', 
            redirect_field_name=REDIRECT_FIELD_NAME, 
            register_form=OpenidRegisterForm, auth_form=AuthenticationForm, 
            register_account=register_account, send_email=True, 
            extra_context=None):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    :attr request: request object
    :attr template_name: string, name of template to use, 
    'authopenid/complete.html' by default
    :attr redirect_field_name: string, field name used for redirect. by default 
    'next'
    :attr register_form: form use to create a new account. By default 
    `OpenidRegisterForm`
    :attr auth_form: form object used for legacy authentification. 
    by default `OpenidVerifyForm` form auser auth contrib.
    :attr register_account: callback used to create a new account from openid. 
    It take the register_form as param.
    :attr send_email: boolean, by default True. If True, an email will be sent 
    to the user.
    :attr extra_context: A dictionary of variables to add to the template 
    context. Any callable object in this dictionary will be called to produce 
    the end result which appears in the context.
    """
    is_redirect = False
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    openid_ = request.session.get('openid', None)
    if openid_ is None or not openid_:
        return HttpResponseRedirect("%s?%s" % (reverse('user_signin'),
                                urllib.urlencode({ 
                                redirect_field_name: redirect_to })))

    nickname = ''
    email = ''
    if openid_.sreg is not None:
        nickname = openid_.sreg.get('nickname', '')
        email = openid_.sreg.get('email', '')
    if openid_.ax is not None and not nickname or not email:
        if openid_.ax.get('http://schema.openid.net/namePerson/friendly', False):
            nickname = openid_.ax.get('http://schema.openid.net/namePerson/friendly')[0]
        if openid_.ax.get('http://schema.openid.net/contact/email', False):
            email = openid_.ax.get('http://schema.openid.net/contact/email')[0]
        
    
    form1 = register_form(initial={
        'username': nickname,
        'email': email,
    }) 
    form2 = auth_form(initial={ 
        'username': nickname,
    })
    
    if request.POST:
        user_ = None
        if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        if 'email' in request.POST.keys():
            form1 = register_form(data=request.POST)
            if form1.is_valid():
                user_ = register_account(form1, openid_)
        else:
            form2 = auth_form(data=request.POST)
            if form2.is_valid():
                user_ = form2.get_user()
        if user_ is not None:
            # associate the user to openid
            uassoc = UserAssociation(
                        openid_url=str(openid_),
                        user_id=user_.id
            )
            uassoc.save(send_email=send_email)
            login(request, user_)    
            return HttpResponseRedirect(redirect_to) 
    
    return render(template_name, {
        'form1': form1,
        'form2': form2,
        redirect_field_name: redirect_to,
        'nickname': nickname,
        'email': email
    }, context_instance=_build_context(request, extra_context=extra_context))
Exemple #13
0
def register(request):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    url : /complete/

    template : authopenid/complete.html
    """

    is_redirect = False
    next = clean_next(request.GET.get('next'))
    openid_ = request.session.get('openid', None)
    if not openid_:
        return HttpResponseRedirect(reverse('user_signin') + next)

    nickname = openid_.sreg.get('nickname', '')
    email = openid_.sreg.get('email', '')
    
    form1 = OpenidRegisterForm(initial={
        'next': next,
        'username': nickname,
        'email': email,
    }) 
    form2 = OpenidVerifyForm(initial={
        'next': next,
        'username': nickname,
    })
    
    if request.POST:
        just_completed = False
        if 'bnewaccount' in request.POST.keys():
            form1 = OpenidRegisterForm(request.POST)
            if form1.is_valid():
                next = clean_next(form1.cleaned_data.get('next'))
                is_redirect = True
                tmp_pwd = User.objects.make_random_password()
                user_ = User.objects.create_user(form1.cleaned_data['username'],
                         form1.cleaned_data['email'], tmp_pwd)
                
                # make association with openid
                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                    
                # login 
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user_)
        elif 'bverify' in request.POST.keys():
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                is_redirect = True
                next = clean_next(form2.cleaned_data.get('next'))
                user_ = form2.get_user()

                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                login(request, user_)
        
        # redirect, can redirect only if forms are valid.
        if is_redirect:
            return HttpResponseRedirect(next) 
    
    return render('authopenid/complete.html', {
        'form1': form1,
        'form2': form2,
        'nickname': nickname,
        'email': email
    }, context_instance=RequestContext(request))
Exemple #14
0
def register(request):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    url : /complete/

    template : authopenid/complete.html
    """

    is_redirect = False
    next = clean_next(request.GET.get('next'))
    openid_ = request.session.get('openid', None)
    if not openid_:
        return HttpResponseRedirect(reverse('user_signin') + next)

    nickname = openid_.sreg.get('nickname', '')
    email = openid_.sreg.get('email', '')

    form1 = OpenidRegisterForm(initial={
        'next': next,
        'username': nickname,
        'email': email,
    })
    form2 = OpenidVerifyForm(initial={
        'next': next,
        'username': nickname,
    })

    user_ = None
    if request.POST:
        just_completed = False
        if 'bnewaccount' in request.POST.keys():
            form1 = OpenidRegisterForm(request.POST)
            if form1.is_valid():
                next = clean_next(form1.cleaned_data.get('next'))
                is_redirect = True
                tmp_pwd = User.objects.make_random_password()
                user_ = User.objects.create_user(
                    form1.cleaned_data['username'],
                    form1.cleaned_data['email'], tmp_pwd)

                # make association with openid
                uassoc = UserAssociation(openid_url=str(openid_),
                                         user_id=user_.id)
                uassoc.save()

                # login
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user_)
        elif 'bverify' in request.POST.keys():
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                is_redirect = True
                next = clean_next(form2.cleaned_data.get('next'))
                user_ = form2.get_user()

                uassoc = UserAssociation(openid_url=str(openid_),
                                         user_id=user_.id)
                uassoc.save()
                login(request, user_)

        #check if we need to post a question that was added anonymously
        #this needs to be a function call becase this is also done
        #if user just logged in and did not need to create the new account

        if user_ != None and settings.EMAIL_VALIDATION == 'on':
            send_new_email_key(user_, nomessage=True)
            output = validation_email_sent(request)
            set_email_validation_message(
                user_)  #message set after generating view
            return output
        elif user_.is_authenticated():
            return HttpResponseRedirect('/')
        else:
            raise server_error('')

    openid_str = str(openid_)
    bits = openid_str.split('/')
    base_url = bits[2]  #assume this is base url
    url_bits = base_url.split('.')
    provider_name = url_bits[-2].lower()

    providers = {
        'yahoo': '<font color="purple">Yahoo!</font>',
        'flickr':
        '<font color="#0063dc">flick</font><font color="#ff0084">r</font>&trade;',
        'google': 'Google&trade;',
        'aol': '<font color="#31658e">AOL</font>',
    }
    if provider_name not in providers:
        provider_logo = provider_name
    else:
        provider_logo = providers[provider_name]

    return render('authopenid/complete.html', {
        'form1': form1,
        'form2': form2,
        'provider': provider_logo,
        'nickname': nickname,
        'email': email
    },
                  context_instance=RequestContext(request))
Exemple #15
0
def register(request):
    """
    register an openid.
    
    If user is already a member he can associate its openid with 
    its account.
    
    A new account could also be created and automaticaly associated
    to the openid.
    
    url : /complete/
    
    template : authopenid/complete.html
    """
    
    logging.debug('')
    openid_ = request.session.get('openid', None)
    next = get_next_url(request)
    if not openid_:
        logging.debug('oops, no openid in session --> go back to signin')
        return HttpResponseRedirect(reverse('user_signin') + '?next=%s' % next)
    
    nickname = openid_.sreg.get('nickname', '')
    email = openid_.sreg.get('email', '')
    form1 = OpenidRegisterForm(initial={
        'next': next,
        'username': nickname,
        'email': email,
    }) 
    form2 = OpenidVerifyForm(initial={
        'next': next,
        'username': nickname,
    })
    email_feeds_form = SimpleEmailSubscribeForm()
    
    user_ = None
    is_redirect = False
    logging.debug('request method is %s' % request.method)
    if request.method == 'POST':
        if 'bnewaccount' in request.POST.keys():
            logging.debug('trying to create new account associated with openid')
            form1 = OpenidRegisterForm(request.POST)
            email_feeds_form = SimpleEmailSubscribeForm(request.POST)
            if not form1.is_valid():
                logging.debug('OpenidRegisterForm is INVALID')
            elif not email_feeds_form.is_valid():
                logging.debug('SimpleEmailSubscribeForm is INVALID')
            else:
                logging.debug('OpenidRegisterForm and SimpleEmailSubscribeForm are valid')
                next = form1.cleaned_data['next']
                is_redirect = True
                logging.debug('creatng new django user %s ...' % form1.cleaned_data['username'])
                tmp_pwd = User.objects.make_random_password()
                user_ = User.objects.create_user(form1.cleaned_data['username'],
                         form1.cleaned_data['email'], tmp_pwd)
                
                user_.set_unusable_password()
                # make association with openid
                logging.debug('creating new openid user association %s <--> %s' \
                            % (user_.username, str(openid_)))
                uassoc = UserAssociation(openid_url=str(openid_), user_id=user_.id)
                uassoc.save()
                
                # login 
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                logging.debug('logging the user in')
                login(request, user_)
                logging.debug('saving email feed settings')
                email_feeds_form.save(user_)
        elif 'bverify' in request.POST.keys():
            logging.debug('processing OpenidVerify form')
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                logging.debug('form is valid')
                is_redirect = True
                next = form2.cleaned_data['next']
                user_ = form2.get_user()
                logging.debug('creating new openid user association %s <--> %s' \
                            % (user_.username, str(openid_)))
                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                logging.debug('logging the user in')
                login(request, user_)
        
        #check if we need to post a question that was added anonymously
        #this needs to be a function call becase this is also done
        #if user just logged in and did not need to create the new account
        
        if user_ != None:
            if settings.EMAIL_VALIDATION == 'on':
                logging.debug('sending email validation')
                send_new_email_key(user_,nomessage=True)
                output = validation_email_sent(request)
                set_email_validation_message(user_) #message set after generating view
                return output
            if user_.is_authenticated():
                logging.debug('success, send user to main page')
                return HttpResponseRedirect(reverse('index'))
            else:
                logging.debug('have really strange error')
                raise Exception('openid login failed')#should not ever get here
    
    openid_str = str(openid_)
    bits = openid_str.split('/')
    base_url = bits[2] #assume this is base url
    url_bits = base_url.split('.')
    provider_name = url_bits[-2].lower()
    
    providers = {'yahoo':'<font color="purple">Yahoo!</font>',
                'flickr':'<font color="#0063dc">flick</font><font color="#ff0084">r</font>&trade;',
                'google':'Google&trade;',
                'aol':'<font color="#31658e">AOL</font>',
                'myopenid':'MyOpenID',
                }
    if provider_name not in providers:
        provider_logo = provider_name
        logging.error('openid provider named "%s" has no pretty customized logo' % provider_name)
    else:
        provider_logo = providers[provider_name]
    
    logging.debug('printing authopenid/complete.html output')
    return render_to_response('authopenid/complete.html', {
        'form1': form1,
        'form2': form2,
        'email_feeds_form': email_feeds_form,
        'provider':mark_safe(provider_logo),
        'username': nickname,
        'email': email,
        'login_type':'openid',
        'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))
Exemple #16
0
def register_openid(request, template_name='auth/registration_form.html'):
    """
    register an openid.

    If user is already a member he can associate its openid with
    its account.

    A new account could also be created and automatically associated
    to the openid.
    """

    errors = None
    is_redirect = False
    next = clean_next(request.GET.get('next'))
    openid_ = request.session.get('openid', None)
    if not openid_:
        return HttpResponseRedirect(reverse('auth_login'))

    nickname = openid_.sreg.get('nickname', '')
    email = openid_.sreg.get('email', '')
    fullname = openid_.sreg.get('fullname', '')
    if fullname:
        _name = fullname.split(' ')
        lastname = _name[-1]
        firstname = ' '.join(_name[:-1])
    else:
        lastname, firstname = '', ''

    form = RegistrationForm(initial={
        'username': nickname,
        'email': email,
        'password': UNUSABLE_PASSWORD_PREFIX,
        'password_dup': UNUSABLE_PASSWORD_PREFIX,
        'first_name': firstname,
        'last_name': lastname,
    })
    openid_form = OpenidVerifyForm(initial={
        'next': next,
        'username': nickname,
    }, auto_id='openid_%s')

    if request.POST:
        just_completed = False
        if 'bnewaccount' in request.POST.keys():
            form = RegistrationForm(data=request.POST)
            if form.is_valid():
                is_redirect = True
                user = form.save()
                user.is_active = False   # set inactive for user to activate via the link in confirmation email
                user.set_unusable_password()
                user.save()

                # Add membership to the 'openid' group.
                # We do it manually instead of via user.grant_openid() because
                # through a series of dependencies, we can't make that call until
                # after the user has logged in for the first time.
                user.groups.add(Group.objects.get(name='openid'))

                # make association with openid
                uassoc = UserAssociation(openid_url=str(openid_),
                                         user_id=user.id)
                uassoc.save()

                #sending out activating email
                #this block of code were taken from account.views.registration
                hostname = Site.objects.get_current().domain
                url = 'http://%s%s' % (hostname, reverse('registration_complete'))
                url = wrap_url(url, uid=user.id, action='activation')
                params = {'domain': hostname, 'login': user.username, 'url': url}
                if email_template(user.email, 'account/mail/activation_required', **params):
                    #logging
                    log.info('username=%s clientip=%s action=user_signup', form.cleaned_data.get('username', ''), request.META.get('REMOTE_ADDR', ''))

                    next_url = reverse('activation_required')
                    print form.cleaned_data
                    if form.cleaned_data.get('signup_ann', False):
                        next_url += '?email=' + form.cleaned_data.get('email', '')
                    return HttpResponseRedirect(next_url)
                else:
                    user.delete()
                    msg = ('The error occurred while sending email '
                           'with activation code. Account was not created. '
                           'Please, try later.')
                    return message_view(request, _(msg))

        elif 'bverify' in request.POST.keys():
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                is_redirect = True
                next_url = clean_next(form2.cleaned_data.get('next'))
                user = form2.get_user()
                user.grant_openid()  # Add membership to the 'openid' group.

                # Don't let the association happens if there already is one.
                if UserAssociation.objects.filter(user=user.id).count() > 0:
                    return render_login_form(request,
                                             next_url,
                         message='Your account can only be associated with one OpenID URL at a time.')

                else:
                    uassoc = UserAssociation(openid_url=str(openid_),
                            user_id=user.id)
                    uassoc.save()
                    auth.login(request, user)
            else:
                # Take the first error message given.
                errors = form2.errors.popitem()[1]

        # redirect, can redirect only if forms are valid.
        if is_redirect:
            return HttpResponseRedirect(next_url)

    return render_to_response(request,
                              template_name,
                              {'form': form,
                               'openid_form': openid_form,
                               'errorlist': errors})
Exemple #17
0
def register(request):
    """
    register an openid.

    If user is already a member he can associate its openid with 
    its account.

    A new account could also be created and automaticaly associated
    to the openid.

    url : /complete/

    template : authopenid/complete.html
    """

    openid_ = request.session.get('openid', None)
    next = get_next_url(request)
    if not openid_:
        return HttpResponseRedirect(reverse('user_signin') + '?next=%s' % next)

    nickname = openid_.sreg.get('nickname', '')
    email = openid_.sreg.get('email', '')
    form1 = OpenidRegisterForm(initial={
        'next': next,
        'username': nickname,
        'email': email,
    }) 
    form2 = OpenidVerifyForm(initial={
        'next': next,
        'username': nickname,
    })
    email_feeds_form = EditUserEmailFeedsForm()

    user_ = None
    is_redirect = False
    if request.POST:
        if 'bnewaccount' in request.POST.keys():
            form1 = OpenidRegisterForm(request.POST)
            email_feeds_form = EditUserEmailFeedsForm(request.POST)
            if form1.is_valid() and email_feeds_form.is_valid():
                next = form1.cleaned_data['next']
                is_redirect = True
                tmp_pwd = User.objects.make_random_password()
                user_ = User.objects.create_user(form1.cleaned_data['username'],
                         form1.cleaned_data['email'], tmp_pwd)

                user_.set_unusable_password()
                # make association with openid
                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                    
                # login 
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user_)
                email_feeds_form.save(user_)
        elif 'bverify' in request.POST.keys():
            form2 = OpenidVerifyForm(request.POST)
            if form2.is_valid():
                is_redirect = True
                next = form2.cleaned_data['next']
                user_ = form2.get_user()

                uassoc = UserAssociation(openid_url=str(openid_),
                        user_id=user_.id)
                uassoc.save()
                login(request, user_)

        #check if we need to post a question that was added anonymously
        #this needs to be a function call becase this is also done
        #if user just logged in and did not need to create the new account
        
        if user_ != None:
            if settings.EMAIL_VALIDATION == 'on':
                send_new_email_key(user_,nomessage=True)
                output = validation_email_sent(request)
                set_email_validation_message(user_) #message set after generating view
                return output
            if user_.is_authenticated():
                return HttpResponseRedirect(reverse('index'))
            else:
                raise Exception('openid login failed')#should not ever get here
    
    openid_str = str(openid_)
    bits = openid_str.split('/')
    base_url = bits[2] #assume this is base url
    url_bits = base_url.split('.')
    provider_name = url_bits[-2].lower()

    providers = {'yahoo':'<font color="purple">Yahoo!</font>',
                'flickr':'<font color="#0063dc">flick</font><font color="#ff0084">r</font>&trade;',
                'google':'Google&trade;',
                'aol':'<font color="#31658e">AOL</font>',
                'myopenid':'MyOpenID',
                }
    if provider_name not in providers:
        provider_logo = provider_name
    else:
        provider_logo = providers[provider_name]

    return render('authopenid/complete.html', {
        'form1': form1,
        'form2': form2,
        'email_feeds_form': email_feeds_form,
        'provider':mark_safe(provider_logo),
        'username': nickname,
        'email': email,
        'login_type':'openid',
        'gravatar_faq_url':reverse('faq') + '#gravatar',
    }, context_instance=RequestContext(request))