Example #1
0
def associations(request):
    from film20.facebook_connect.models import FBAssociation
    from film20.facebook_connect.utils import get_facebook_cookie
    from django_openidconsumer import views as openid_consumer_views
    from django_openidauth.models import UserOpenID, associate_openid, unassociate_openid
    from film20.account.models import OAuthService, OAUTH_SERVICES
    from django.contrib.auth import BACKEND_SESSION_KEY, load_backend
    from film20.facebook_connect.facebookAuth import FacebookBackend

    openid_url = request.POST.get('openid_url')
    if openid_url:
        # They entered a new OpenID and need to authenticate it - kick off the
        # process and make sure they are redirected back here afterwards
        def openid_failure(request, message):
            return message

        ret = openid_consumer_views.begin(
            request,
            redirect_to=reverse('openid_complete'),
            on_failure=openid_failure)
        if isinstance(ret, (str, unicode)) or isinstance(ret, unicode):
            messages.add_message(request, messages.ERROR, ret)
        else:
            return ret
    try:
        fb_association = FBAssociation.objects.get(user=request.user)
    except FBAssociation.DoesNotExist, e:
        fb_association = None
Example #2
0
def login(request):
    reason = None
    next = request.REQUEST.get('next', '')

    if request.method == "POST":
        openidform = OpenIDForm(request.POST)
        def openid_failure(request,message):
          return direct_to_template(request, "account/login.html", {
            "form": LoginForm(),
            "openidform": openidform,
            "openid_message":message,
            "reason": reason,
          })

        def if_not_user_url(request):
          return HttpResponseRedirect(reverse('acct_login'))

        if request.POST.has_key('openid_url'):
            redirect_to = '/openid/complete/'
            if next:
                logger.info("NEXT: %s", next)
                redirect_to += '?' + urlencode({'next':next})
            return openid_consumer_views.begin(request,on_failure=openid_failure,sreg = 'email,nickname',redirect_to=redirect_to, if_not_user_url=if_not_user_url)
          
        form = LoginForm(request.POST)
        redirect_to = None
        if form.login(request):	                
            return HttpResponseRedirect(make_absolute_url(next or '/'))
    else:        
        # http://jira.filmaster.org/browse/FLM-420
        full_next = FULL_DOMAIN + next
        if next == full_url("LOGOUT") or full_next == full_url("LOGOUT"):
            next = ""
        reason = request.GET.get('reason')
            
        form = LoginForm(
            initial = {
                'next': next,
                'reason': reason,
        })

        openidform = OpenIDForm(
            initial = {
                'next': next,
                'reason': reason,
        })
        
    return direct_to_template(request, "account/login.html", {
        "next": next,
        "form": form,
        "openidform": openidform,
        "reason": reason, 
    })
Example #3
0
def signup(request):
    reason = None
    next = get_next(request)
    iframe = 'iframe' in request.GET
    template = "account/%ssignup.html" % (iframe and 'iframe_' or '')
    
    if request.method == "POST":
        openidform = OpenIDForm(request.POST)
        def openid_failure(request,message):
            return direct_to_template(request, template, {
                "form": SignupForm(request=request),
                "openidform": openidform,
                "openid_message":message,
                "next":next,
                "reason": reason,
            })

        def if_not_user_url(request):
            return HttpResponseRedirect(reverse('acct_login'))

        if request.POST.has_key('openid_url'):
            from urllib import urlencode
            return openid_consumer_views.begin(request,on_failure=openid_failure,sreg = 'email,nickname',redirect_to='/openid/complete/?%s'%urlencode({'next':next or '/'}), if_not_user_url=if_not_user_url)
            
        form = SignupForm(request.POST, request=request, prefix=iframe and 'ajax' or None)
        if form.is_valid():
            user = form.save()
            user = authenticate(username=user.username, password=form.cleaned_data['password1'])
            auth_login(request, user)
            if iframe:
                return HttpResponse('<script>top.location.href = "%s";</script>' % make_absolute_url(next or '/'))
            return new_user_registered_redirect(request, next or '/')
    else:
        form = SignupForm(request=request, prefix=iframe and 'ajax' or None)
    openidform = OpenIDForm(
        initial = {
            'next': next,
            'reason': reason,
    })
    return direct_to_template(request, template, {
        "form": form,
        "next": next,
        "openidform": openidform,
    })
