Exemplo n.º 1
0
def logout_view(request, next_page=None,
           template_name='accounts/logged_out.html',
           redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)

    if next_page is not None:
        next_page = resolve_url(next_page)
    elif settings.LOGOUT_REDIRECT_URL:
        next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)

    if (redirect_field_name in request.POST or
            redirect_field_name in request.GET):
        next_page = request.POST.get(redirect_field_name,
                                     request.GET.get(redirect_field_name))
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(url=next_page, host=request.get_host()):
            next_page = request.path

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    context = {
        'title': _('Logged out')
    }

    return TemplateResponse(request, template_name, context)
Exemplo n.º 2
0
def login_view(request):
    """
    Control how the use is to be authenticated, options are 'email' and
    'username'
    """
    kwargs = {'template_name': 'authentication/login.html'}

    if setting_login_method.value == 'email':
        kwargs['authentication_form'] = EmailAuthenticationForm
    else:
        kwargs['authentication_form'] = UsernameAuthenticationForm

    if not request.user.is_authenticated:
        extra_context = {
            'appearance_type': 'plain',
            REDIRECT_FIELD_NAME: resolve_url(settings.LOGIN_REDIRECT_URL)
        }

        result = login(request, extra_context=extra_context, **kwargs)
        if request.method == 'POST':
            form = kwargs['authentication_form'](request, data=request.POST)
            if form.is_valid():
                if form.cleaned_data['remember_me']:
                    request.session.set_expiry(
                        setting_maximum_session_length.value
                    )
                else:
                    request.session.set_expiry(0)
        return result
    else:
        return HttpResponseRedirect(resolve_url(settings.LOGIN_REDIRECT_URL))
Exemplo n.º 3
0
def _should_abort_user(request, should_redirect):

    # authorize if user is staff
    if request.user.is_staff:
        return False

    # authorize if user is female and not blocked
    not_female = False
    blocked = False
    if hasattr(request.user, 'profile'):
        if request.user.profile.gender == Profile.FEMALE:
            if not request.user.profile.blocked:
                return False
            else:
                blocked = True
        else:
            not_female = True

    auth_logout(request)
    if should_redirect:
        if not_female:
            return redirect(resolve_url('female_only'))
        elif blocked:
            return redirect(resolve_url('blocked'))

    return HttpResponseForbidden()
Exemplo n.º 4
0
def logout(request, redirect_to=None):
	auth_logout(request)
	if redirect_to:
		redirect_to = resolve_url(redirect_to)
	else:
		redirect_to = resolve_url(settings.LOGOUT_REDIRECT_URL)
	return HttpResponseRedirect(redirect_to)
