Пример #1
0
def signin(request):
    """
    signin page. It manage the legacy authentification (user/password) 
    and authentification with openid.

    url: /signin/
    
    template : authopenid/signin.htm
    """
    request.encoding = 'UTF-8'
    on_failure = signin_failure
    next = clean_next(request.GET.get('next'))

    form_signin = OpenidSigninForm(initial={'next':next})
    form_auth = OpenidAuthForm(initial={'next':next})
    
    if request.POST:   
        
        if 'bsignin' in request.POST.keys():

            form_signin = OpenidSigninForm(request.POST)
            if form_signin.is_valid():
                next = clean_next(form_signin.cleaned_data.get('next'))
                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (
                        get_url_host(request),
                        reverse('user_complete_signin'), 
                        urllib.urlencode({'next':next})
                )

                return ask_openid(request, 
                        form_signin.cleaned_data['openid_url'], 
                        redirect_to, 
                        on_failure=signin_failure, 
                        sreg_request=sreg_req)

        elif 'blogin' in request.POST.keys():
            # perform normal django authentification
            form_auth = OpenidAuthForm(request.POST)
            if form_auth.is_valid():
                user_ = form_auth.get_user()
                login(request, user_)
                next = clean_next(form_auth.cleaned_data.get('next'))
                return HttpResponseRedirect(next)


    return render('authopenid/signin.html', {
        'form1': form_auth,
        'form2': form_signin,
        'msg':  request.GET.get('msg',''),
        'sendpw_url': reverse('user_sendpw'),
    }, context_instance=RequestContext(request))
Пример #2
0
def signup(request):
    """
    signup page. Create a legacy account

    url : /signup/"

    templates: authopenid/signup.html, authopenid/confirm_email.txt
    """
    action_signin = reverse('user_signin')
    next = clean_next(request.GET.get('next'))
    form = RegistrationForm(initial={'next': next})
    form_signin = OpenidSigninForm(initial={'next': next})

    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            next = clean_next(form.cleaned_data.get('next'))
            user_ = User.objects.create_user(form.cleaned_data['username'],
                                             form.cleaned_data['email'],
                                             form.cleaned_data['password1'])

            user_.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user_)

            # send email
            current_domain = Site.objects.get_current().domain
            subject = _("Welcome")
            message_template = loader.get_template(
                'authopenid/confirm_email.txt')
            message_context = Context({
                'site_url':
                'http://%s/' % current_domain,
                'username':
                form.cleaned_data['username'],
                'password':
                form.cleaned_data['password1']
            })
            message = message_template.render(message_context)
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
                      [user_.email])

            return HttpResponseRedirect(next)

    return render('authopenid/signup.html', {
        'form': form,
        'form2': form_signin,
    },
                  context_instance=RequestContext(request))
Пример #3
0
def signin_success(request, identity_url, openid_response):
    """
    openid signin success.

    If the openid is already registered, the user is redirected to 
    url set par next or in settings with OPENID_REDIRECT_NEXT variable.
    If none of these urls are set user is redirectd to /.

    if openid isn't registered user is redirected to register page.
    """

    openid_ = from_openid_response(
        openid_response)  #create janrain OpenID object
    request.session['openid'] = openid_
    try:
        rel = UserAssociation.objects.get(openid_url__exact=str(openid_))
    except:
        # try to register this new user
        return register(request)
    user_ = rel.user
    if user_.is_active:
        user_.backend = "django.contrib.auth.backends.ModelBackend"
        login(request, user_)

    next = clean_next(request.GET.get('next'))
    return HttpResponseRedirect(next)
Пример #4
0
def signin_success(request, identity_url, openid_response):
    """
    openid signin success.

    If the openid is already registered, the user is redirected to 
    url set par next or in settings with OPENID_REDIRECT_NEXT variable.
    If none of these urls are set user is redirectd to /.

    if openid isn't registered user is redirected to register page.
    """

    openid_ = from_openid_response(openid_response)  # create janrain OpenID object
    request.session["openid"] = openid_
    try:
        rel = UserAssociation.objects.get(openid_url__exact=str(openid_))
    except:
        # try to register this new user
        return register(request)
    user_ = rel.user
    if user_.is_active:
        user_.backend = "django.contrib.auth.backends.ModelBackend"
        login(request, user_)

    next = clean_next(request.GET.get("next"))
    return HttpResponseRedirect(next)
