Optionally handles the login and logout actions by intercepting the HTTP calls to the
{@link #getLoginPath()} and {@link #getLogoutPath()} URIs.
432868
@Override
    protected int beforeHandle(final Request request, final Response response)
    {
        this.log.debug("Calling isLoggingIn");
        if(this.isLoggingIn(request, response))
        {
            this.log.debug("Calling isLoggingIn");
            this.login(request, response);
            if(this.authenticate(request, response))
            {
                this.log.debug("Calling authenticated");
                this.authenticated(request, response);
            }
            // we redirect after logging in for all cases, so stop here and return the 303 response
            return Filter.STOP;
        }
        else if(this.isLoggingOut(request, response))
        {
            this.log.debug("Calling logout");
            return this.logout(request, response);
        }
        
        // log.info("calling super.beforeHandle");
        // return super.beforeHandle(request, response);
        
        this.log.debug("Calling copy of Authenticator beforeHandle");
        
        if(
        // FIXME: How important is multiAuthenticating to this class?
        // isMultiAuthenticating() ||
        !request.getClientInfo().isAuthenticated())
        {
            this.log.debug("Calling authenticate");
            if(this.authenticate(request, response))
            {
                this.log.debug("Calling authenticated");
                return this.authenticated(request, response);
            }
            else if(this.isOptional())
            {
                this.log.debug("Authentication isOptional, returning CONTINUE with Status.SUCCESS_OK");
                response.setStatus(Status.SUCCESS_OK);
                return Filter.CONTINUE;
            }
            else
            {
                this.log.debug("Calling unauthenticated");
                return this.unauthenticated(request, response);
            }
        }
        else
        {
            this.log.debug("Returning CONTINUE");
            return Filter.CONTINUE;
        }
    }
1079164
private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory, NativeWebRequest request) {
		List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection);
		if (userIds.size() == 0) {
			ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection);
			sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt);
			return redirect(signUpUrl);
		} else if (userIds.size() == 1) {
			usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection);
			String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request);
			postSignIn(connectionFactory, connection, (WebRequest) request);
			return originalUrl != null ? redirect(originalUrl) : redirect(postSignInUrl);
		} else {
			return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "multiple_users").build().toString());
		}
	}
249889
public login logout() throws Exception
	{
		if(sessionid == null || sessionid.length() <= 0)
			throw new Exception("User not logged-in");
		
		login logout_obj = new login();
		logout_obj.set_sessionid(sessionid);
		
		login result = login.delete(this, logout_obj);
		sessionid = null;
		user_name = null;
		password = null;
		return result;
	}
374279
public void logout() throws Exception {
    Api apiResult = getActionResult("logout", "", null, null);
    if (apiResult != null) {
      userid = null;
      // FIXME check apiResult
    }
    if (cookies != null) {
      cookies.clear();
      cookies = null;
    }
  }
383911
def process_exception(self, request, exception):
        

        if isinstance(exception, CasTicketException):
            do_logout(request)
            # This assumes that request.path requires authentication.
            return HttpResponseRedirect(request.path)
        else:
            return None
430613
@Override
  public boolean loginHandler(String target, HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (! isLoginTarget(target)) {
      return false;
    }

    if (isPageRequest(request)) {
      sendLoginForm(request, response);
    } else {
      ServletUtils.sendResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "Access denied. Please login.");
    }
    return true;
  }
118893
protected function execLogout()
    {
        $logoutService = $this->authFactory->newLogoutService();
        $auth = $this->authFactory->newInstance();
        $logoutService->logout($auth);
        $this->httpResponse = $this->httpResponse->withHeader('Location', '/' . $this->configuration['areas'][AREA]['authentication']['loginURL']);
    }
576923
def _handle_login(opt, action, bz):
    
    is_login_command = (action == 'login')

    do_interactive_login = (is_login_command or
        opt.login or opt.username or opt.password)
    username = getattr(opt, "pos_username", None) or opt.username
    password = getattr(opt, "pos_password", None) or opt.password

    try:
        if do_interactive_login:
            if bz.url:
                print("Logging into %s" % urlparse(bz.url)[1])
            bz.interactive_login(username, password,
                    restrict_login=opt.restrict_login)
    except bugzilla.BugzillaError as e:
        print(str(e))
        sys.exit(1)

    if opt.ensure_logged_in and not bz.logged_in:
        print("--ensure-logged-in passed but you aren't logged in to %s" %
            bz.url)
        sys.exit(1)

    if is_login_command:
        msg = "Login successful."
        if bz.cookiefile or bz.tokenfile:
            msg = "Login successful, token cache updated."

        print(msg)
        sys.exit(0)