Exemplo n.º 5
0
def login(request):
    redirect_to = request.POST.get('next', request.GET.get('next', '/dashboard'))
    if not request.user.is_anonymous():
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
        return HttpResponseRedirect(redirect_to)
    if request.method == "POST":
        form = LoginForm(request, redirect_to=redirect_to, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = LoginForm(request, redirect_to=redirect_to)

    current_site = get_current_site(request)

    context = {
        'form': form,
        'next': redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }

    return TemplateResponse(request, 'login.html', context)
Exemplo n.º 6
0
 def test_non_view_callable_raises_no_reverse_match(self):
     """
     Tests that passing a non-view callable into ``resolve_url`` raises a
     ``NoReverseMatch`` exception.
     """
     with self.assertRaises(NoReverseMatch):
         resolve_url(lambda: 'asdf')
Exemplo n.º 7
0
    def get(self, request, uuid):
        lot = get_object_or_404(LOT, uuid=uuid)
        if not lot.verify():
            lot.delete()
            return HttpResponseNotFound()

        user = authenticate(request, lot_uuid=uuid)
        if user is not None:
            login(request, user)
        else:
            raise RuntimeError('The authentication backend did not return a user')

        try:
            session_data = json.loads(lot.session_data)
            request.session.update(session_data)
        except Exception:
            # If not correctly serialized not set the session_data
            pass

        if lot.is_one_time():
            lot.delete()

        redirect_to = request.GET.get('next')
        if lot.next_url:
            redirect_to = resolve_url(lot.next_url)

        if not is_safe_url(url=redirect_to, allowed_hosts=[request.get_host()]):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

        return HttpResponseRedirect(redirect_to)
Exemplo n.º 8
0
def login_link(request, **kwargs):
    email = kwargs.get('email')
    password = kwargs.get('password')

    redirect_to = request.REQUEST.get(auth.REDIRECT_FIELD_NAME, '')

    if request.method == "GET":
        user = auth.authenticate(username=email, password=password)

        if user is not None:
            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth.login(request, user)

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

            messages.success(request, _("You're logged in."))

            return HttpResponseRedirect(redirect_to)

    messages.error(request, _("Vos identifiants de connexion sont incorrects. Si vous n'êtes pas encore inscrit, nous vous invitons à vous inscrire en cliquant sur « Inscription » dans le cas contraire, cliquez sur le lien « J'ai oublié mon mot de passe »."))
    redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

    return HttpResponseRedirect(redirect_to)
Exemplo n.º 9
0
def test_message_create_and_retrieve(dd, admin_client):
    messages_api_view = resolve_url('infokala_messages_view', event_slug=dd.event.slug)

    retr_message_1 = get_data_from_response(admin_client.post(
        messages_api_view,
        json.dumps({'messageType': 'event', 'author': 'Infocorgi', 'message': 'Vuh!', }),
        content_type='application/json',
    ))

    message = Message.objects.get(
        id=retr_message_1['id'],
        author='Infocorgi',
        message='Vuh!'
    )
    assert message.state.initial  # initial state got set

    messages = get_data_from_response(admin_client.get(messages_api_view))
    assert len(messages) == 1
    retr_message_2 = messages[0]

    assert retr_message_2['message'] == 'Vuh!'
    assert retr_message_2['author'] == 'Infocorgi'

    message_api_view = resolve_url('infokala_message_view', event_slug=dd.event.slug, message_id=retr_message_2['id'])
    retr_message_3 = get_data_from_response(admin_client.get(message_api_view))
    assert retr_message_1 == retr_message_2 == retr_message_3  # check all endpoints agree on the content
Exemplo n.º 10
0
 def links(self, object):
     fmt = '<a href="%s?user__id__exact=%d">%s</a>'
     payments_url = resolve_url('admin:payments_payment_changelist')
     tickets_url = resolve_url('admin:tickets_ticket_changelist')
     s = fmt % (payments_url, object.id, "Payments")
     s += ' - ' + fmt % (tickets_url, object.id, "Tickets")
     return s
Exemplo n.º 11
0
 def test_non_view_callable_raises_no_reverse_match(self):
     """
     Passing a non-view callable into resolve_url() raises a
     NoReverseMatch exception.
     """
     with self.assertRaises(NoReverseMatch):
         resolve_url(lambda: 'asdf')
Exemplo n.º 12
0
    def test_revision_conflict(self):
        """
        Test the warning if the same article is being edited concurrently.
        """

        example_data = {
            'content': 'More modifications',
            'current_revision': str(URLPath.root().article.current_revision.id),
            'preview': '0',
            'save': '1',
            'summary': 'why edited',
            'title': 'wiki test'
        }

        response = self.client.post(
            resolve_url('wiki:edit', path=''),
            example_data
        )

        self.assertRedirects(response, resolve_url('wiki:root'))

        response = self.client.post(
            resolve_url('wiki:edit', path=''),
            example_data
        )

        self.assertContains(
            response,
            'While you were editing, someone else changed the revision.'
        )
Exemplo n.º 13
0
    def test_hierarchy_search(self):

        c = self.client

        c.post(
            resolve_url('wiki:create', path=''),
            {'title': 'Test0', 'slug': 'test0', 'content': 'Content test0'}
        )
        c.post(
            resolve_url('wiki:create', path=''),
            {'title': 'Test1', 'slug': 'test1', 'content': 'Content test1'}
        )
        c.post(
            resolve_url('wiki:create', path='test0/'),
            {'title': 'Subtest0', 'slug': 'subtest0', 'content': 'Content test2'}
        )

        response = c.get(resolve_url('wiki:search', path='test0/'), {'q': 'Content test'})
        articles = response.context['articles']

        def contains_title(articles, title):
            return any(article.current_revision.title == title for article in articles)

        self.assertTrue(contains_title(articles, 'Test0'))
        self.assertFalse(contains_title(articles, 'Test1'))
        self.assertTrue(contains_title(articles, 'Subtest0'))
Exemplo n.º 14
0
    def test_add_changelog_sending_email(self, logged_client):
        project = ProjectFactory.create()
        changelog_create_url = resolve_url(
            'projects:changelog_add',
            project.pk
        )
        project_detail_url = resolve_url(
            'projects:project_detail',
            project.pk
        )

        payload = {
            'description': '# version 0.0.1',
            'send_mail': True,
            'email_subject': 'Changelog - test',
            'email_recipients': '*****@*****.**',
        }

        response = logged_client.post(
            changelog_create_url,
            payload,
            follow=True
        )

        redirect_url, status_code = response.redirect_chain[0]
        changelog = Changelog.objects.last()

        assert project_detail_url in redirect_url
        assert status_code == 302

        assert changelog.email_sent
Exemplo n.º 15
0
def logout(
    request,
    next_page=None,
    template_name="registration/logged_out.html",
    redirect_field_name=REDIRECT_FIELD_NAME,
    extra_context=None,
):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    auth_logout(request)

    if next_page is not None:
        next_page = resolve_url(next_page)
    elif settings.LOGOUT_REDIRECT_URL:
        next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)

    if redirect_field_name in request.POST or redirect_field_name in request.GET:
        next_page = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name))
        # Security check -- don't allow redirection to a different host.
        if not is_safe_url(url=next_page, host=request.get_host()):
            next_page = request.path

    if next_page:
        # Redirect to this page until the session has been cleared.
        return HttpResponseRedirect(next_page)

    current_site = get_current_site(request)
    context = {"site": current_site, "site_name": current_site.name, "title": _("Logged out")}
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)
Exemplo n.º 16
0
    def test_send_email_ok(self, logged_client):
        changelog = ChangelogFactory.create()
        changelog_send_mail_url = resolve_url(
            'projects:changelog_send_mail',
            changelog.pk
        )
        project_detail_url = resolve_url(
            'projects:project_detail',
            changelog.project.pk
        )

        assert changelog.email_sent is False

        response = logged_client.post(
            changelog_send_mail_url,
            follow=True
        )

        redirect_url, status_code = response.redirect_chain[0]

        assert project_detail_url in redirect_url
        assert status_code == 302

        changelog = Changelog.objects.last()
        assert changelog.email_sent