Пример #5
0
def signin_complete(request):
    is_redirect = False
    next = clean_next(request.GET.get('next'))

    form1 = OpenidRegisterForm()
    form2 = OpenidVerifyForm()
    if request.POST:
        if not request.session.get('webauth_pui', None):
            return HttpResponseRedirect('/webauth/signin/')
        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 = WebauthUser(userLiveID=request.session.get('webauth_pui'), user_id=user_.id)
                uassoc.save()

                # login
                user_.backend = "django.contrib.auth.backends.ModelBackend"
                login(request, user_)
                request.session['auth_type'] = 'webauth'
        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 = WebauthUser(userLiveID=request.session.get('webauth_pui'), user_id=user_.id)
                uassoc.save()
                login(request, user_)
                request.session['auth_type'] = 'webauth'

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

    return render_to_response('webauth/signin_complete.html', {
        'form1': form1,
        'form2': form2,
    }, context_instance=RequestContext(request))
Пример #6
0
def common_login(request):
    next = clean_next(request.GET.get('next', ''))
    wll = get_window_live_login()
    return render_to_response('common_login.html',
                              {'form_auth': OpenidAuthForm(initial={'next': next}),
                               'form_google': OpenidSigninForm(initial={'next': next}),
                               'webauth_appid': wll.getAppId(),
                               'webauth_controlstyle': settings_webauth.CONTROLSTYLE, },
                               context_instance=RequestContext(request))
Пример #7
0
def signup(request):
    """
    signup page. Create a legacy account

    url : /signup/"

    templates: authopenid/signup.html, authopenid/confirm_email.txt
    """
    action_signin = reverse('user_signin')
    next = clean_next(request.GET.get('next'))
    form = RegistrationForm(initial={'next':next})
    form_signin = OpenidSigninForm(initial={'next':next})
    
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            next = clean_next(form.cleaned_data.get('next'))
            user_ = User.objects.create_user( form.cleaned_data['username'],
                    form.cleaned_data['email'], form.cleaned_data['password1'])
           
            user_.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user_)
            
            # send email
            current_domain = Site.objects.get_current().domain
            subject = _("Welcome")
            message_template = loader.get_template(
                    'authopenid/confirm_email.txt'
            )
            message_context = Context({ 
                'site_url': 'http://%s/' % current_domain,
                'username': form.cleaned_data['username'],
                'password': form.cleaned_data['password1'] 
            })
            message = message_template.render(message_context)
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, 
                    [user_.email])
            
            return HttpResponseRedirect(next)
    
    return render('authopenid/signup.html', {
        'form': form,
        'form2': form_signin,
        }, context_instance=RequestContext(request))
Пример #8
0
def signup(request):
    """
    signup page. Create a legacy account

    url : /signup/"

    templates: authopenid/signup.html, authopenid/confirm_email.txt
    """
    action_signin = reverse("user_signin")
    next = clean_next(request.GET.get("next"))
    form = RegistrationForm(initial={"next": next})
    form_signin = OpenidSigninForm(initial={"next": next})

    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            next = clean_next(form.cleaned_data.get("next"))
            user_ = User.objects.create_user(
                form.cleaned_data["username"], form.cleaned_data["email"], form.cleaned_data["password1"]
            )

            user_.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user_)

            # send email
            current_domain = Site.objects.get_current().domain
            subject = _("Welcome")
            message_template = loader.get_template("authopenid/confirm_email.txt")
            message_context = Context(
                {
                    "site_url": "http://%s/" % current_domain,
                    "username": form.cleaned_data["username"],
                    "password": form.cleaned_data["password1"],
                }
            )
            message = message_template.render(message_context)
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user_.email])

            return HttpResponseRedirect(next)

    return render(
        "authopenid/signup.html", {"form": form, "form2": form_signin}, context_instance=RequestContext(request)
    )
Пример #9
0
def signout(request):
    """
    signout from the website. Remove openid from session and kill it.

    url : /signout/"
    """
    try:
        del request.session['openid']
    except KeyError:
        pass
    next = clean_next(request.GET.get('next'))
    logout(request)

    return HttpResponseRedirect(next)
Пример #10
0
def signout(request):
    """
    signout from the website. Remove openid from session and kill it.

    url : /signout/"
    """
    try:
        del request.session["openid"]
    except KeyError:
        pass
    next = clean_next(request.GET.get("next"))
    logout(request)

    return HttpResponseRedirect(next)
Пример #11
0
def signin_failure(request, message):
    """
    falure with openid signin. Go back to signin page.

    template : "authopenid/signin.html"
    """
    next = clean_next(request.GET.get('next'))
    form_signin = OpenidSigninForm(initial={'next': next})
    form_auth = OpenidAuthForm(initial={'next': next})

    return render('authopenid/signin.html', {
        'msg': message,
        'form1': form_auth,
        'form2': form_signin,
    }, context_instance=RequestContext(request))