Example #4
0
def associations(request):
    from film20.facebook_connect.models import FBAssociation
    from django_openidconsumer import views as openid_consumer_views
    from django_openidauth.models import UserOpenID, associate_openid, unassociate_openid
    from film20.account.models import OAuthService, OAUTH_SERVICES
    
    openid_url = request.POST.get('openid_url')
    if openid_url:
        # They entered a new OpenID and need to authenticate it - kick off the
        # process and make sure they are redirected back here afterwards
        def openid_failure(request,message):
          return message
        ret = openid_consumer_views.begin(request, redirect_to=reverse('openid_complete'), on_failure=openid_failure)
        if isinstance(ret, (str, unicode)) or isinstance(ret,unicode):
            messages.add_message(request, messages.ERROR, ret)
        else:
          return ret
    try:
        fb_association = FBAssociation.objects.get(user=request.user)
    except FBAssociation.DoesNotExist, e:
        fb_association = None
Example #5
0
def associations(request, template_name='openid_associations.html', post_login_redirect='/openid/complete/'):
    """
    A view for managing the OpenIDs associated with a user account.
    """
    if 'openid_url' in request.POST:
        # They entered a new OpenID and need to authenticate it - kick off the
        # process and make sure they are redirected back here afterwards
        return consumer_views.begin(request, redirect_to=post_login_redirect)
    
    messages = []
    associated_openids = [
        rec.openid
        for rec in UserOpenID.objects.filter(user__id = request.user.id)
    ]
    
    # OpenIDs are associated and de-associated based on their key - which is a
    # hash of the OpenID, user ID and SECRET_KEY - this gives us a nice key for
    # submit button names or checkbox values and provides CSRF protection at 
    # the same time. We need to pre-calculate the hashes for the user's OpenIDs
    # in advance.
    add_hashes = dict([
        (_make_hash('add', request.user, openid), str(openid))
        for openid in request.openids
        if str(openid) not in associated_openids
    ])
    del_hashes = dict([
        (_make_hash('del', request.user, openid), openid)
        for openid in associated_openids
    ])
    
    # We can now cycle through the keys in POST, looking for stuff to add or 
    # delete. First though we check for the ?direct=1 argument and directly add
    # any OpenIDs that were authenticated in the last 5 seconds - this supports
    # the case where a user has entered an OpenID in the form on this page, 
    # authenticated it and been directed straight back here.
    # TODO: Reconsider this technique now that it's easier to create custom 
    #       behaviour when an OpenID authentication is successful.
    if request.GET.get('direct') and request.openids and \
            request.openids[-1].issued > int(time.time()) - 5 and \
            str(request.openids[-1]) not in associated_openids:
        new_openid = str(request.openids[-1])
        associate_openid(request.user, new_openid)
        associated_openids.append(new_openid)
        messages.append('%s has been associated with your account' % escape(
            new_openid
        ))
    
    # Now cycle through POST.keys() looking for OpenIDs to add or remove
    for key in request.POST.keys():
        if key in add_hashes:
            openid = add_hashes[key]
            if openid not in associated_openids:
                associate_openid(request.user, openid)
                associated_openids.append(openid)
                messages.append('%s has been associated with your account' % \
                    escape(openid)
                )
        if key in del_hashes:
            openid = del_hashes[key]
            if openid in associated_openids:
                unassociate_openid(request.user, openid)
                associated_openids.remove(openid)
                messages.append('%s has been removed from your account' % \
                    escape(openid)
                )
    
    # At this point associated_openids represents the current set of associated
    # OpenIDs, and messages contains any messages that should be displayed. The
    # final step is to work out which OpenIDs they have that are currently 
    # logged in BUT are not associated - these are the ones that should be 
    # displayed with an "associate this?" buttons.
    potential_openids = [
        str(openid) for openid in request.openids
        if str(openid) not in associated_openids
    ]
    
    # Finally, calculate the button hashes we are going to need for the form.
    add_buttons = [
        {'openid': openid, 'hash': _make_hash('add', request.user, openid)}
        for openid in potential_openids
    ]
    del_buttons = [
        {'openid': openid, 'hash': _make_hash('del', request.user, openid)}
        for openid in associated_openids
    ]
    
    return render(template_name, {
        'user': request.user,
        'messages': messages,
        'action': request.path,
        'add_buttons': add_buttons,
        'del_buttons': del_buttons, # This is also used to generate the list of 
                                    # of associated OpenIDs
    },
    context_instance=RequestContext(request))