Exemplo n.º 17
0
    def test_send_slack_ok(self, slack_mock, logged_client):
        changelog = ChangelogFactory.create()
        changelog_send_slack = resolve_url(
            'projects:changelog_send_slack',
            changelog.pk
        )
        project_detail_url = resolve_url(
            'projects:project_detail',
            changelog.project.pk
        )

        payload = {
            'channel': '#test-channel, #test-slack'
        }

        response = logged_client.post(
            changelog_send_slack,
            payload,
            follow=True
        )

        assert slack_mock.call_count == 2
        assert slack_mock.called

        redirect_url, status_code = response.redirect_chain[0]

        assert project_detail_url in redirect_url
        assert status_code == 302
Exemplo n.º 18
0
    def test_anonymous_redirect(self):
        url = reverse('banktransactions:list', kwargs={
            'bankaccount_pk': self.bankaccount.pk,
        })
        login_url = resolve_url(settings.LOGIN_URL)
        admin_base_url = get_script_prefix() + settings.MYMONEY['ADMIN_BASE_URL']

        # Anonymous should be redirect to login url.
        response = self.client.get(url, follow=True)
        self.assertEqual(response.request['PATH_INFO'], login_url)
        self.assertEqual(
            urlunquote(response.request['QUERY_STRING']),
            'next=' + url
        )

        # Check explicit infinite loop with anonymous.
        response = self.client.get(login_url, follow=True)
        self.assertEqual(response.request['PATH_INFO'], login_url)

        # However, check that anonymous could access back-office
        response = self.client.get(admin_base_url, follow=True)
        self.assertEqual(response.request['PATH_INFO'], admin_base_url + '/login/')

        # Authentificated user are not redirected.
        self.client.force_login(self.owner)
        response = self.client.get(url, follow=True)
        self.assertEqual(response.request['PATH_INFO'], url)

        # Check explicit infinite loop after log out.
        logout_url = resolve_url(settings.LOGOUT_URL)
        response = self.client.get(logout_url, follow=True)
        self.assertEqual(response.request['PATH_INFO'], login_url)
    def decorator(request, *args, **kwargs):
        if (request.user.is_authenticated() and
                (request.session[BACKEND_SESSION_KEY] == "two_factor_light.backends.TwoFactorBackend" or
                    not request.user.two_factor_required
                 )):
            return view_func(request, *args, **kwargs)

        if not request.user.is_authenticated():
            # If user isn't authenticated, do the same as login_required - redirect to login
            resolved_redirect_url = resolve_url(login_url or settings.LOGIN_URL)
        elif request.user.two_factor_enabled:
            # If the user has two factor auth, redirect to two factor login url
            resolved_redirect_url = resolve_url(two_factor_login_url or TWO_FACTOR_LOGIN_URL)
        else:
            # The user hasn't setup two factor auth yet, so redirect to setup url
            resolved_redirect_url = resolve_url(two_factor_setup_url or TWO_FACTOR_SETUP_URL)

        path = request.build_absolute_uri()
        redirect_scheme, redirect_netloc = urlparse(resolved_redirect_url)[:2]
        current_scheme, current_netloc = urlparse(path)[:2]
        if ((not redirect_scheme or redirect_scheme == current_scheme) and
                (not redirect_netloc or redirect_netloc == current_netloc)):
            path = request.get_full_path()
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(
            path, resolved_redirect_url, redirect_field_name
        )
Exemplo n.º 20
0
    def test_update_changelog_ok(self, logged_client):
        changelog = ChangelogFactory.create()
        changelog_update_url = resolve_url(
            'projects:changelog_update',
            changelog.pk
        )
        project_detail_url = resolve_url(
            'projects:project_detail',
            changelog.project.pk
        )

        # test GET
        response = logged_client.get(changelog_update_url)
        assert response.status_code == 200

        # test POST
        payload = {'description': '# version 0.0.1'}
        response = logged_client.post(
            changelog_update_url,
            payload,
            follow=True
        )
        redirect_url, status_code = response.redirect_chain[0]

        assert project_detail_url in redirect_url
        assert status_code == 302