Пример #12
0
def signin_failure(request, message):
    """
    falure with openid signin. Go back to signin page.

    template : "authopenid/signin.html"
    """
    next = clean_next(request.GET.get("next"))
    form_signin = OpenidSigninForm(initial={"next": next})
    form_auth = OpenidAuthForm(initial={"next": next})

    return render(
        "authopenid/signin.html",
        {"msg": message, "form1": form_auth, "form2": form_signin},
        context_instance=RequestContext(request),
    )
Пример #13
0
def signin_failure(request, message):
    """
    falure with openid signin. Go back to signin page.

    template : "authopenid/signin.html"
    """
    next = clean_next(request.GET.get('next'))
    form_signin = OpenidSigninForm(initial={'next': next})
    form_auth = OpenidAuthForm(initial={'next': next})

    return render('authopenid/signin.html', {
        'msg': message,
        'form1': form_auth,
        'form2': form_signin,
    }, context_instance=RequestContext(request))
Пример #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,
    })
    
    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))
Пример #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
    """

    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))
Пример #16
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),
    )
Пример #17
0
def signin(request, newquestion=False, newanswer=False):
    """
    signin page. It manage the legacy authentification (user/password) 
    and authentification with openid.

    url: /signin/
    
    template : authopenid/signin.htm
    """
    request.encoding = "UTF-8"
    on_failure = signin_failure
    next = clean_next(request.GET.get("next"))

    form_signin = OpenidSigninForm(initial={"next": next})
    form_auth = OpenidAuthForm(initial={"next": next})

    if request.POST:

        if "bsignin" in request.POST.keys() or "openid_username" in request.POST.keys():

            form_signin = OpenidSigninForm(request.POST)
            if form_signin.is_valid():
                next = clean_next(form_signin.cleaned_data.get("next"))
                sreg_req = sreg.SRegRequest(optional=["nickname", "email"])
                redirect_to = "%s%s?%s" % (
                    get_url_host(request),
                    reverse("user_complete_signin"),
                    urllib.urlencode({"next": next}),
                )
                return ask_openid(
                    request,
                    form_signin.cleaned_data["openid_url"],
                    redirect_to,
                    on_failure=signin_failure,
                    sreg_request=sreg_req,
                )

        elif "blogin" in request.POST.keys():
            # perform normal django authentification
            form_auth = OpenidAuthForm(request.POST)
            if form_auth.is_valid():
                user_ = form_auth.get_user()
                login(request, user_)
                next = clean_next(form_auth.cleaned_data.get("next"))
                return HttpResponseRedirect(next)

    question = None
    if newquestion == True:
        from forum.models import AnonymousQuestion as AQ

        session_key = request.session.session_key
        qlist = AQ.objects.filter(session_key=session_key).order_by("-added_at")
        if len(qlist) > 0:
            question = qlist[0]
    answer = None
    if newanswer == True:
        from forum.models import AnonymousAnswer as AA

        session_key = request.session.session_key
        alist = AA.objects.filter(session_key=session_key).order_by("-added_at")
        if len(alist) > 0:
            answer = alist[0]

    return render(
        "authopenid/signin.html",
        {
            "question": question,
            "answer": answer,
            "form1": form_auth,
            "form2": form_signin,
            "msg": request.GET.get("msg", ""),
            "sendpw_url": reverse("user_sendpw"),
        },
        context_instance=RequestContext(request),
    )
Пример #18
0
def default_on_success(request, identity_url, openid_response):
    """ default action on openid signin success """
    request.session["openid"] = from_openid_response(openid_response)
    return HttpResponseRedirect(clean_next(request.GET.get("next")))
Пример #19
0
 def clean(self, value):
     return clean_next(value)
Пример #20
0
def default_on_success(request, identity_url, openid_response):
    """ default action on openid signin success """
    request.session['openid'] = from_openid_response(openid_response)
    return HttpResponseRedirect(clean_next(request.GET.get('next')))
Пример #21
0
def signin(request,newquestion=False,newanswer=False):
    """
    signin page. It manage the legacy authentification (user/password) 
    and authentification with openid.

    url: /signin/
    
    template : authopenid/signin.htm
    """
    request.encoding = 'UTF-8'
    on_failure = signin_failure
    next = clean_next(request.GET.get('next'))

    form_signin = OpenidSigninForm(initial={'next':next})
    form_auth = OpenidAuthForm(initial={'next':next})
    
    if request.POST:   
        
        if 'bsignin' in request.POST.keys() or 'openid_username' in request.POST.keys():

            form_signin = OpenidSigninForm(request.POST)
            if form_signin.is_valid():
                next = clean_next(form_signin.cleaned_data.get('next'))
                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (
                        get_url_host(request),
                        reverse('user_complete_signin'), 
                        urllib.urlencode({'next':next})
                )
                return ask_openid(request, 
                        form_signin.cleaned_data['openid_url'], 
                        redirect_to, 
                        on_failure=signin_failure, 
                        sreg_request=sreg_req)

        elif 'blogin' in request.POST.keys():
            # perform normal django authentification
            form_auth = OpenidAuthForm(request.POST)
            if form_auth.is_valid():
                user_ = form_auth.get_user()
                login(request, user_)
                next = clean_next(form_auth.cleaned_data.get('next'))
                return HttpResponseRedirect(next)

    question = None
    if newquestion == True:
        from forum.models import AnonymousQuestion as AQ
        session_key = request.session.session_key
        qlist = AQ.objects.filter(session_key=session_key).order_by('-added_at')
        if len(qlist) > 0:
            question = qlist[0]
    answer = None
    if newanswer == True:
        from forum.models import AnonymousAnswer as AA
        session_key = request.session.session_key
        alist = AA.objects.filter(session_key=session_key).order_by('-added_at')
        if len(alist) > 0:
            answer = alist[0]

    return render('authopenid/signin.html', {
        'question':question,
        'answer':answer,
        'form1': form_auth,
        'form2': form_signin,
        'msg':  request.GET.get('msg',''),
        'sendpw_url': reverse('user_sendpw'),
    }, context_instance=RequestContext(request))
Пример #22
0
 def clean_next(self):
     """ validate next """
     if 'next' in self.cleaned_data and self.cleaned_data['next'] != "":
         self.cleaned_data['next'] = clean_next(self.cleaned_data['next'])
         return self.cleaned_data['next']
Пример #23
0
def signin(request, newquestion=False, newanswer=False):
    """
    signin page. It manage the legacy authentification (user/password) 
    and authentification with openid.

    url: /signin/
    
    template : authopenid/signin.htm
    """
    request.encoding = 'UTF-8'
    on_failure = signin_failure
    next = clean_next(request.GET.get('next'))

    form_signin = OpenidSigninForm(initial={'next': next})
    form_auth = OpenidAuthForm(initial={'next': next})

    if request.POST:

        if 'bsignin' in request.POST.keys(
        ) or 'openid_username' in request.POST.keys():

            form_signin = OpenidSigninForm(request.POST)
            if form_signin.is_valid():
                next = clean_next(form_signin.cleaned_data.get('next'))
                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (get_url_host(request),
                                           reverse('user_complete_signin'),
                                           urllib.urlencode({'next': next}))
                return ask_openid(request,
                                  form_signin.cleaned_data['openid_url'],
                                  redirect_to,
                                  on_failure=signin_failure,
                                  sreg_request=sreg_req)

        elif 'blogin' in request.POST.keys():
            # perform normal django authentification
            form_auth = OpenidAuthForm(request.POST)
            if form_auth.is_valid():
                user_ = form_auth.get_user()
                login(request, user_)
                next = clean_next(form_auth.cleaned_data.get('next'))
                return HttpResponseRedirect(next)

    question = None
    if newquestion == True:
        from forum.models import AnonymousQuestion as AQ
        session_key = request.session.session_key
        qlist = AQ.objects.filter(
            session_key=session_key).order_by('-added_at')
        if len(qlist) > 0:
            question = qlist[0]
    answer = None
    if newanswer == True:
        from forum.models import AnonymousAnswer as AA
        session_key = request.session.session_key
        alist = AA.objects.filter(
            session_key=session_key).order_by('-added_at')
        if len(alist) > 0:
            answer = alist[0]

    return render('authopenid/signin.html', {
        'question': question,
        'answer': answer,
        'form1': form_auth,
        'form2': form_signin,
        'msg': request.GET.get('msg', ''),
        'sendpw_url': reverse('user_sendpw'),
    },
                  context_instance=RequestContext(request))
Пример #24
0
 def clean_next(self):
     """ validate next """
     if 'next' in self.cleaned_data and self.cleaned_data['next'] != "":
         self.cleaned_data['next'] = clean_next(self.cleaned_data['next'])
         return self.cleaned_data['next']
Пример #25
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))