455122
public void logout() {
        if (loginContext != null) {
            try {
                loginContext.logout();
                if (logoutLogger.isDebugEnabled()) {
                    logoutLogger.debug("[ws/#" + getId() + "] Logout successful.");
                }
            } catch (LoginException e) {
                logoutLogger.trace("[ws/#" + getId() + "] Exception occurred logging out of this WebSocket session.", e);
            }
        }
        loginContext = null;
    }
545792
@Override
	public LoginResult handle(HttpServletRequest request, HttpServletResponse response) {
		String userName = request.getRemoteUser();
		if (userName != null && userName.trim().length() > 0) {
			LoginResult result;
			ContainerPreAuthCallbackHandler callbackHandler = new ContainerPreAuthCallbackHandler(userName);
			result = authenticate(callbackHandler, null);
			//result = new LoginResult(LoginResult.STATUS_SUCCEEDED);
			logger.debug("handle() called for user '" + userName 
					+ "', LoginResult.statues=" + result.getStatus() 
					+ ", LoginResult.subject=" + result.getSubject());
			
			/*
			logger.debug("using PlainTextCallbackHandler");
			CredentialsCallbackHandler callbackHandler2 = new PlainTextCallbackHandler(userName, "Test123Test".toCharArray());
			authenticate(callbackHandler2, SecuritySupportBase.DEFAULT_JAAS_LOGIN_CHAIN);
			LoginResult result = new LoginResult(LoginResult.STATUS_SUCCEEDED);
			*/
			return result;
		}else{
			logger.debug("handle() called but the user has not been authenticated by the container.");
		}
		return LoginResult.NOT_HANDLED;
	}
614943
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest httpRequest,
                       HttpResponse httpResponse)
         throws IOException
    {
        if (!isStarted())
            return;
        
        // Handle TRACE
        if (HttpRequest.__TRACE.equals(httpRequest.getMethod()))
        {
            handleTrace(httpRequest,httpResponse);
            return;
        }

        // Look for existing request/response objects (from enterScope call)
        ServletHttpRequest request = (ServletHttpRequest) httpRequest.getWrapper();
        ServletHttpResponse response = (ServletHttpResponse) httpResponse.getWrapper();
        if (request==null)
        {
            // Not in ServletHttpContext, but bumble on anyway
            request = new ServletHttpRequest(this,pathInContext,httpRequest);
            response = new ServletHttpResponse(request,httpResponse);
            httpRequest.setWrapper(request);
            httpResponse.setWrapper(response);
        }
        else
        {
            request.recycle(this,pathInContext);
            response.recycle();
        }
        
        // Look for the servlet
        Map.Entry servlet=getHolderEntry(pathInContext);
        ServletHolder servletHolder=servlet==null?null:(ServletHolder)servlet.getValue();
        if(log.isDebugEnabled())log.debug("servlet="+servlet);
            
        try
        {
            // Adjust request paths
            if (servlet!=null)
            {
                String servletPathSpec=(String)servlet.getKey(); 
                request.setServletPaths(PathMap.pathMatch(servletPathSpec,pathInContext),
                                        PathMap.pathInfo(servletPathSpec,pathInContext),
                                        servletHolder);
            }
            
            // Handle the session ID
            request.setRequestedSessionId(pathParams);
            HttpSession session=request.getSession(false);
            if (session!=null)
                ((SessionManager.Session)session).access();
            if(log.isDebugEnabled())log.debug("session="+session);
            
            // Do that funky filter and servlet thang!
            if (servletHolder!=null)
                dispatch(pathInContext,request,response,servletHolder, Dispatcher.__REQUEST);
        }
        catch(Exception e)
        {
            log.debug(LogSupport.EXCEPTION,e);
            
            Throwable th=e;
            while (th instanceof ServletException)
            {
                log.warn(LogSupport.EXCEPTION, th);
                Throwable cause=((ServletException)th).getRootCause();
                if (cause==th || cause==null)
                    break;
                th=cause;
            }
            
            if (th instanceof HttpException)
                throw (HttpException)th;
            if (th instanceof EOFException)
                throw (IOException)th;
            else if (log.isDebugEnabled() || !( th instanceof java.io.IOException))
            {
                if (_contextLog!=null)
                {
                    if (th instanceof RuntimeException) 
                        _contextLog.error(httpRequest.getURI()+": ",th);
                    else
                        _contextLog.warn(httpRequest.getURI()+": ",th);
                }
                
                if(log.isDebugEnabled())
                {
                    if (th instanceof RuntimeException) 
                        log.error(httpRequest.getURI()+": ",th);
                    else
                        log.warn(httpRequest.getURI()+": ",th);
                    log.debug(httpRequest);
                }
            }
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
                if (th instanceof UnavailableException)
                {
                    UnavailableException ue = (UnavailableException)th;
                    if (ue.isPermanent())
                        response.sendError(HttpResponse.__404_Not_Found,e.getMessage());
                    else
                        response.sendError(HttpResponse.__503_Service_Unavailable,e.getMessage());
                }
                else
                    response.sendError(HttpResponse.__500_Internal_Server_Error,e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling "+th);
        }
        catch(Error e)
        {   
            log.warn("Error for "+httpRequest.getURI(),e);
            if(log.isDebugEnabled())log.debug(httpRequest);
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
                response.sendError(HttpResponse.__500_Internal_Server_Error,
                                   e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling ",e);
        }
        finally
        {
            if (servletHolder!=null && response!=null)
            {
                response.complete();
            }
        }
    }
1304901
def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL):
    
    django_logout(request)
    return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
90986
public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (!common.checkPost(request, response)) return;

        String username = request.getParameter("username");
        if (username == null) {
            response.sendError(400, "Missing field \"username\".");
            return;
        }

        String usernameError = checkUsername(username);
        if (usernameError != null) {
            response.sendError(400, "Invalid username: " + usernameError);
            return;
        }

        // Lookup user.  If the user doesn't exist, create it.
        User user;
        synchronized (common.userDb) {
            user = common.userDb.get(username);
            if (user == null) {
                user = new User();
                user.username = username;
                user.dropboxAccessToken = null;

                common.userDb.put(user.username, user);
                common.saveUserDb();
            }
        }

        request.getSession().setAttribute("logged-in-username", user.username);
        response.sendRedirect("/");
    }