Exemplo n.º 21
0
 def test_album_shows_in_library(self):
     _ = self.client.post(resolve_url('auth_login'), {
         'username': self.user.username,
         'password': "******",
     })
     library_response = self.client.get(resolve_url('library'))
     self.assertContains(library_response, resolve_url('albums', album_id=self.album.id))
Exemplo n.º 22
0
    def test_initial_setup_post(self):
        resp = self.client.post(
            resolve_url('first_time_setup'),
            data={
                'username': '',
                'password': '******'
            })
        self.assertEqual(resp.status_code, 400)

        resp = self.client.post(
            resolve_url('first_time_setup'),
            data={
                'username': '******',
                'password': ''
            })
        self.assertEqual(resp.status_code, 400)
        self.assertFalse(get_user_model().objects.exists())

        resp = self.client.post(
            resolve_url('first_time_setup'),
            data={
                'username': '******',
                'password': '******'
            })
        self.assertEqual(resp.status_code, 302)
        self.assertTrue(get_user_model().objects.exists())
Exemplo n.º 23
0
def login_view(request):
    context = {}
    if 'POST' == request.method:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)
                next = request.POST['next'] or \
                       resolve_url(settings.LOGIN_REDIRECT_URL)
                return HttpResponseRedirect(next)
            else:
                context['error_message'] = 'Disabled account'
        else:
            context['error_message'] = 'Invalid username or password'
        context['username'] = username
    else:                       # GET method
        if request.user.is_authenticated():
            return HttpResponseRedirect(resolve_url(settings.LOGIN_REDIRECT_URL))
        else:
            next = request.GET.get('next')
            if next:
                context['next'] = next

    return render(request, 'accounts/login.html', context)
Exemplo n.º 24
0
def register_view(request):
    context = {}

    if 'POST' == request.method:
        username = request.POST['username']
        password = request.POST['password']
        repassword = request.POST['repassword']
        context['username'] = username

        if username and password and repassword:
            if password == repassword:
                try:
                    User.objects.get(username=username)
                except User.DoesNotExist:
                    user = User.objects.create_user(username, password=password)
                    user.save()
                    return render(request, 'accounts/register_result.html', {
                        'login_url': resolve_url(settings.LOGIN_URL),
                    })
                else:
                    context['error_message'] = 'User already exists'
            else:
                context['error_message'] = 'Password not matched'
        else:
            context['error_message'] = 'Empty username or password'
    else:                       # GET method
        if request.user.is_authenticated():
            return HttpResponseRedirect(resolve_url(settings.LOGIN_REDIRECT_URL))

    return render(request, 'accounts/register.html', context)
Exemplo n.º 25
0
def postorius(request):
    """Add template variables to context.
    """
    # Use a template so that the page header/footer is suppressed when
    # requested via AJAX

    if request.is_ajax():
        template_to_extend = "postorius/base_ajax.html"
    else:
        template_to_extend = "postorius/base.html"

    # Find the HyperKitty URL if installed
    hyperkitty_url = False
    if "hyperkitty" in settings.INSTALLED_APPS:
        try:
            hyperkitty_url = reverse("hk_root")
        except NoReverseMatch:
            pass

    return {
        'postorius_base_template': template_to_extend,
        'request': request,
        'hyperkitty_url': hyperkitty_url,
        # Resolve the login and logout URLs from the settings
        'login_url': resolve_url(settings.LOGIN_URL),
        'logout_url': resolve_url(settings.LOGOUT_URL),
    }
Exemplo n.º 26
0
 def get_success_url(self):
     next_url = self.request.GET.get('next')
     if next_url:
         return next_url
     if self.request.user.is_staff:
         return resolve_url('acc_app:setup_info')
     return resolve_url('client_side:home')
Exemplo n.º 27
0
    def setUp(self):
        from django import forms
        
        self.factory = RequestFactory()
        
        user_model = get_user_model()
        
        class TestForm(forms.Form):
            text = forms.CharField(initial="Something...", required=True, widget=forms.Textarea)
            user = forms.ModelChoiceField(queryset=user_model.objects.all())

        registry.register_simple_plugget_source("Test", description="A test plugget source", form=TestForm)
               
        self.u1 = user_model.objects.create_user("u1", "*****@*****.**", "password")
        self.u2 = user_model.objects.create_user("u2", "*****@*****.**", "password")
        self.u3 = user_model.objects.create_user("u3", "*****@*****.**", "password")
        self.r = Region.objects.create(slug="r")
        self.p = Plugget.objects.create(title="Plugget", source="Test", context='{"text": "My plugget text", "user": 1}', region=self.r)
        
        rp, n = ObjectPermission.objects.get_or_create_by_uid("pluggets.change_region.%d" % self.r.pk)
        pp, n = ObjectPermission.objects.get_or_create_by_uid("pluggets.change_plugget.%d" % self.p.pk)
        ap, n = Permission.objects.get_or_create_by_uid("pluggets.add_plugget")
        
        self.u2.objectpermissions.add(rp)
        self.u2.user_permissions.add(ap)
        self.u3.objectpermissions.add(rp)
        self.u3.objectpermissions.add(pp)
        
        self.add_url = resolve_url("plugget_add", slug=self.r.slug)
        self.edit_url = resolve_url("plugget_edit", pk=self.p.pk)
