Exemplo n.º 1
0
def openid_new_user(request):
    next = get_next(request)
    if request.method == 'POST':
        form = SSORegistrationForm(request.POST, request=request)

        if form.is_valid():
            from django_openidauth.models import associate_openid
            from django.contrib.auth import load_backend
            new_user = form.save()
            associate_openid( new_user, request.openid )
            backend = load_backend('django.contrib.auth.backends.ModelBackend')
            new_user.backend = '%s.%s' % (
                backend.__module__, backend.__class__.__name__
            )
            auth_login(request, new_user)
            return new_user_registered_redirect(request, next or '/')
    else:
        initial = dict(
            next=next,
        )
        form = SSORegistrationForm(initial=initial, request=request)

    return direct_to_template(request, "account/sso_registration.html", {
        'form':form,
    })
Exemplo n.º 2
0
def is_unattached_openid(request):
    if not settings.OPENID:
        return False
    if request.openid and request.openid.openid:
        from django_openidauth.models import UserOpenID, associate_openid        
        res = UserOpenID.objects.filter(openid=request.openid.openid)
        if res:
            # connected openid user exists: login user
            user = res[0].user
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, user)            
            return False
        elif DELAYED_REGISTRATION_SESSION_KEY in request.session:
            # 1. create account previously registered
            # 2. associate with OpenID
            # 3. login
            
            # 1.
            data = request.session[DELAYED_REGISTRATION_SESSION_KEY]
            user = Profile.objects.create_inactive_user(data['username'],
                                 data['email'],
                                 data['password'],
                                 data['preferred_language'],
                                 send_email = False,
                                 )
            user.first_name = data['firstname']
            user.last_name = data['lastname']
            profile = user.get_profile() 
            profile.is_temp = False
            profile.save()
            
            # 2.
            associate_openid(user,request.openid)
            
            # 3.
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, user)                
        else:
            return True
    return False
Exemplo n.º 3
0
def register(request, success_url='/accounts/register/complete/',
        template_name='openid_register.html', already_registered_url='/'):
    """
    Allows a new user to register an account. A customised variation of the
    view of the same name from django-registration.

    Context::
        form
            The registration form

    Template::
        registration/registration_form.html (or template_name argument)

    """
    if request.method == 'POST':
        form = SSORegistrationForm(request.POST)

        if form.is_valid():
            new_user = form.save()
            associate_openid( new_user, request.openid )
            next = form.cleaned_data['next']
            print 'next',next

            # Unfortunately we have to annotate the user with the
            # 'django.contrib.auth.backends.ModelBackend' backend, or stuff breaks
            backend = load_backend('django.contrib.auth.backends.ModelBackend')
            new_user.backend = '%s.%s' % (
                backend.__module__, backend.__class__.__name__
            )
            log_user_in(request, new_user)

            return HttpResponseRedirect(next or success_url)
    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect( already_registered_url )
        form = SSORegistrationForm(initial={'next':request.GET.get('next','')})

    return render_to_response(template_name, { 'form': form },
                              context_instance=RequestContext(request))
Exemplo n.º 4
0
def openid_assign(request):
    user_openids = set(o.openid for o in UserOpenID.objects.filter(user=request.user).order_by('created_at'))
    last_openid = request.openids and request.openids[-1].openid
    if last_openid and last_openid not in user_openids:
        associate_openid(request.user, last_openid)
    return HttpResponseRedirect(reverse('associations'))
