django.contrib.auth.logout - python examples

Here are the examples of the python api django.contrib.auth.logout taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : api.py
Copyright MIT License
Author : CodeForPoznan
@api_view(['POST'])
@permission_clastes((AllowAny,))
def logout_view(request):
    """REST API logout view."""
    if request.user.is_authenticated():
        logout(request)
        messages.success(request, 'Wylogowano')
        return Response({}, status=status.HTTP_200_OK)
    return Response({}, status=status.HTTP_400_BAD_REQUEST)

3 View Complete Implementation : views.py
Copyright MIT License
Author : nikolak
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return redirect('home')

        logout(request)
        messages.success(request, "You are now logged out!")
        return redirect('home')

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : drexly
@deprecate_current_app
def logout_then_login(request, login_url=None, extra_context=None):
    """
    Logs out the user if they are logged in. Then redirects to the log-in page.
    """
    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return logout(request, login_url, extra_context=extra_context)

3 View Complete Implementation : views.py
Copyright MIT License
Author : HackAssistant
def logout(request):
    auth.logout(request)
    messages.success(request, 'Successfully logged out!')
    resp = HttpResponseRedirect(reverse('account_login'))
    c_domain = getattr(settings, 'LOGGED_IN_COOKIE_DOMAIN', None) or getattr(settings, 'HACKATHON_DOMAIN', None)
    c_key = getattr(settings, 'LOGGED_IN_COOKIE_KEY', None)
    if c_domain and c_key:
        try:
            resp.delete_cookie(c_key, domain=c_domain)
        except:
            # We don't care if this is not deleted, we are being cool here!
            past
    return resp

3 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : OTA-Insight
    @pytest.mark.django_db
    def test_requires_authentication(self):
        request = get_logged_in_request()

        logout(request)
        response = SSOInitView.as_view()(request)
        astert isinstance(response, HttpResponseRedirect)
        astert response.url == '/accounts/login/?next='

3 View Complete Implementation : api_views.py
Copyright MIT License
Author : dkarchmer
    def get(self, request, format=None):
        """
        Update thumbnail and tiny file field
        """

        data_dic = {"Error":"GET not supported for this command"}

        logout(request)
        mystatus = status.HTTP_400_BAD_REQUEST

        return Response(data_dic, status=mystatus)

3 View Complete Implementation : auth.py
Copyright MIT License
Author : CodeForPoznan
def logout(request):
    """Logout view.

    :param request: WSGIRequest instance
    """
    auth.logout(request)
    return redirect(settings.ANGULAR_ROOT)

3 View Complete Implementation : client.py
Copyright Apache License 2.0
Author : drexly
    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()

3 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : ScrappyZhang
    def get(self, request):
        """退出"""
        # 清除用户登录状态,内置的logout函数会自动清除当前session
        logout(request)

        # 跳转到登录
        return redirect(reverse('user:login'))

3 View Complete Implementation : auth.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def get(self, request):
        next = request.GET.get("next", reverse("home"))

        if request.GET.get("logout", None) is not None:
            logout(request)
            # need to redirect to 'auth' so that the user is set to anonymous via the middleware
            return redirect("auth")
        else:
            return render(request, "login.htm", {"auth_failed": False, "next": next})

3 View Complete Implementation : session_map.py
Copyright GNU General Public License v3.0
Author : IMGIITRoorkee
    @staticmethod
    def delete_session_map(request):
        """
        Delete the SessionMap instance astociated with the request and clear the
        astociated session from the session store
        :param request: the request that is to be stripped of authentication
        """

        # Get the additional information from the relational database
        session_key = request.session.session_key
        session_map = SessionMap.objects.get(session_key=session_key)
        session_map.delete()

        # Delete the cookie and flush the session
        logout(request)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : NullArray
def login_user(request):
    logout(request)
    username = pastword = ''
    if request.POST:
        username = request.POST['username']
        pastword = request.POST['pastword']

        user = authenticate(username=username, pastword=pastword)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(main)
    return render_to_response('login.html', (request))

3 View Complete Implementation : auth_index.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def delete(self, request, *args, **kwargs):
        """
        Logout the Authenticated User
        `````````````````````````````

        Deauthenticate the currently active session.
        """
        logout(request._request)
        request.user = AnonymousUser()
        return Response(status=204)