Exemplo n.º 28
0
def reset_password(request,
                   template_name=None,
                   cancel_url=None,
                   post_change_redirect=None,
                   reset_password_form=ResetPasswordForm,
                   extra_context=None):
    cancel_url = resolve_url(cancel_url or '/')
    if request.user.is_authenticated():
        return HttpResponseRedirect(cancel_url)
    if post_change_redirect is None:
        post_change_redirect = reverse('reset_password_done')
    else:
        post_change_redirect = resolve_url(post_change_redirect)
    if request.method == "POST":
        form = reset_password_form(request=request, data=request.POST)
        if form.is_valid():
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = reset_password_form(request=request)
    context = {
        'form': form,
        'cancel_url': cancel_url,
    }
    context.update(extra_context or {})
    return TemplateResponse(request, template_name, context)
Exemplo n.º 29
0
    def get_context_data(self, form, **kwargs):
        """
        Adds user's default and backup OTP devices to the context.
        """
        context = super(LoginView, self).get_context_data(form, **kwargs)
        if self.steps.current == 'token':
            context['device'] = self.get_device()
            context['other_devices'] = [
                phone for phone in backup_phones(self.get_user())
                if phone != self.get_device()]
            try:
                context['backup_tokens'] = self.get_user().staticdevice_set\
                    .get(name='backup').token_set.count()
            except StaticDevice.DoesNotExist:
                context['backup_tokens'] = 0

        if getattr(settings, 'LOGOUT_REDIRECT_URL', None):
            context['cancel_url'] = resolve_url(settings.LOGOUT_REDIRECT_URL)
        elif getattr(settings, 'LOGOUT_URL', None):
            warnings.warn(
                "LOGOUT_URL has been replaced by LOGOUT_REDIRECT_URL, please "
                "review the URL and update your settings.",
                DeprecationWarning)
            context['cancel_url'] = resolve_url(settings.LOGOUT_URL)
        return context
Exemplo n.º 30
0
    def form_valid(self, form):
        data = form.cleaned_data
        domain = data['domain_base']
        domain_is_whitelisted = check_valid_tld(domain)
        if not domain_is_whitelisted:
            messages.info(
                self.request,
                "Sorry, but to limit the cost of running this service, we have not enabled searching this domain name (%s)." % domain
            )
            return HttpResponseRedirect(resolve_url('home'))

        search_done = search_bing(domain)
        if not search_done:
            messages.info(
                self.request,
                "This domain has already been requested today! Here is what we've gathered."
            )
        else:
            messages.info(
                self.request,
                "Gathering results now. They will be displayed shortly."
            )
        return HttpResponseRedirect(
            resolve_url('domain_result', domain)
        )
Exemplo n.º 31
0
def logout_then_login(request, login_url=None):
    """
    Log out the user if they are logged in. Then redirect to the login page.
    """
    login_url = resolve_url(login_url or settings.LOGIN_URL)
    return LogoutView.as_view(next_page=login_url)(request)
Exemplo n.º 32
0
 def get_success_url(self):
     return resolve_url('register:user_detail', pk=self.kwargs['pk'])
Exemplo n.º 33
0
def _affiliation_to_dict(affiliation):
    return dict(url=resolve_url('app:chat', affiliation.chat.hash_id),
                key=affiliation.hash_id,
                alias=affiliation.alias,
                active=affiliation.active,
                valentinas=affiliation.chat.affiliation_set.count())
Exemplo n.º 34
0
def logout(request):
    auth_logout(request)
    return redirect(resolve_url('home'))
Exemplo n.º 35
0
 def get_success_url(self):
     url = self.get_redirect_url()
     return url or resolve_url(settings.LOGIN_REDIRECT_URL)
Exemplo n.º 36
0
 def test_url_path(self):
     """
     Tests that passing a URL path to ``resolve_url`` will result in the
     same url.
     """
     self.assertEqual('/something/', resolve_url('/something/'))
Exemplo n.º 37
0
def get_device_kinds():
    return ((resolve_url('ip_pool:networks_%s/' % kind_code), kind_descr)
            for kind_code, kind_descr in NetworkModel.NETWORK_KINDS)
Exemplo n.º 38
0
 def location(self, obj):
     return resolve_url('thread:category', url_code=obj.url_code)
Exemplo n.º 39
0
 def location(self, obj):
     return resolve_url('thread:topic', pk=obj.id)
Exemplo n.º 40
0
def delete(request,id):
    post = Post.objects.get(id=id)
    post.delete()
    
    return redirect(resolve_url('post:list'))