Example #6
0
def activate_view(request, activation_key, row_level_role_id, user_id, text_id = None):
    activation_key = activation_key.lower() # Normalize before trying anything with it.
    activated, user = Profile.objects.activate_user(activation_key)
    if user:
        if row_level_role_id and not text_id:# old invitations 
            rl = ObjectUserRole.objects.filter(content_type = ContentType.objects.get_for_model(Text),
                                               user__exact = user.id,)
            if len(rl) == 1 :  #in case of a click in the first mail after a sequence of invitation/removal/re-invitation use text.id to recover  
                text_id = rl[0].object_id
           
        if text_id: # new invitations
            rl = ObjectUserRole.objects.filter(object_id__exact = text_id,
                                               content_type = ContentType.objects.get_for_model(Text),
                                               user__exact = user.id,)
            if not rl  :
                return HttpResponseRedirect(reverse('unauthorized'))
            
            row_level_role_id = rl[0].id
            
        if row_level_role_id:
            inviter_user = get_object_or_404(User,pk = user_id)            
            row_level_role = get_object_or_404(ObjectUserRole,pk = row_level_role_id)
           
        if request.method == 'POST':
            form = BasicRegisterForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                openid_url = data.get('openid_url', None)
                if not openid_url:  
                    # non openid activation
                    user.username = data['username']
                    user.first_name = data['firstname']
                    user.last_name = data['lastname']
                    user.set_password(data['password'])
                    user.save()
                    profile = user.get_profile() 
                    profile.preferred_language = data['preferred_language']
                    profile.is_temp = False
                    profile.save()
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, user)                
                    request.session['message'] = _(u"Registration successful !")
                    if row_level_role_id:
                        # directly redirect to text
                        redirect_to = reverse('text-viewandcomment', args=[row_level_role.object.id])
                        return HttpResponseRedirect(redirect_to)                    
                    else:
                        return HttpResponseRedirect("/")
                else:
                    # open id activation
                    # 1. store registration data in session
                    # 2. redirect to openid authentification page
                    # 3. home page redirect will:
                    #    - detect the authentification
                    #    - create the user
                    #    - attach the new user to openid
                    #    - login the user
                    request.session[DELAYED_REGISTRATION_SESSION_KEY] = form.cleaned_data
                    from django_openidconsumer.views import begin
                    return begin(request, redirect_to = reverse('openid-complete'))
        else:
            form = BasicRegisterForm(initial={'email': user.email})            
            if not user.get_profile().is_temp:
                # hack : manual backend setting
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                if activated:
                    request.session['message'] = _(u"Welcome, your account has been activated.")
                if row_level_role_id:
                    # directly redirect to text
                    redirect_to = reverse('text-viewandcomment', args=[row_level_role.object.id])
                    return HttpResponseRedirect(redirect_to)                    
                else:
                    return HttpResponseRedirect("/")

        text = row_level_role.object
        # slightly modify form appearance
        form.fields['email'].help_text = _(u"this is the email which received the invitation (it will never be displayed on the site)")
        form.fields['email'].widget.attrs['readonly'] = 'readonly'
        TOU_TXT = get_tou_txt()
        return render_to_response('accounts/invitation_register.html', {'has_newsletter':settings.HAS_NEWSLETTER, 'TOU_TXT' : TOU_TXT, 'form': form, 'inviter_user' : inviter_user, 'text' : text} , context_instance=RequestContext(request))            
    else:
        request.session['message'] = _(u"Invalid activation key.")
        return HttpResponseRedirect("/")
Example #7
0
def register_view(request):
    next_activate = ''
    if request.method == 'POST':
        if is_unattached_openid(request):
            form = RegisterFormWithoutPw(request.POST)
        else:
            form = RegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            if is_unattached_openid(request):
                pw = ''
                send = False
            else:
                pw = data['password']
                send = True
            if 'openid_url' in data and data['openid_url']:
                # the user is registering with OpendID authentification
                request.session[DELAYED_REGISTRATION_SESSION_KEY] = data
                from django_openidconsumer.views import begin
                return begin(request, redirect_to = reverse('openid-complete'))
            else:
                # no OpenID:
                # - redirect from an OpenID login
                # - plain old register
                user = Profile.objects.create_inactive_user(data['username'], 
                                                              data['email'], 
                                                              pw, 
                                                              data['preferred_language'],
                                                              send_email = send,
                                                              next_activate = request.POST.get('next_activate',''),
                                                              )
                user.first_name = data['firstname']
                user.last_name = data['lastname']
                user.save()
                # newsletter
                if data['newsletter'] and settings.HAS_NEWSLETTER and not settings.DEBUG:
                    register_mailman(data['email'], settings.NEWSLETTER_ADR, data['username'])
                # opend id?
                if is_unattached_openid(request):
                    # activate user
                    profile = user.get_profile() 
                    profile.is_temp = False
                    profile.save()                
                    user.is_active = True
                    user.save()
                    # attach it
                    from django_openidauth.models import associate_openid
                    associate_openid(user,request.openid)
                    # login
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, user)
                    request.session['message'] = _(u"OpenId Registration successful!")
                    return HttpResponseRedirect("/")            
                else:
                    request.session['message'] = _(u"Registration successful! Check your email to activate your account.")
                    return HttpResponseRedirect("/")            
    else:
        if 'django_language' in request.session:
            default_lang = request.session['django_language']
        elif request.LANGUAGE_CODE:
            default_lang = request.LANGUAGE_CODE
        else:
            default_lang = 'en'
        next_activate = request.GET.get("next_activate",'')
        if is_unattached_openid(request):
            form = RegisterFormWithoutPw(
                                initial={'preferred_language': default_lang}
                                )
        else:
            form = RegisterForm(
                                initial={'preferred_language': default_lang}
                                )
            
        
    TOU_TXT = get_tou_txt()
    return render_to_response('accounts/register.html', {'has_newsletter':settings.HAS_NEWSLETTER, 
                                                         'TOU_TXT':TOU_TXT, 
                                                         'form': form,
                                                         'next_activate': base64.b64encode(next_activate),
                                                         } , context_instance=RequestContext(request))
