// LogoutHandler allows users to log out by clearing all
// values from their session
182408
func LogoutHandler(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	err := session.Save()
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	c.String(http.StatusOK, "You have successfully logged out.")
}
318340
func Logout(nextURL, basepath string, routes AuthRoutes) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		principal, err := getPrincipal(ctx)
		if err != nil {
			http.Redirect(w, r, path.Join(basepath, nextURL), http.StatusTemporaryRedirect)
			return
		}
		route, ok := routes.Lookup(principal.Issuer)
		if !ok {
			http.Redirect(w, r, path.Join(basepath, nextURL), http.StatusTemporaryRedirect)
			return
		}
		http.Redirect(w, r, route.Logout, http.StatusTemporaryRedirect)
	}
}
209302
func (c *Client) wsOutHandler() {
out:
	for {
		// Send any messages ready for send until the client is
		// disconnected closed.
		select {
		case msg := <-c.sendChan:
			err := c.wsConn.WriteMessage(websocket.TextMessage, msg)
			if err != nil {
				c.Disconnect()
				break out
			}

		case <-c.disconnectChan():
			break out
		}
	}

	// Drain any channels before exiting so nothing is left waiting around
	// to send.
cleanup:
	for {
		select {
		case <-c.sendChan:
		default:
			break cleanup
		}
	}
	c.wg.Done()
	log.Tracef("RPC client output handler done for %s", c.config.Host)
}
927202
func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler {
	// Create options...
	return NewTokenHandlerWithOptions(TokenHandlerOptions{
		Transport:   transport,
		Credentials: creds,
		Scopes: []Scope{
			RepositoryScope{
				Repository: scope,
				Actions:    actions,
			},
		},
	})
}
1303599
func (rl *RevelLogger) SetHandler(h LogHandler) {
	rl.Logger.SetHandler(callHandler(h.Log))
}
26623
func SignedInUser(ctx *macaron.Context, sess session.Store) (_ *models.User, isBasicAuth bool, isTokenAuth bool) {
	if !models.HasEngine {
		return nil, false, false
	}

	uid, isTokenAuth := SignedInID(ctx, sess)

	if uid <= 0 {
		if setting.Service.EnableReverseProxyAuth {
			webAuthUser := ctx.Req.Header.Get(setting.ReverseProxyAuthUser)
			if len(webAuthUser) > 0 {
				u, err := models.GetUserByName(webAuthUser)
				if err != nil {
					if !errors.IsUserNotExist(err) {
						log.Error(2, "GetUserByName: %v", err)
						return nil, false, false
					}

					// Check if enabled auto-registration.
					if setting.Service.EnableReverseProxyAutoRegister {
						u := &models.User{
							Name:     webAuthUser,
							Email:    gouuid.NewV4().String() + "@localhost",
							Passwd:   webAuthUser,
							IsActive: true,
						}
						if err = models.CreateUser(u); err != nil {
							// FIXME: should I create a system notice?
							log.Error(2, "CreateUser: %v", err)
							return nil, false, false
						} else {
							return u, false, false
						}
					}
				}
				return u, false, false
			}
		}

		// Check with basic auth.
		baHead := ctx.Req.Header.Get("Authorization")
		if len(baHead) > 0 {
			auths := strings.Fields(baHead)
			if len(auths) == 2 && auths[0] == "Basic" {
				uname, passwd, _ := tool.BasicAuthDecode(auths[1])

				u, err := models.UserLogin(uname, passwd, -1)
				if err != nil {
					if !errors.IsUserNotExist(err) {
						log.Error(2, "UserLogin: %v", err)
					}
					return nil, false, false
				}

				return u, true, false
			}
		}
		return nil, false, false
	}

	u, err := models.GetUserByID(uid)
	if err != nil {
		log.Error(2, "GetUserByID: %v", err)
		return nil, false, false
	}
	return u, false, isTokenAuth
}
101848
func onLogout(cf *CLIConf) {
	// Extract all clusters the user is currently logged into.
	active, available, err := client.Status("", "")
	if err != nil {
		utils.FatalError(err)
		return
	}
	profiles := append([]*client.ProfileStatus{}, available...)
	if active != nil {
		profiles = append(profiles, active)
	}

	// Extract the proxy name.
	proxyHost, _, err := net.SplitHostPort(cf.Proxy)
	if err != nil {
		proxyHost = cf.Proxy
	}

	switch {
	// Proxy and username for key to remove.
	case proxyHost != "" && cf.Username != "":
		tc, err := makeClient(cf, true)
		if err != nil {
			utils.FatalError(err)
			return
		}

		// Remove keys for this user from disk and running agent.
		err = tc.Logout()
		if err != nil {
			if trace.IsNotFound(err) {
				fmt.Printf("User %v already logged out from %v.\n", cf.Username, proxyHost)
				os.Exit(1)
			}
			utils.FatalError(err)
			return
		}

		// Get the address of the active Kubernetes proxy to find AuthInfos,
		// Clusters, and Contexts in kubeconfig.
		clusterName, _ := tc.KubeProxyHostPort()
		if tc.SiteName != "" {
			clusterName = fmt.Sprintf("%v.%v", tc.SiteName, clusterName)
		}

		// Remove Teleport related entries from kubeconfig.
		log.Debugf("Removing Teleport related entries for '%v' from kubeconfig.", clusterName)
		err = kubeclient.RemoveKubeconifg(tc, clusterName)
		if err != nil {
			utils.FatalError(err)
			return
		}

		fmt.Printf("Logged out %v from %v.\n", cf.Username, proxyHost)
	// Remove all keys.
	case proxyHost == "" && cf.Username == "":
		// The makeClient function requires a proxy. However this value is not used
		// because the user will be logged out from all proxies. Pass a dummy value
		// to allow creation of the TeleportClient.
		cf.Proxy = "dummy:1234"
		tc, err := makeClient(cf, true)
		if err != nil {
			utils.FatalError(err)
			return
		}

		// Remove Teleport related entries from kubeconfig for all clusters.
		for _, profile := range profiles {
			log.Debugf("Removing Teleport related entries for '%v' from kubeconfig.", profile.Cluster)
			err = kubeclient.RemoveKubeconifg(tc, profile.Cluster)
			if err != nil {
				utils.FatalError(err)
				return
			}
		}

		// Remove all keys from disk and the running agent.
		err = tc.LogoutAll()
		if err != nil {
			utils.FatalError(err)
			return
		}

		fmt.Printf("Logged out all users from all proxies.\n")
	default:
		fmt.Printf("Specify --proxy and --user to remove keys for specific user ")
		fmt.Printf("from a proxy or neither to log out all users from all proxies.\n")
	}
}
806217
func (c *LoggerCollection) SetHandler(re *regexp.Regexp, handler Handler) {
	c.mtx.Lock()
	defer c.mtx.Unlock()

	if re == nil {
		c.handler = handler
	}
	for name, logger := range c.loggers {
		if re == nil || re.MatchString(name) {
			logger.setHandler(handler)
		}
	}
}
539523
func (m *MMClient) Logout() error {
	m.logger.Debugf("logout as %s (team: %s) on %s", m.Credentials.Login, m.Credentials.Team, m.Credentials.Server)
	m.WsQuit = true
	m.WsClient.Close()
	m.WsClient.UnderlyingConn().Close()
	if strings.Contains(m.Credentials.Pass, model.SESSION_COOKIE_TOKEN) {
		m.logger.Debug("Not invalidating session in logout, credential is a token")
		return nil
	}
	_, resp := m.Client.Logout()
	if resp.Error != nil {
		return resp.Error
	}
	return nil
}
912789
func (tc *TeleportClient) LogoutAll() error {
	err := tc.localAgent.DeleteKeys()
	if err != nil {
		return trace.Wrap(err)
	}
	return nil
}
573806
func (service *Service) Logout(w http.ResponseWriter, request *http.Request) {
	service.SetLoggedInUser(w, request, "")
	sessions.Save(request, w)
	http.Redirect(w, request, "", http.StatusFound)
}
417722
func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
	handler := &tokenHandler{
		transport:     options.Transport,
		creds:         options.Credentials,
		offlineAccess: options.OfflineAccess,
		forceOAuth:    options.ForceOAuth,
		clientID:      options.ClientID,
		scopes:        options.Scopes,
		clock:         realClock{},
		logger:        options.Logger,
	}

	return handler
}
569813
func (service *Service) GetLoggedInUser(request *http.Request, w http.ResponseWriter) (username string, err error) {
	authenticatedSession, err := service.GetSession(request, SessionInteractive, "authenticatedsession")
	if err != nil {
		log.Error(err)
		return
	}
	err = authenticatedSession.Save(request, w)
	if err != nil {
		log.Error(err)
		return
	}
	savedusername := authenticatedSession.Values["username"]
	if savedusername != nil {
		username, _ = savedusername.(string)
	}
	return
}
691960
func (mock *HTTPMock) SetHandler(config rest.Config, handler http.Handler) (httpServer io.Closer, err error) {
	mock.handler = handler
	return &doNothingCloser{}, nil
}
1055690
func (c *Client) Logout(sessionID string) error {
	payload := &Request{
		Action: "logout",
		Param: &LogoutRequest{
			CustomerNumber:  c.customerNumber,
			APIKey:          c.apiKey,
			APISessionID:    sessionID,
			ClientRequestID: "",
		},
	}

	err := c.doRequest(payload, nil)
	if err != nil {
		return fmt.Errorf("logout error: %v", err)
	}

	return nil
}
387319
func (g *GlobalContext) LogoutSelfCheck(ctx context.Context) error {
	mctx := NewMetaContext(ctx, g)
	uid := g.ActiveDevice.UID()
	if uid.IsNil() {
		mctx.Debug("LogoutSelfCheck: no uid")
		return nil
	}
	deviceID := g.ActiveDevice.DeviceID()
	if deviceID.IsNil() {
		mctx.Debug("LogoutSelfCheck: no device id")
		return nil
	}

	arg := APIArg{
		Endpoint: "selfcheck",
		Args: HTTPArgs{
			"uid":       S{Val: uid.String()},
			"device_id": S{Val: deviceID.String()},
		},
		SessionType: APISessionTypeREQUIRED,
	}
	res, err := g.API.Post(mctx, arg)
	if err != nil {
		return err
	}

	logout, err := res.Body.AtKey("logout").GetBool()
	if err != nil {
		return err
	}

	mctx.Debug("LogoutSelfCheck: should log out? %v", logout)
	if logout {
		mctx.Debug("LogoutSelfCheck: logging out...")
		return g.Logout(mctx.Ctx())
	}

	return nil
}
798383
func (d *DNSProvider) logout() (*response, error) {
	if d.config.AuthSid == "" {
		return nil, fmt.Errorf("already logged out")
	}

	response, err := d.postRequest("logout", url.Values{})
	if err == nil {
		d.config.AuthSid = ""
	}
	return response, err
}