Exemplo n.º 41
0
def redirect_param(location, params, *args, **kwargs):
    """Redirect to a URL with parameters."""
    return HttpResponseRedirect(
        resolve_url(location, *args, **kwargs) + params)
Exemplo n.º 42
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['login_url'] = resolve_url(settings.LOGIN_URL)
     return context
Exemplo n.º 43
0
def upload_subbasin_shapefile_zip(request):
    # Clear any previous progress or error messages
    request.session['progress_complete'] = []
    request.session['progress_message'] = []
    request.session['error'] = []
    request.session['error_subbasin'] = []

    # If user is submitting a zipped SWAT Model
    if request.method == 'POST':
        logger.info('Receiving the subbasin shapefile zip')
        if 'subbasin_shapefile_zip' in request.FILES:
            try:
                # Get the uploaded file and store the name of the zip
                file = request.FILES['subbasin_shapefile_zip']
                filename = file.name
                subbasin_shapefile_file = os.path.splitext(filename)
                subbasin_shapefile_filename = subbasin_shapefile_file[0]
                subbasin_shapefile_file_ext = subbasin_shapefile_file[1]
            except:
                logger.error(
                    "{0}: Unable to receive uploaded shapefile.".format(
                        request.session.get('unique_directory_name')))
                error_msg = 'Unable to receive the uploaded ' \
                            'file, please try again. If the ' \
                            'issue persists please use the ' \
                            'Contact Us form to request ' \
                            'further assistance from the ' \
                            'site admins.'
                request.session['error'] = error_msg
                request.session['error_subbasin'] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            if subbasin_shapefile_file_ext != ".zip":
                logger.error("{0}: Uploaded shapefile does not have .zip "
                             "extension.".format(
                                 request.session.get("unique_directory_name")))
                error_msg = "The file you are uploading does not have a .zip " \
                            "extension. Make sure the file you are uploading " \
                            "is a compressed zipfile. Please refer to the " \
                            "user manual if you need help creating a zipfile."
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url("luuchecker"))

            try:
                # Set up the working directory
                create_working_directory(request)
                unique_path = request.session.get("directory")
            except:
                logger.error("{0}: Unable to create working directory.".format(
                    request.session.get('unique_directory_name')))
                error_msg = 'Unable to set up user workspace, please try ' \
                            'again. If the issue persists please use the ' \
                            'Contact Us form to request further assistance ' \
                            'from the site admins.'
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            try:
                # If the shapefile directory already exists,
                # remove it to make way for new upload
                shp_path = unique_path + '/input/' + subbasin_shapefile_filename
                if os.path.exists(shp_path):
                    shutil.rmtree(shp_path)
            except:
                logger.error(
                    "{0}: Unable to remove previously uploaded file.".format(
                        request.session.get('unique_directory_name')))
                error_msg = 'Unable to remove previously uploaded file, ' \
                            'please use the Reset button to reset the tool. ' \
                            'If the issue persists please use the Contact Us ' \
                            'form to request further assistance from the ' \
                            'site admins.'
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            try:
                # Copy compressed data to the working directory
                with open(unique_path + '/input/' + filename,
                          'wb+') as destination:
                    for chunk in file.chunks():
                        destination.write(chunk)
            except:
                logger.error(
                    "{0}: Unable to write uploaded shapefile to disk.".format(
                        request.session.get('unique_directory_name')))
                error_msg = 'Unable to receive the uploaded file, please try ' \
                            'again. If the issue persists please use the ' \
                            'Contact Us form to request further assistance ' \
                            'from the site admins.'
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            # Uncompress the data
            logger.info('Unzipping the uploaded file')
            try:
                filepath = "{0}/input/{1}".format(unique_path,
                                                  subbasin_shapefile_filename)
                subprocess.call([
                    "unzip", "-qq", "-o", filepath, "-d",
                    unique_path + "/input/"
                ])

                # Set permissions for unzipped data
                fix_file_permissions(filepath)

                # Remove uploaded zip file
                os.remove(filepath + subbasin_shapefile_file_ext)
            except:
                logger.error("{0}: Unable to unzip uploaded shapefile.".format(
                    request.session.get('unique_directory_name')))
                error_msg = 'Unable to unzip the uploaded file, please try ' \
                            'again. If the issue persists please use the ' \
                            'Contact Us form to request further assistance ' \
                            'from the site admins.'
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            if not os.path.exists(filepath):
                logger.error(
                    "{0}: Unable to extract subbasin shapefile.".format(
                        request.session.get('unique_directory_name')))
                error_msg = 'Could not extract the folder ' \
                            '"subbasin_shapefile_filename + '". Please check " \
                            "if the file is compressed in zip format and has " \
                            "the same name as compressed folder. If the " \
                            "issue persists please use the Contact Us form " \
                            "to request further assistance from the site " \
                            "admins."
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            subbasin_shapefile_filepath = unique_path + '/input/' + subbasin_shapefile_filename + '/subs1.shp'

            if not os.path.exists(subbasin_shapefile_filepath):
                logger.error("{0}: Unable upload subbasin shapefile.".format(
                    request.session.get('unique_directory_name')))
                error_msg = 'Could not find the folder ' + \
                            subbasin_shapefile_filename + '/subs1.shp. ' \
                            'Please check for files in folder and re-upload ' \
                            'the zip file. If the issue persists please use ' \
                            'the Contact Us form to request further ' \
                            'assistance from the site admins.'
                request.session["error"] = error_msg
                request.session["error_subbasin"] = error_msg
                return HttpResponseRedirect(resolve_url('luuchecker'))

            # Update relevant session variables
            request.session[
                'luuc_subbasin_shapefile_filename'] = subbasin_shapefile_filename
            request.session[
                'luuc_subbasin_shapefile_filepath'] = subbasin_shapefile_filepath
            request.session['progress_message'].append(
                'Subbasin shapefile uploaded.')
            logger.info(
                'Subbasin shapefile successfully uploaded and extracted from zip'
            )

            # Render the main page
            return render(request, 'luuchecker/index.html')
        else:
            # Couldn't find a required subbasin shapefile, return error msg
            request.session['error'] = 'Please select your zipped subbasin ' \
                                       'shapefile before clicking the Upload ' \
                                       'button.'
            return HttpResponseRedirect(resolve_url('luuchecker'))
    else:
        # Nothing was posted, reload main page
        return render(request, 'luuchecker/index.html')