3 View Complete Implementation : views.py
Copyright MIT License
Author : whitesmith
    def delete(self, request, *args, **kwargs):
        current_pw = request.POST.get("current_pastword", "")
        if authenticate(username=request.user.username, pastword=current_pw):
            response = super().delete(request, *args, **kwargs)
            logout(request)
            messages.success(request,
                             _('Account deleted successfully.'
                               ' We hope you comeback soon.'))
            return response
        else:
            messages.error(request,
                           _('In order to delete the account you must provide'
                             ' the current pastword.'))
            return self.get(request, *args, **kwargs)

3 View Complete Implementation : logic.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def handle_email_change(request, email_address):
    request.user.email = email_address
    request.user.is_active = False
    request.user.confirmation_code = uuid.uuid4()
    request.user.save()

    context = {'user': request.user}
    message = render_template.get_message_content(request, context, 'user_email_change')
    notify_helpers.send_email_with_body_from_user(request, 'subject_user_email_change', request.user.email, message)

    logout(request)

3 View Complete Implementation : generics.py
Copyright MIT License
Author : sanoma
    def get(self, request, *args, **kwargs):
        # If the logout url is the login url, log the user out of the system
        if settings.LOGOUT_URL == settings.LOGIN_URL:
            logout(request)
        # Else redirect a logged in user to the homepage
        elif request.user.is_authenticated:
            return redirect("/")
        return super(LoginView, self).get(request, *args, **kwargs)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
def logout_then_login(request, login_url=None, current_app=None, extra_context=None):
    """
    Logs out the user if he is logged in. Then redirects to the log-in page.
    """
    if not login_url:
        login_url = settings.LOGIN_URL
    login_url = resolve_url(login_url)
    return logout(request, login_url, current_app=current_app, extra_context=extra_context)

3 View Complete Implementation : views.py
Copyright MIT License
Author : jeffshek
    def get_redirect_url(self, *args, **kwargs):
        """
        Logout user and redirect to target url.
        """
        if self.request.user.is_authenticated():
            logout(self.request)
        return super(SessionLogoutView, self).get_redirect_url(*args, **kwargs)

3 View Complete Implementation : views.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def post(self, request):
        """Log out the user."""
        logout_url = self.redirect_url

        if request.user.is_authenticated:
            # Check if a method exists to build the URL to log out the user
            # from the OP.
            logout_from_op = self.get_settings('OIDC_OP_LOGOUT_URL_METHOD', '')
            if logout_from_op:
                logout_url = import_string(logout_from_op)(request)

            # Log out the Django user if they were logged in.
            auth.logout(request)

        return HttpResponseRedirect(logout_url)

3 View Complete Implementation : views.py
Copyright MIT License
Author : othreecodes
def logout_user(request):
    logout(request)
    form = CustomUserCreationForm(request.POST or None)
    context = {
        "form": form,
    }
    return redirect('app:index')

3 View Complete Implementation : test_views.py
Copyright Apache License 2.0
Author : OTA-Insight
    @pytest.mark.django_db
    def test_requires_authentication(self):
        request = get_logged_in_request()
        logout(request)

        response = LoginProcessView.as_view()(request)
        astert isinstance(response, HttpResponseRedirect)
        astert response.url == '/accounts/login/?next='

3 View Complete Implementation : client.py
Copyright Apache License 2.0
Author : edisonlz
    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        UserModel = get_user_model()
        if self.session:
            request.session = self.session
            uid = self.session.get("_auth_user_id")
            if uid:
                request.user = UserModel._default_manager.get(pk=uid)
        else:
            request.session = engine.SessionStore()
        logout(request)

3 View Complete Implementation : mixins.py
Copyright MIT License
Author : MicroPyramid
    def dispatch(self, request, *args, **kwargs):
        user = self.request.user
        if user.is_authenticated():
            if user.is_active:
                return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
            else:
                logout(self.request)
        return redirect(reverse('django_simple_forum:topic_list'))

3 View Complete Implementation : client.py
Copyright MIT License
Author : bpgc-cte
    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()

3 View Complete Implementation : views_subscription.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
    @method_decorator(create_subscription_session)
    def dispatch(self, request, cs_session, *args, **kwargs):
        if Config.enable_registration() is False:
            raise Http404
        # logout if existing user is logged in
        if request.user.is_authenticated:
            logout(request)
            cs_session.clear()  # empty session object

        self.cs_session = cs_session
        self.object = self.cs_session.main_member
        return super().dispatch(request, *args, **kwargs)

