Python django.contrib.auth 模块,logout() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.auth.logout()

项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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()
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return redirect('import_:login')


# class StaffRoleRequiredMixin(AccessMixin):
#     def dispatch(self, request, *args, **kwargs):
#         url_name = self.request.resolver_match.url_name
#         for group in self.request.user.groups.all():
#             for staff_permission in group.staffpermission_set.all():
#                 if staff_permission.allowed_url_name == 'all' \
#                         or staff_permission.allowed_url_name == url_name:
#                     return super(StaffRoleRequiredMixin, self).dispatch(
#                             request, *args, **kwargs)
#
#         return HttpResponse("Not Allowed.", status=403)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def complete(request, *args, **kwargs):
    """Override this method so we can force user to be logged out."""
    # This view overrides the behavior of the default 'complete' endpoint in order
    # to log out the user first. If user 1 is already logged in and user 2 is logged in on edX,
    # social_core can get confused on which User should get the SocialAuth object.
    if request.user.is_authenticated():
        key = "{}_state".format(request.backend.name)
        backend_state = request.session.get(key)
        logout(request)
        # logout will clear the session, this preserves the backend session state. We need to do
        # this so that this workflow will validate correctly (EdxOrgOAuth2.validate_state).
        # key is the same one used in EdxOrgAuth2.get_session_state().
        request.session[key] = backend_state

    # Continue with social_core pipeline
    social_complete_rtn = social_complete(request, *args, **kwargs)

    # Update redis cache if user had invalid credentials
    if request.user.is_authenticated():
        con = get_redis_connection("redis")
        user_key = FIELD_USER_ID_BASE_STR.format(request.user.id)
        con.hdel(CACHE_KEY_FAILURE_NUMS_BY_USER, user_key)
        con.srem(CACHE_KEY_FAILED_USERS_NOT_TO_UPDATE, request.user.id)

    return social_complete_rtn
项目:network-pulse-api    作者:mozilla    | 项目源码 | 文件源码
def start_auth(request):
    """
    Specific login call for logging in through another front-end
    """
    original_url = request.GET.get('original_url', False)

    if original_url is False:
        new_state_value(request)
        original_url = request.session['state']

    else:
        request.session['state'] = original_url

    # record the url to send the user back to post-authentication
    # in the state value.
    FlowHandler.get_flow().params['state'] = original_url
    auth_url = FlowHandler.get_flow().step1_get_authorize_url()
    return redirect(auth_url)


# API Route: /logout (immediately directs to /)
项目:cetusshop    作者:icetusorg    | 项目源码 | 文件源码
def process_request(self, request):
        #logger.debug('Come into the process_request.')
        myuser = request.user
        if myuser.is_anonymous():
            #????????
            #path = request.path
            pass
        else:
            #logger.debug('%s' % myuser)
            path = request.path_info.lstrip('/')
            #logger.debug('path:%s' % path)
            if not path=='user/login/':
                if myuser.is_active == False:
                    #logger.info('%s user has been banned. Reject!' % request.user.email)
                    from django.contrib import auth
                    auth.logout(request)
                    return HttpResponseRedirect(settings.LOGIN_URL)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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()
