def register(request, template_name="registration/register.html"):
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
    initial = {"email": request.GET["email"]} if "email" in request.GET else None
    user_form = RegistrationForm(initial=initial, data=(request.POST or None))
    profile_form = RegistrationProfileForm(request.POST or None)

    if user_form.is_valid() and profile_form.is_valid():
        new_user = user_form.save()
        if hasattr(profile_form, 'location'):
            profile = new_user.get_profile()
            profile.location = profile_form.location
            profile.save()
        user = auth.authenticate(username=new_user.email, password=user_form.cleaned_data["password1"])
        logged_in.send(sender=None, request=request, user=user, is_new_user=True)
        auth.login(request, user)
        save_queued_POST(request)
        # Light security check -- make sure redirect_to isn't garbage.
        if not redirect_to or ' ' in redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL

        # Heavier security check -- redirects to http://example.com should 
        # not be allowed, but things like /view/?param=http://example.com 
        # should be allowed. This regex checks if there is a '//' *before* a
        # question mark.
        elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
            redirect_to = settings.LOGIN_REDIRECT_URL

        return HttpResponseRedirect(redirect_to)
    return render_to_response(template_name, {
        'form': user_form,
        'profile_form': profile_form,
        REDIRECT_FIELD_NAME: redirect_to,
    }, context_instance=RequestContext(request))
Esempio n. 2
0
def login(request,
          template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    redirect_to = request.REQUEST.get(redirect_field_name, '')

    if request.method == "POST":
        form = authentication_form(data=request.POST)
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Heavier security check -- redirects to http://example.com should
            # not be allowed, but things like /view/?param=http://example.com
            # should be allowed. This regex checks if there is a '//' *before* a
            # question mark.
            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security checks complete. Log the user in.
            user = form.get_user()
            logged_in.send(sender=None,
                           request=request,
                           user=user,
                           is_new_user=False)
            auth.login(request, user)
            save_queued_POST(request)
            messages.add_message(request, GA_TRACK_PAGEVIEW, '/login/success')

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)

    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    return render_to_response(template_name, {
        'login_form': form,
        'register_form': RegistrationForm(),
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    },
                              context_instance=RequestContext(request))
Esempio n. 3
0
def register(request, template_name="registration/register.html"):
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
    initial = {
        "email": request.GET["email"]
    } if "email" in request.GET else None
    user_form = RegistrationForm(initial=initial, data=(request.POST or None))
    profile_form = RegistrationProfileForm(request.POST or None)

    if user_form.is_valid() and profile_form.is_valid():
        new_user = user_form.save()
        if hasattr(profile_form, 'location'):
            profile = new_user.get_profile()
            profile.location = profile_form.location
            profile.save()
        user = auth.authenticate(username=new_user.email,
                                 password=user_form.cleaned_data["password1"])
        logged_in.send(sender=None,
                       request=request,
                       user=user,
                       is_new_user=True)
        auth.login(request, user)
        save_queued_POST(request)
        # Light security check -- make sure redirect_to isn't garbage.
        if not redirect_to or ' ' in redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL

        # Heavier security check -- redirects to http://example.com should
        # not be allowed, but things like /view/?param=http://example.com
        # should be allowed. This regex checks if there is a '//' *before* a
        # question mark.
        elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
            redirect_to = settings.LOGIN_REDIRECT_URL

        return HttpResponseRedirect(redirect_to)
    return render_to_response(template_name, {
        'form': user_form,
        'profile_form': profile_form,
        REDIRECT_FIELD_NAME: redirect_to,
    },
                              context_instance=RequestContext(request))
Esempio n. 4
0
def _import_users(request):
    users = []
    has_errors = False

    group = None
    if "group" in request.POST and request.POST['group']:
        try:
            group = Group.objects.get(slug=request.POST['group'])
        except Group.DoesNotExist:
            messages.error(request, "Group '%s' does not exist.")
        
    for key in request.POST.keys():
        if key.startswith("confirm_"):
            counter = key[len("confirm_"):]
            user_data = dict([
                    (i, request.POST["%s_%s" % (i, counter)])
                    for i in "first_name last_name email geom phone language".split()
                    ])
            user_data['password1'] = "password"
            user_form = RegistrationForm(data=user_data)
            profile_form = ProfileEditForm(user_data)

            if user_form.is_valid() and profile_form.is_valid():
                new_user = user_form.save(commit=False)
                new_user.set_unusable_password()
                for attr in ("geom", "language", "phone"):
                    if attr in profile_form.cleaned_data and profile_form.cleaned_data[attr]:
                        setattr(new_user, attr, profile_form.cleaned_data[attr])
                users.append(new_user)
            else:
                has_errors = True
                user_data['errors'] = errors = {}
                errors.update(user_form.errors)
                errors.update(profile_form.errors)
                users.append(user_data)

    if has_errors:
        transaction.rollback()
    else:
        for user in users:
            user.save()
            profile = user.get_profile()
            for attr in ("geom", "language", "phone"):
                if hasattr(user, attr):
                    setattr(profile, attr, getattr(user, attr))
            profile.save()

            if group is not None:
                GroupUsers.objects.create(group=group, user=user, is_manager=False)
                message = ("Added user: <a href='/admin/auth/user/%s/'>%s</a> "
                           "to group <a href='/admin/groups/group/%s/'>%s</a>" % (
                        user.pk, user.get_full_name(), group.pk, group.name))
            else:
                message = ("Added user: <a href='/admin/auth/user/%s/'>%s</a> " % (
                        user.pk, user.get_full_name()))

            ## Now send the new user an email, telling him we created an account
            ## and giving him a link to set a password for his account.
            form = AccountConfirmForm({'email': user.email})
            if form.is_valid():
                form.save(email_template_name='export/user_import_password_reset_email.html',
                          use_https=request.is_secure(),
                          request=request)

            messages.success(request, message)

        return HttpResponseRedirect(".")

    groups = Group.objects.all()
    return render_to_response("export/user_import_preview.html", locals(), context_instance=RequestContext(request))