472746
private AuthenticationResult handleRedirect(HttpServletRequest req,
                                                HttpServletResponse res,
                                                WebRequest webRequest) {
        AuthenticationResult authResult;

        String loginURL = getFormLoginURL(req, webRequest, webAppSecurityConfig);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "form login URL: " + loginURL);
        }

        authResult = new AuthenticationResult(AuthResult.REDIRECT, loginURL);

        if (allowToAddCookieToResponse(webAppSecurityConfig, req)) {
            postParameterHelper.save(req, res, authResult);
            ReferrerURLCookieHandler referrerURLHandler = webAppSecurityConfig.createReferrerURLCookieHandler();
//            referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req));
            Cookie c = referrerURLHandler.createReferrerURLCookie(ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME, getReqURL(req), req);
            authResult.setCookie(c);
        }

        return authResult;
    }
651598
public void login(final LoginHandler handler, int forceLogin) {
        HMSAgentLog.i("login:handler=" + StrUtils.objDesc(handler) + "  forceLogin=" + forceLogin);
        this.handler = handler;
        this.forceLogin = forceLogin;
        this.retryTimes = MAX_RETRY_TIMES;
        connect();
    }
628742
public function logoutAction()
    {
        $possibleRedirectionUri = $this->backendRedirectionService->getAfterLogoutRedirectionUri($this->request);
        parent::logoutAction();
        switch ($this->request->getFormat()) {
            case 'json':
                $this->view->assign('value', ['success' => true]);
            break;
            default:
                if ($possibleRedirectionUri !== null) {
                    $this->redirectToUri($possibleRedirectionUri);
                }
                $this->addFlashMessage('Successfully logged out', 'Logged out', Message::SEVERITY_NOTICE, [], 1318421560);
                $this->redirect('index');
        }
    }
1299500
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        Resource resource = getResource(pathInContext);
        if (resource==null)
            return;

        // Is the method allowed?
        if (!isMethodAllowed(request.getMethod()))
        {
            if(log.isDebugEnabled())log.debug("Method not allowed: "+request.getMethod());
            if (resource.exists())
            {
                setAllowHeader(response);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            return;
        }

        // Handle the request
        try
        {
            if(log.isDebugEnabled())log.debug("PATH="+pathInContext+" RESOURCE="+resource);
            
            // check filename
            String method=request.getMethod();
            if (method.equals(HttpRequest.__GET) ||
                method.equals(HttpRequest.__POST) ||
                method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, pathParams, resource);  
            else if (method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(response, pathInContext);
            else if (method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__TRACE))
                handleTrace(request, response);
            else
            {
                if(log.isDebugEnabled())log.debug("Unknown action:"+method);
                // anything else...
                try{
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                }
                catch(Exception e) {LogSupport.ignore(log,e);}
            }
        }
        catch(IllegalArgumentException e)
        {
            LogSupport.ignore(log,e);
        }
        finally
        {
            if (resource!=null && !(resource instanceof CachedResource))
                resource.release();
        }
    }