项目:lykchat    作者:lykops    | 项目源码 | 文件源码
def wx_logout(self, request):
        '''
        ??????
        '''
        is_login = self._check_userlogin(request)
        if not is_login :
            return HttpResponseRedirect(reverse('login'))

        self._init_param(request)
        if self.status == 222 :
            wx_logout = Logout(self.session_info_dict)
            wx_logout.logout()
            self.session_info_dict['status'] = self.status = 444
            display_html_dict = self._displayhtml(request)
            return render(request, self.display_html, display_html_dict) 
        else :
            return HttpResponseRedirect(reverse('index'))
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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()
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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()
项目:SOMS    作者:qitan    | 项目源码 | 文件源码
def logout(request, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Logs out the user and displays 'You are logged out' message.
    """
    Message.objects.create(type=u'????', user=request.user, action=u'????', action_ip=UserIP(request),
                           content='???? %s' % request.user)
    auth_logout(request)

    if next_page is not None:
        next_page = resolve_url(next_page)

    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)

        return HttpResponseRedirect('/')
项目:MusicQR    作者:tangziyi001    | 项目源码 | 文件源码
def register(request):
    if request.method == 'GET':
        return render(request,'musician/register.html')
    else:
        try:
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password']
            user = User.objects.create_user(username, email, password)
            user.save()
            login_user = authenticate(username=username, password=password)
            login(request, login_user)
            return redirect('/musician/artist/'+username+'/')
        except Exception as e:
            messages.add_message(request, messages.ERROR, "Registration Failed: Duplicated Username")
            logging.exception("message")
            return redirect('/musician/register/')

# logout user
项目:adminset    作者:guohongze    | 项目源码 | 文件源码
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'GET' and request.GET.has_key('next'):
        next_page = request.GET['next']
    else:
        next_page = '/'
    if next_page == "/accounts/logout/":
        next_page = '/'
    if request.method == "POST":
        form = LoginUserForm(request, data=request.POST)
        if form.is_valid():
            auth.login(request, form.get_user())
            return HttpResponseRedirect(request.POST['next'])
    else:
        form = LoginUserForm(request)
    kwargs = {
        'request': request,
        'form':  form,
        'next': next_page,
    }
    return render(request, 'accounts/login.html', kwargs)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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()
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
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()
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def logout(request):
    # log the user out and go to login page
    auth.logout(request)
    return HttpResponseRedirect(reverse('login'))
项目:III    作者:collinmutembei    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/")
项目:django-shibauth-rit    作者:audiolion    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        # Log the user out.
        auth.logout(self.request)
        # Set session key that middleware will use to force
        # Shibboleth reauthentication.
        self.request.session[getattr(settings, "SHIBAUTH_LOGOUT_SESSION_KEY")] = True
        # Get logout redirect url
        next = getattr(settings, "SHIBAUTH_LOGOUT_REDIRECT_URL")
        requests.post('https://shibboleth.main.ad.rit.edu/logout.html', data='')
        return redirect(next)
项目:OpsManage    作者:welliamcao    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/login')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    messages.success(request, _('You have been successfully logged out.'))
    return redirect(settings.LOGIN_REDIRECT_URL)
项目:tecken    作者: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
            )
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return redirect('staff:login')
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return redirect('lecturer:login')
项目:hiwi-stunden    作者:janisstreib    | 项目源码 | 文件源码
def delete_profile(request):
    if request.method == 'POST':
        user = request.user
        user.delete()
        return redirect("/logout")
    return redirect("/profile")
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return redirect("/")
#----

#----
项目:sso    作者:hhr66    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    response = HttpResponseRedirect('/')
    response.delete_cookie('sso_token', domain=settings.SESSION_COOKIE_DOMAIN)
    return response

#@login_required
项目:BCFM-Reserve    作者:BlaiseRoberts    | 项目源码 | 文件源码
def logout_user(request):
    """
    This method is invoked to logout the user and redirect them to the index
     ---Arguments---
    None
    Author: Blaise Roberts
    """

    # Since we know the user is logged in, we can now just log them out.
    logout(request)

    # Take the user back to the homepage. 
    return HttpResponseRedirect(reverse('reserve:index'))
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/login')
项目:registration    作者: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!
            pass
    return resp
项目:wifi-attendance    作者:elvinzeng    | 项目源码 | 文件源码
def get(self, request):
        if request.user.is_authenticated:
            auth.logout(request)
            return redirect("/")
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:API-Manager    作者:OpenBankProject    | 项目源码 | 文件源码
def get_redirect_url(self, *args, **kwargs):
        logout(self.request)
        if 'obp' in self.request.session:
            del self.request.session['obp']
        return reverse('home')
项目:ava-website    作者:ava-project    | 项目源码 | 文件源码
def get(self, request, **kwargs):
        Device.objects.filter(user=request.user).delete()
        logout(request)
        return JsonResponse({'data': 'You have been logged out'})
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        #import pdb; pdb.set_trace()
        coop_worker = False
        if self.request.user.is_authenticated():
            user = self.request.user
            try:
                agent = user.agent.agent
                if agent.is_coop_worker():
                    coop_worker = True
            except:
                pass       
            auth.logout(self.request)
        return redirect(self.get_redirect_url(is_worker=coop_worker))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        AccountDeletion.mark(self.request.user)
        auth.logout(self.request)
        messages.add_message(
            self.request,
            self.messages["account_deleted"]["level"],
            self.messages["account_deleted"]["text"] % {
                "expunge_hours": settings.ACCOUNT_DELETION_EXPUNGE_HOURS,
            }
        )
        return redirect(self.get_redirect_url())
项目:steemprojects.com    作者:noisy    | 项目源码 | 文件源码
def social_user(strategy, backend, uid, user=None, *args, **kwargs):
    provider = backend.name
    social = backend.strategy.storage.user.get_social_auth(provider, uid)
    if social:
        if user and social.user != user:
            merge = strategy.request_data().get('merge')
            if merge is None:
                current_partial = kwargs.get('current_partial')

                return strategy.redirect(
                    '{url}?partial_token={token}'.format(
                        url=reverse("merging_accounts"),
                        token=current_partial.token,
                    )
                )
            else:
                if merge == 'yes':
                    user.profile.merge(social.user.profile)
                    social.user = user

                else:
                    # logout user and login
                    from django.contrib.auth import logout
                    logout(strategy.request)
                    raise AuthCanceled__RedirectToLogin(backend.name)

        elif not user:
            user = social.user

    return {'social': social,
            'user': user,
            'is_new': user is None,
            'new_association': social is None}
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        if self.request.user.is_authenticated():
            auth.logout(self.request)
        return redirect(self.get_redirect_url())
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        AccountDeletion.mark(self.request.user)
        auth.logout(self.request)
        messages.add_message(
                self.request,
                self.messages["account_deleted"]["level"],
                self.messages["account_deleted"]["text"].format(**{
                    "expunge_hours": settings.ACCOUNT_DELETION_EXPUNGE_HOURS,
                })
        )
        return redirect(self.get_redirect_url())
项目:LDERP    作者:Ignoramuss    | 项目源码 | 文件源码
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password'],
                email=form.cleaned_data['email'],
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name']
            )
            # message = 'Registered successfully'
            return redirect('home')
    else:
        form = RegistrationForm()

    return render(request, 'home.html', {'form':LoginForm(),'signup_form':form})


# def register_success(request):
#     return render( request,  'home.html', {'message': 'Registered successfully'} )


# def logout_page(request):
#     logout(request)
#     return HttpResponseRedirect('/logout')
项目:betterself    作者: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)
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:django-authlib    作者:matthiask    | 项目源码 | 文件源码
def logout(request):
    auth.logout(request)
    messages.success(
        request,
        _('You have been signed out.'))
    return redirect('login')
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def delete_list(self, request = None, **kwargs):
        """Log out this session"""
        auth.logout(request)
项目:network-pulse-api    作者:mozilla    | 项目源码 | 文件源码
def force_logout(request):
    """
    An explicit logout route.
    """
    user = request.user
    if user.is_authenticated:
        logout(request)
    return HttpResponse("User is no longer logged in.")
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def logout_view(request):
    logout(request)
    return redirect('kpi-logout')
项目:wanblog    作者:wanzifa    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request)