def associations(request, template_name="openid_associations.html"):
    """
    A view for managing the OpenIDs associated with a user account.
    """
    if "openid_url" in request.POST:
        # They entered a new OpenID and need to authenticate it - kick off the
        # process and make sure they are redirected back here afterwards
        return consumer_views.begin(request, redirect_to="/openid/complete/")

    messages = []
    associated_openids = [rec.openid for rec in UserOpenID.objects.filter(user__id=request.user.id)]

    # OpenIDs are associated and de-associated based on their key - which is a
    # hash of the OpenID, user ID and SECRET_KEY - this gives us a nice key for
    # submit button names or checkbox values and provides CSRF protection at
    # the same time. We need to pre-calculate the hashes for the user's OpenIDs
    # in advance.
    add_hashes = dict(
        [
            (_make_hash("add", request.user, openid), str(openid))
            for openid in request.openids
            if str(openid) not in associated_openids
        ]
    )
    del_hashes = dict([(_make_hash("del", request.user, openid), openid) for openid in associated_openids])

    # We can now cycle through the keys in POST, looking for stuff to add or
    # delete. First though we check for the ?direct=1 argument and directly add
    # any OpenIDs that were authenticated in the last 5 seconds - this supports
    # the case where a user has entered an OpenID in the form on this page,
    # authenticated it and been directed straight back here.
    # TODO: Reconsider this technique now that it's easier to create custom
    #       behaviour when an OpenID authentication is successful.
    if (
        request.GET.get("direct")
        and request.openids
        and request.openids[-1].issued > int(time.time()) - 5
        and str(request.openids[-1]) not in associated_openids
    ):
        new_openid = str(request.openids[-1])
        if associate_openid(request.user, new_openid):
            associated_openids.append(new_openid)
            messages.append("%s has been associated with your account" % escape(new_openid))
        else:
            messages.append(
                (
                    "%s could not be associated with your account, "
                    + "as it is already associated with a different account"
                )
                % escape(new_openid)
            )

    # Now cycle through POST.keys() looking for OpenIDs to add or remove
    for key in request.POST.keys():
        if key in add_hashes:
            openid = add_hashes[key]
            if openid not in associated_openids:
                if associate_openid(request.user, openid):
                    associated_openids.append(openid)
                    messages.append("%s has been associated with your account" % escape(openid))
                else:
                    messages.append(
                        (
                            "%s could not be associated with your "
                            + "account, as it is already associated with a "
                            + "different account"
                        )
                        % escape(openid)
                    )

        if key in del_hashes:
            openid = del_hashes[key]
            if openid in associated_openids:
                # if user has no password and this is last one, don't allow
                if (not request.user.has_usable_password()) and len(associated_openids) < 2:
                    messages.append("You need to set a password if you want to remove all" + " of your OpenIDs")
                else:
                    unassociate_openid(request.user, openid)
                    associated_openids.remove(openid)
                    messages.append("%s has been removed from your account" % escape(openid))

    # At this point associated_openids represents the current set of associated
    # OpenIDs, and messages contains any messages that should be displayed. The
    # final step is to work out which OpenIDs they have that are currently
    # logged in BUT are not associated - these are the ones that should be
    # displayed with an "associate this?" buttons.
    potential_openids = [str(openid) for openid in request.openids if str(openid) not in associated_openids]

    # Finally, calculate the button hashes we are going to need for the form.
    add_buttons = [{"openid": openid, "hash": _make_hash("add", request.user, openid)} for openid in potential_openids]
    del_buttons = [{"openid": openid, "hash": _make_hash("del", request.user, openid)} for openid in associated_openids]

    return render(
        template_name,
        {
            "user": request.user,
            "messages": messages,
            "action": request.path,
            "add_buttons": add_buttons,
            "del_buttons": del_buttons,  # This is also used to generate the list of
            # of associated OpenIDs
        },
    )