Exemplo n.º 44
0
 def get_context_data(self, **kwargs):
     kwargs["secretgraph_path"] = resolve_url(
         getattr(settings, "SECRETGRAPH_GRAPHQL_PATH", "/graphql"))
     return super().get_context_data(**kwargs)
Exemplo n.º 45
0
 def get_success_url(self):
     return resolve_url('shortener:url-preview', code=self.object.code)
Exemplo n.º 46
0
 def get_url(self, to=None, *args, **kwargs):
     return self.test.live_server_url + (resolve_url(to, *args, **kwargs)
                                         if to else '')
Exemplo n.º 47
0
 def get_success_url(self):
     return resolve_url('GroupConnect:group_setting', pk=self.kwargs['pk'])
Exemplo n.º 48
0
 def get_success_url(self):
     return resolve_url('myapp1:lists_detail', pk=self.kwargs['pk'])
Exemplo n.º 49
0
 def get_success_url(self):
     return resolve_url('tasks:task_detail', pk=self.task.id)
Exemplo n.º 50
0
 def get_success_url(self):
     return resolve_url('GroupConnect:user_test2mailaddress_update',
                        pk=self.kwargs['pk'])
    def setUpTestData(cls):
        cls.user = UserFactory()
        entity_version = EntityVersionFactory(acronym='ADRI')
        PartnershipEntityManagerFactory(
            entity=entity_version.entity,
            person__user=cls.user,
            scopes=[PartnershipType.GENERAL.name]
        )

        # Dates :
        cls.partner = PartnerFactory()
        cls.partner_entity = PartnerEntityFactory(partner=cls.partner)

        # Years
        cls.start_academic_year = AcademicYearFactory(year=2150)
        cls.from_academic_year = AcademicYearFactory(year=2151)
        cls.end_academic_year = AcademicYearFactory(year=2152)

        cls.education_field = DomainIscedFactory()
        cls.education_level = PartnershipYearEducationLevelFactory()

        # Ucl
        root = EntityVersionFactory(parent=None).entity
        sector = EntityVersionFactory(entity_type=SECTOR, parent=root).entity
        cls.ucl_university = EntityVersionFactory(
            parent=sector,
            entity_type=FACULTY,
        ).entity
        UCLManagementEntityFactory(entity=cls.ucl_university)
        cls.ucl_university_labo = EntityVersionFactory(
            parent=cls.ucl_university,
        ).entity
        UCLManagementEntityFactory(entity=cls.ucl_university_labo)

        cls.partnership = PartnershipFactory(
            partnership_type=PartnershipType.GENERAL.name,
            partner=cls.partner,
            partner_entity=cls.partner_entity.entity,
            author=cls.user.person,
            years=[],
            ucl_entity=cls.ucl_university,
        )
        PartnershipYearFactory(
            partnership=cls.partnership,
            academic_year=cls.start_academic_year,
        )
        PartnershipYearFactory(
            partnership=cls.partnership,
            academic_year=cls.from_academic_year,
        )
        PartnershipYearFactory(
            partnership=cls.partnership,
            academic_year=cls.end_academic_year,
        )
        cls.url = resolve_url('partnerships:update', pk=cls.partnership.pk)

        cls.subtype1 = PartnershipSubtypeFactory()
        cls.subtype2 = PartnershipSubtypeFactory()
        cls.data = {
            'comment': '',
            'partner': cls.partner.pk,
            'partner_entities': [cls.partner_entity.entity_id],
            'supervisor': cls.user.person.pk,
            'ucl_entity': cls.ucl_university_labo.pk,
            'start_date': cls.start_academic_year.start_date,
            'end_date': cls.end_academic_year.end_date,
            'year-is_sms': True,
            'year-is_smp': False,
            'year-is_sta': True,
            'year-is_stt': False,
            'year-education_fields': [cls.education_field.pk],
            'year-education_levels': [cls.education_level.pk],
            'year-entities': [],
            'year-offers': [],
            'year-funding_type': FundingTypeFactory().pk,
            'missions': [
                PartnershipMissionFactory().pk,
                PartnershipMissionFactory().pk,
            ],
            'subtype': cls.subtype1.pk,
        }