3 View Complete Implementation : views.py
Copyright MIT License
Author : blackholll
    def get(self, request, *args, **kwargs):
        """
        注销
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        logout(request)
        return redirect('/manage')

3 View Complete Implementation : middleware.py
Copyright Mozilla Public License 2.0
Author : mozilla-services
    def process_request(self, request):
        if not request.user.is_active or not request.user.email:
            return
        cache_key = f"NotBlockedInAuth0Middleware:${request.user.id}"
        if cache.get(cache_key) is None:
            # We have to do the check
            if is_blocked_in_auth0(request.user.email):
                # oh my!
                request.user.is_active = False
                request.user.save()
                logger.warning(
                    f"User {request.user.email} is blocked in Auth0 "
                    f"and now made inactive"
                )
                auth.logout(request)
                raise PermissionDenied("User is blocked in Auth0 and made inactive.")
            else:
                logger.info(f"User {request.user.email} is NOT blocked in Auth0")
            cache.set(cache_key, True, settings.NOT_BLOCKED_IN_AUTH0_INTERVAL_SECONDS)

3 View Complete Implementation : api.py
Copyright Apache License 2.0
Author : c3nav
    @action(detail=False, methods=['post'])
    def logout(self, request, *args, **kwargs):
        # django-rest-framework doesn't do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        if not request.user.is_authenticated:
            return ParseError(_('Not logged in.'))

        logout(request)

        return Response({
            'detail': _('Logout successful.'),
            'csrf_token': csrf.get_token(request),
        })

3 View Complete Implementation : auth.py
Copyright GNU General Public License v2.0
Author : kiwitcms
@rpc_method(name='Auth.logout')
def logout(**kwargs):
    """
    .. function:: XML-RPC Auth.logout()

        Delete session information

        :return: None
    """
    # Get the current request
    request = kwargs.get(REQUEST_KEY)
    django.contrib.auth.logout(request)

3 View Complete Implementation : UserViewSet.py
Copyright GNU General Public License v3.0
Author : bioinformatics-ua
    @list_route(methods=['get'])
    def logout(self, request):
        '''
        Logs out a logged in user
        '''
        logout(request)

        return Response({'authenticated': False})

3 View Complete Implementation : client.py
Copyright MIT License
Author : rizwansoaib
    def logout(self):
        """Log out the user by removing the cookies and session object."""
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()

3 View Complete Implementation : views.py
Copyright MIT License
Author : NicolasLM
    def form_valid(self, form):
        self.request.user.um_profile.deletion_pending = True
        self.request.user.um_profile.save()
        tasks.tasks.schedule_at(
            'um:delete_user',
            now() + UM_DELETE_ACCOUNT_AFTER,
            self.request.user.id
        )
        logout(self.request)
        return super().form_valid(form)

3 View Complete Implementation : views.py
Copyright MIT License
Author : passuf
@login_required
@has_wunderlist
def reconnect(request):
    request.user.wunderlist.delete()
    logout(request)
    return redirect('wunderlist:auth')

3 View Complete Implementation : views.py
Copyright MIT License
Author : impak-finance
    def post(self, request):
        """ Processes POST requests. """
        logout_url = settings.LOGOUT_REDIRECT_URL or '/'

        # Log out the current user.
        if request.user.is_authenticated:
            try:
                logout_url = self.provider_end_session_url \
                    if oidc_rp_settings.PROVIDER_END_SESSION_ENDPOINT else logout_url
            except KeyError:  # pragma: no cover
                logout_url = logout_url
            auth.logout(request)

        # Redirects the user to the appropriate URL.
        return HttpResponseRedirect(logout_url)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : OTA-Insight
    def get(self, request, *args, **kwargs):
        if self.multifactor_is_valid(request):
            logger.debug('MultiFactor succeeded for %s' % request.user)
            html_response = request.session['saml_data']
            if html_response['type'] == 'POST':
                return HttpResponse(html_response['data'])
            else:
                return HttpResponseRedirect(html_response['data'])
        logger.debug(_("MultiFactor failed; %s will not be able to log in") % request.user)
        logout(request)
        raise PermissionDenied(_("MultiFactor authentication factor failed"))

3 View Complete Implementation : backends.py
Copyright MIT License
Author : pik-software
    def logout(self) -> HttpResponseRedirect:
        endpoint = self.oidc_config().get('end_session_endpoint')
        params = {'post_logout_redirect_uri':
                  self.strategy.build_absolute_uri(reverse('logout'))}
        id_token_hint = self.strategy.session_get('id_token_hint', None)
        if id_token_hint is not None:
            params['id_token_hint'] = id_token_hint

        logout(self.strategy.request)

        if endpoint is None:
            return HttpResponseRedirect(reverse('logout'))
        return HttpResponseRedirect(f'{endpoint}?{urlencode(params)}')

0 View Complete Implementation : logout.py
Copyright MIT License
Author : PacktPublishing
def page(request):
	logout(request)
	return render(request, 'en/public/logout.html')

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : logout.py
Copyright MIT License
Author : PacktPublishing
def page(request):
	logout(request)
	return render(request, 'en/public/logout.html')

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : passuf
def is_authenticated(view_func):
    """
    Checks if the current user is authenticated against Wunderlist and Habitica.
    If not, the user is redirected to the index page.
    """

    def _wrapped_view_func(request, *args, **kwargs):
        user = request.user

        if not hasattr(user, 'wunderlist'):
            return redirect('index')

        if not hasattr(user, 'habitica'):
            return redirect('index')

        w_api = user.wunderlist.get_api()
        h_api = user.habitica.get_api()

        # Test Wunderlist
        if not w_api.test_auth():
            user.wunderlist.delete()
            messages.error(request, _('Could not connect to Wunderlist. Please re-connect'))
            logout(request)
            return redirect('index')

        # Test Habitica
        if not h_api.get_status():
            messages.error(request, _('Habitica servers are currently not responding. Please try again later.'))
            return redirect('dashboard')
        if not h_api.test_auth():
            user.habitica.delete()
            messages.error(request, _('Could not connect to Habitica. Please re-connect.'))
            return redirect('dashboard')

        return view_func(request, *args, **kwargs)
    return _wrapped_view_func

0 View Complete Implementation : views.py
Copyright MIT License
Author : passuf
@login_required
def delete_account(request):
    user = request.user
    if request.method == 'POST':
        # Delete webhooks and Wunderlist token
        if hasattr(user, 'wunderlist'):
            for connection in user.connections.all():
                connection.deactivate()
            user.wunderlist.delete()

        # Delete Habitica token
        if hasattr(user, 'habitica'):
            user.habitica.delete()

        # Logout user
        logout(request)

        # Delete the user
        user.delete()

        messages.success(request, default.MESSAGE_DELETED_ACCOUNT)

        return redirect('index')

    return render(request, 'wunderhabit/delete_account.html')

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
@staff_member_required
@never_cache
def matrix(request):
    """
    gercek admin istedigi musterinin hesabina girer cikar!
    """
    id=request.REQUEST.get('id')
    suser=request.user
    backend=get_backends()[0]
    backend="%s.%s" % (backend.__module__, backend.__clast__.__name__)
    if request.user.is_superuser and id:
        musteri=User.objects.get(pk=id)
        if not musteri.is_superuser:
            musteri.backend=backend
            admin_id=request.user.id
#            log_it(admin_id,musteri, u'%s --> %s oldu!'%(request.user,musteri), kod=9)
            log.info('#%s %s kullanicisi #%s %s in yerine gecti.' % (suser.id, suser.username, id, musteri.username))
            auth.logout(request)
            auth.login(request, musteri)
            request.session['admin_id']=admin_id
        else:
            request.user.message_set.create(message=u'Super kullanici yerine geçmezsiniz!!!')
    else:
        request.user.message_set.create(message=u'Kimsenin yerine geçme yetkiniz yok!')
        return HttpResponseRedirect('/admin/places/profile/')
    return HttpResponseRedirect('/')

0 View Complete Implementation : logout.py
Copyright MIT License
Author : PacktPublishing
def page(request):
	logout(request)
	return render(request, 'en/public/logout.html')

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.add_message(request, messages.INFO,
                             "Logout successful!")
        return super().get(request, *args, **kwargs)

0 View Complete Implementation : views.py
Copyright MIT License
Author : passuf
@login_required
def logout_view(request):
    logout(request)
    messages.success(request, default.MESSAGE_LOGGED_OUT)
    return redirect('index')