我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.auth.logout()。
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()
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)
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
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 /)
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)
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'))
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('/')
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
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)
def logout(request): # log the user out and go to login page auth.logout(request) return HttpResponseRedirect(reverse('login'))
def logout(request): auth.logout(request) return HttpResponseRedirect("/")
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)
def logout(request): auth.logout(request) return HttpResponseRedirect('/login')
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)
def logout(request): auth.logout(request) messages.success(request, _('You have been successfully logged out.')) return redirect(settings.LOGIN_REDIRECT_URL)
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 )
def logout(request): auth.logout(request) return redirect('staff:login')
def logout(request): auth.logout(request) return redirect('lecturer:login')
def delete_profile(request): if request.method == 'POST': user = request.user user.delete() return redirect("/logout") return redirect("/profile")
def logout(request): auth.logout(request) return redirect("/") #---- #----
def logout(request): auth.logout(request) response = HttpResponseRedirect('/') response.delete_cookie('sso_token', domain=settings.SESSION_COOKIE_DOMAIN) return response #@login_required
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'))
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
def get(self, request): if request.user.is_authenticated: auth.logout(request) return redirect("/")
def get_redirect_url(self, *args, **kwargs): logout(self.request) if 'obp' in self.request.session: del self.request.session['obp'] return reverse('home')
def get(self, request, **kwargs): Device.objects.filter(user=request.user).delete() logout(request) return JsonResponse({'data': 'You have been logged out'})
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))
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())
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}
def post(self, *args, **kwargs): if self.request.user.is_authenticated(): auth.logout(self.request) return redirect(self.get_redirect_url())
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())
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')
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)
def logout(request): auth.logout(request) messages.success( request, _('You have been signed out.')) return redirect('login')
def delete_list(self, request = None, **kwargs): """Log out this session""" auth.logout(request)
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.")
def logout_view(request): logout(request) return redirect('kpi-logout')