Exemplo n.º 52
0
 def get_success_url(self):
     next_url = self.request.GET.get('next') or 'profile'
     return resolve_url(next_url)
Exemplo n.º 53
0
 def get_success_url(self):
     return resolve_url('blogs:blog_list')
Exemplo n.º 54
0
    def test_create(self):
        url = resolve_url('gw_app:add')
        self._client_get_check_login(url)

        # test success create nas
        r = self.client.post(url,
                             data={
                                 'title': 'Test success nas',
                                 'ip_address': '192.168.8.10',
                                 'ip_port': 1254,
                                 'auth_login': '******',
                                 'auth_passw': '_',
                                 'nas_type': 'mktk'
                             })
        self.assertEqual(r.status_code, 302)
        msg = r.cookies.get('messages')
        self.assertIn('New NAS has been created', msg.output())
        NASModel.objects.get(title='Test success nas',
                             ip_address='192.168.8.10',
                             ip_port=1254,
                             auth_login='******',
                             auth_passw='_')

        # test error ip_port big range
        r = self.client.post(url,
                             data={
                                 'title': 'New nas',
                                 'ip_address': '192.168.8.13',
                                 'ip_port': 8755877855798,
                                 'auth_login': '******',
                                 'auth_passw': '_'
                             })
        self.assertEqual(r.status_code, 200)
        self.assertFormError(
            response=r,
            form='form',
            field='ip_port',
            errors='Ensure this value is less than or equal to %(limit_value)s.'
            % {'limit_value': 32767})

        # test get request
        r = self.client.get(url)
        self.assertEqual(r.status_code, 200)

        # test error duplicates title
        r = self.client.post(url,
                             data={
                                 'title': 'Test success nas',
                                 'ip_address': '192.168.8.14',
                                 'ip_port': 2543,
                                 'auth_login': '******',
                                 'auth_passw': '_v'
                             })
        self.assertEqual(r.status_code, 200)
        self.assertFormError(
            response=r,
            form='form',
            field='title',
            errors='%(model_name)s with this %(field_label)s already exists.' %
            {
                'model_name': NASModel._meta.verbose_name,
                'field_label': NASModel._meta.get_field('title').verbose_name
            })

        # test error duplicates default
        r = self.client.post(url,
                             data={
                                 'title': 'New again nas',
                                 'ip_address': '192.168.8.15',
                                 'ip_port': 9873,
                                 'auth_login': '******',
                                 'auth_passw': '_v',
                                 'default': True
                             })
        self.assertEqual(r.status_code, 200)
        self.assertFormError(response=r,
                             form='form',
                             field='default',
                             errors='Can be only one default gateway')

        # test error duplicates ip_address
        r = self.client.post(url,
                             data={
                                 'title': 'New again nas2',
                                 'ip_address': '192.168.8.10',
                                 'ip_port': 1254,
                                 'auth_login': '******',
                                 'auth_passw': '_v'
                             })
        self.assertEqual(r.status_code, 200)
        self.assertFormError(
            response=r,
            form='form',
            field='ip_address',
            errors='%(model_name)s with this %(field_label)s already exists.' %
            {
                'model_name': NASModel._meta.verbose_name,
                'field_label':
                NASModel._meta.get_field('ip_address').verbose_name
            })
Exemplo n.º 55
0
def url(viewname, *args, **kwargs):
    # TODO: automatycznie tutaj ustawiać bierzący namespace
    return resolve_url(viewname, *args, **kwargs)
Exemplo n.º 56
0
 def get_success_url(self):
     return resolve_url('blogs:one_blog', pk=self.object.blog.id)
Exemplo n.º 57
0
 def get_success_url(self):
     return resolve_url('accounts:user_detail', pk=self.kwargs['pk'])
Exemplo n.º 58
0
 def get_success_url(self):
     return resolve_url('blogs:one_post', pk=self.object.pk, blog_id = self.object.blog.id)
Exemplo n.º 59
0
 def test_domain(self):
     """
     Tests that passing a domain to ``resolve_url`` returns the same domain.
     """
     self.assertEqual(resolve_url('example.com'), 'example.com')
Exemplo n.º 60
0
 def location(self, obj):
     return resolve_url('sensei_app:user_detail', pk=obj.pk)