Exemplo n.º 5
0
def signup(request):
    if not request.user.is_anonymous():
        return redirect(reverse('index'))
    if request.method == 'POST':
        if request.openid:
            form = SignupForm(
                request.POST, request.FILES, openid=request.openid
            )
        else:
            form = SignupForm(request.POST, request.FILES)
        if form.is_valid():
            # First create the user
            creation_args = {
                'username': form.cleaned_data['username'],
                'email': form.cleaned_data['email'],
            }
            if form.cleaned_data.get('password1'):
                creation_args['password'] = form.cleaned_data['password1']

            user = User.objects.create_user(**creation_args)
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.save()

            if request.openid:
                associate_openid(user, str(request.openid))

            region = None
            if form.cleaned_data['region']:
                region = Region.objects.get(
                    country__iso_code = form.cleaned_data['country'],
                    code = form.cleaned_data['region']
                )

            # Now create the DjangoPerson
            person = DjangoPerson.objects.create(
                user = user,
                bio = form.cleaned_data['bio'],
                country = Country.objects.get(
                    iso_code = form.cleaned_data['country']
                ),
                region = region,
                latitude = form.cleaned_data['latitude'],
                longitude = form.cleaned_data['longitude'],
                location_description = form.cleaned_data['location_description']
            )

            # Set up the various machine tags
            for fieldname, (namespace, predicate) in \
                    MACHINETAGS_FROM_FIELDS.items():
                if form.cleaned_data.has_key(fieldname) and \
                    form.cleaned_data[fieldname].strip():
                    value = form.cleaned_data[fieldname].strip()
                    person.add_machinetag(namespace, predicate, value)

            # Stash their blog and looking_for_work
            if form.cleaned_data['blog']:
                person.add_machinetag(
                    'profile', 'blog', form.cleaned_data['blog']
                )
            if form.cleaned_data['looking_for_work']:
                person.add_machinetag(
                    'profile', 'looking_for_work',
                    form.cleaned_data['looking_for_work']
                )

            # Finally, set their skill tags
            person.skilltags = form.cleaned_data['skilltags']

            # Log them in and redirect to their profile page
            # HACK! http://groups.google.com/group/django-users/
            #    browse_thread/thread/39488db1864c595f
            user.backend='django.contrib.auth.backends.ModelBackend'
            auth.login(request, user)
            return redirect(person.get_absolute_url())
    else:
        if request.openid and request.openid.sreg:
            sreg = request.openid.sreg
            first_name = ''
            last_name = ''
            username = ''
            if sreg.get('fullname'):
                bits = sreg['fullname'].split()
                first_name = bits[0]
                if len(bits) > 1:
                    last_name = ' '.join(bits[1:])
            # Find a not-taken username
            if sreg.get('nickname'):
                username = derive_username(sreg['nickname'])
            form = SignupForm(initial = {
                'first_name': first_name,
                'last_name': last_name,
                'email': sreg.get('email', ''),
                'username': username,
            }, openid = request.openid)
        elif request.openid:
            form = SignupForm(openid = request.openid)
        else:
            form = SignupForm()
    
    return render(request, 'signup.html', {
        'form': form,
        'openid': request.openid,
    })
Exemplo n.º 6
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))
Exemplo n.º 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))
Exemplo n.º 8
0
def signup(request):
    if not request.user.is_anonymous():
        return HttpResponseRedirect("/")
    if request.method == "POST":
        if request.openid:
            form = SignupForm(request.POST, request.FILES, openid=request.openid)
        else:
            form = SignupForm(request.POST, request.FILES)
        if form.is_valid():
            # First create the user
            creation_args = {"username": form.cleaned_data["username"], "email": form.cleaned_data["email"]}
            if form.cleaned_data.get("password1"):
                creation_args["password"] = form.cleaned_data["password1"]

            user = User.objects.create_user(**creation_args)
            user.first_name = form.cleaned_data["first_name"]
            user.last_name = form.cleaned_data["last_name"]
            user.save()

            if request.openid:
                associate_openid(user, str(request.openid))

            region = None
            if form.cleaned_data["region"]:
                region = Region.objects.get(
                    country__iso_code=form.cleaned_data["country"], code=form.cleaned_data["region"]
                )

            # Now create the DjangoPerson
            person = DjangoPerson.objects.create(
                user=user,
                bio=form.cleaned_data["bio"],
                country=Country.objects.get(iso_code=form.cleaned_data["country"]),
                region=region,
                latitude=form.cleaned_data["latitude"],
                longitude=form.cleaned_data["longitude"],
                location_description=form.cleaned_data["location_description"],
            )

            # Set up the various machine tags
            for fieldname, (namespace, predicate) in MACHINETAGS_FROM_FIELDS.items():
                if form.cleaned_data.has_key(fieldname) and form.cleaned_data[fieldname].strip():
                    value = form.cleaned_data[fieldname].strip()
                    person.add_machinetag(namespace, predicate, value)

            # Stash their blog and looking_for_work
            if form.cleaned_data["blog"]:
                person.add_machinetag("profile", "blog", form.cleaned_data["blog"])
            if form.cleaned_data["looking_for_work"]:
                person.add_machinetag("profile", "looking_for_work", form.cleaned_data["looking_for_work"])

            # Finally, set their skill tags
            person.skilltags = form.cleaned_data["skilltags"]

            # Log them in and redirect to their profile page
            # HACK! http://groups.google.com/group/django-users/
            #    browse_thread/thread/39488db1864c595f
            user.backend = "django.contrib.auth.backends.ModelBackend"
            auth.login(request, user)
            return HttpResponseRedirect(person.get_absolute_url())
    else:
        if request.openid and request.openid.sreg:
            sreg = request.openid.sreg
            first_name = ""
            last_name = ""
            username = ""
            if sreg.get("fullname"):
                bits = sreg["fullname"].split()
                first_name = bits[0]
                if len(bits) > 1:
                    last_name = " ".join(bits[1:])
            # Find a not-taken username
            if sreg.get("nickname"):
                username = derive_username(sreg["nickname"])
            form = SignupForm(
                initial={
                    "first_name": first_name,
                    "last_name": last_name,
                    "email": sreg.get("email", ""),
                    "username": username,
                },
                openid=request.openid,
            )
        elif request.openid:
            form = SignupForm(openid=request.openid)
        else:
            form = SignupForm()

    return render(
        request, "signup.html", {"form": form, "api_key": settings.GOOGLE_MAPS_API_KEY, "openid": request.openid}
    )