// Login logs the user into a Teleport cluster by talking to a Teleport proxy.
//
// If 'activateKey' is true, saves the received session cert into the local
// keystore (and into the ssh-agent) for future use.
//
333352
func (tc *TeleportClient) Login(ctx context.Context, activateKey bool) (*Key, error) {
	// Ping the endpoint to see if it's up and find the type of authentication
	// supported.
	pr, err := tc.credClient.Ping(ctx, tc.AuthConnector)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// If version checking was requested and the server advertises a minimum version.
	if tc.CheckVersions && pr.MinClientVersion != "" {
		if err := utils.CheckVersions(teleport.Version, pr.MinClientVersion); err != nil {
			return nil, trace.Wrap(err)
		}
	}

	// preserve original web proxy host that could have
	webProxyHost, _ := tc.WebProxyHostPort()

	if err := tc.applyProxySettings(pr.Proxy); err != nil {
		return nil, trace.Wrap(err)
	}

	// generate a new keypair. the public key will be signed via proxy if client's
	// password+OTP are valid
	key, err := NewKey()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	var response *auth.SSHLoginResponse

	switch pr.Auth.Type {
	case teleport.Local:
		response, err = tc.localLogin(ctx, pr.Auth.SecondFactor, key.Pub)
		if err != nil {
			return nil, trace.Wrap(err)
		}
	case teleport.OIDC:
		response, err = tc.ssoLogin(ctx, pr.Auth.OIDC.Name, key.Pub, teleport.OIDC)
		if err != nil {
			return nil, trace.Wrap(err)
		}

		// in this case identity is returned by the proxy
		tc.Username = response.Username
		if tc.localAgent != nil {
			tc.localAgent.username = response.Username
		}
	case teleport.SAML:
		response, err = tc.ssoLogin(ctx, pr.Auth.SAML.Name, key.Pub, teleport.SAML)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		// in this case identity is returned by the proxy
		tc.Username = response.Username
		if tc.localAgent != nil {
			tc.localAgent.username = response.Username
		}
	case teleport.Github:
		response, err = tc.ssoLogin(ctx, pr.Auth.Github.Name, key.Pub, teleport.Github)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		// in this case identity is returned by the proxy
		tc.Username = response.Username
		if tc.localAgent != nil {
			tc.localAgent.username = response.Username
		}
	default:
		return nil, trace.BadParameter("unsupported authentication type: %q", pr.Auth.Type)
	}

	// extract the new certificate out of the response
	key.Cert = response.Cert
	key.TLSCert = response.TLSCert
	key.ProxyHost = webProxyHost

	if len(response.HostSigners) <= 0 {
		return nil, trace.BadParameter("bad response from the server: expected at least one certificate, got 0")
	}
	key.ClusterName = response.HostSigners[0].ClusterName

	if activateKey {
		// save the list of CAs client trusts to ~/.tsh/known_hosts
		err = tc.localAgent.AddHostSignersToCache(response.HostSigners)
		if err != nil {
			return nil, trace.Wrap(err)
		}

		// save the list of TLS CAs client trusts
		err = tc.localAgent.SaveCerts(response.HostSigners)
		if err != nil {
			return nil, trace.Wrap(err)
		}

		// save the cert to the local storage (~/.tsh usually):
		_, err = tc.localAgent.AddKey(key)
		if err != nil {
			return nil, trace.Wrap(err)
		}

		// Connect to the Auth Server of the main cluster
		// and fetch the known hosts for this cluster.
		if err := tc.UpdateTrustedCA(ctx, key.ClusterName); err != nil {
			return nil, trace.Wrap(err)
		}
	}
	return key, nil
}
1049846
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
	session, _ := a.cookiejar.Get(req, "auth")
	if session.Values["username"] == u {
		return mkerror("already authenticated")
	}
	if user, err := a.backend.User(u); err == nil {
		verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))
		if verify != nil {
			a.addMessage(rw, req, "Invalid username or password.")
			return mkerror("password doesn't match")
		}
	} else {
		a.addMessage(rw, req, "Invalid username or password.")
		return mkerror("user not found")
	}
	session.Values["username"] = u
	session.Save(req, rw)

	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	if flashes := redirectSession.Flashes(); len(flashes) > 0 {
		dest = flashes[0].(string)
	}
	http.Redirect(rw, req, dest, http.StatusSeeOther)
	return nil
}
763068
func (k *KeybaseServiceBase) LoggedIn(ctx context.Context, name string) error {
	k.log.CDebugf(ctx, "Current session logged in: %s", name)
	// Since we don't have the whole session, just clear the cache and
	// repopulate it.  The `CurrentSession` call executes the "logged
	// in" flow.
	k.setCachedCurrentSession(idutil.SessionInfo{})
	const sessionID = 0
	_, err := k.CurrentSession(ctx, sessionID)
	if err != nil {
		k.log.CDebugf(ctx, "Getting current session failed when %s is logged "+
			"in, so pretending user has logged out: %v",
			name, err)
		if k.config != nil {
			serviceLoggedOut(ctx, k.config)
		}
		return nil
	}

	return nil
}
70892
func (c LoginClient) LoginWithPaperKey(ctx context.Context, sessionID int) (err error) {
	__arg := LoginWithPaperKeyArg{SessionID: sessionID}
	err = c.Cli.Call(ctx, "keybase.1.login.loginWithPaperKey", []interface{}{__arg}, nil)
	return
}
1089601
func (c *Client) Login() (string, error) {
	payload := &Request{
		Action: "login",
		Param: &LoginRequest{
			CustomerNumber:  c.customerNumber,
			APIKey:          c.apiKey,
			APIPassword:     c.apiPassword,
			ClientRequestID: "",
		},
	}

	var responseData LoginResponse
	err := c.doRequest(payload, &responseData)
	if err != nil {
		return "", fmt.Errorf("loging error: %v", err)
	}

	return responseData.APISessionID, nil
}
1117060
func (j *AuthMux) Login() http.Handler {
	conf := j.Provider.Config()
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// We are creating a token with an encoded random string to prevent CSRF attacks
		// This token will be validated during the OAuth callback.
		// We'll give our users 10 minutes from this point to type in their
		// oauth2 provider's password.
		// If the callback is not received within 10 minutes, then authorization will fail.
		csrf := randomString(32) // 32 is not important... just long
		now := j.Now()

		// This token will be valid for 10 minutes.  Any chronograf server will
		// be able to validate this token.
		p := Principal{
			Subject:   csrf,
			IssuedAt:  now,
			ExpiresAt: now.Add(TenMinutes),
		}
		token, err := j.Tokens.Create(r.Context(), p)

		// This is likely an internal server error
		if err != nil {
			j.Logger.
				WithField("component", "auth").
				WithField("remote_addr", r.RemoteAddr).
				WithField("method", r.Method).
				WithField("url", r.URL).
				Error("Internal authentication error: ", err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		url := conf.AuthCodeURL(string(token), oauth2.AccessTypeOnline)
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	})
}
353590
func (u *User) GetLogin() string {
	if u == nil || u.Login == nil {
		return ""
	}
	return *u.Login
}
422986
func (web *webAPIHandlers) Login(r *http.Request, args *LoginArgs, reply *LoginRep) error {
	token, err := authenticateWeb(args.Username, args.Password)
	if err != nil {
		return toJSONError(err)
	}

	reply.Token = token
	reply.UIVersion = browser.UIVersion
	return nil
}
109124
func (c *IdentityClient) Login(ctx context.Context, email, password string) (string, error) {
	lt, err := c.Tokens.CreateLogin(ctx, &LoginTokenRequest{Email: email})
	if err != nil {
		return "", err
	}

	salt, err := base64.NewFromString(lt.Salt)
	if err != nil {
		return "", err
	}

	_, pk, err := deriveKeypair(password, salt)
	if err != nil {
		return "", err
	}

	sig := sign(pk, lt.Token).String()
	at, err := c.Tokens.CreateAuth(ctx, "Bearer "+lt.Token, &AuthTokenRequest{
		Type:          "auth",
		LoginTokenSig: sig,
	})
	if err != nil {
		return "", err
	}

	return at.Body.Token, nil
}
71313
func (auth *Auth) Login(query *models.LoginUserQuery) error {
	// connect to ldap server
	if err := auth.Dial(); err != nil {
		return err
	}
	defer auth.conn.Close()

	// perform initial authentication
	if err := auth.initialBind(query.Username, query.Password); err != nil {
		return err
	}

	// find user entry & attributes
	user, err := auth.searchForUser(query.Username)
	if err != nil {
		return err
	}

	auth.log.Debug("Ldap User found", "info", spew.Sdump(user))

	// check if a second user bind is needed
	if auth.requireSecondBind {
		err = auth.secondBind(user, query.Password)
		if err != nil {
			return err
		}
	}

	grafanaUser, err := auth.GetGrafanaUserFor(query.ReqContext, user)
	if err != nil {
		return err
	}

	query.User = grafanaUser
	return nil
}
707309
func (handle *ContextHandle) Login(session mPkcs11.SessionHandle) error {

	handle.lock.RLock()
	defer handle.lock.RUnlock()

	if handle.pin == "" {
		return errors.New("No PIN set")
	}
	err := handle.ctx.Login(session, mPkcs11.CKU_USER, handle.pin)
	if err != nil && err != mPkcs11.Error(mPkcs11.CKR_USER_ALREADY_LOGGED_IN) {
		return errors.Errorf("Login failed [%s]", err)
	}
	return nil
}
415438
func (i *Invitation) GetLogin() string {
	if i == nil || i.Login == nil {
		return ""
	}
	return *i.Login
}
40625
func (bridge *Bridge) Login(username string) error {
	uri := fmt.Sprintf("/api/%s", username)
	_, _, err := bridge.Get(uri)
	if err != nil {
		return err
	}
	bridge.Username = username
	return nil
}
777397
func (tc *TeleportClient) Logout() error {
	err := tc.localAgent.DeleteKey()
	if err != nil {
		return trace.Wrap(err)
	}

	return nil
}
1067496
func (m *MWApi) Login(username, password string) error {
	if username == "" {
		return errors.New("empty username supplied")
	}
	if password == "" {
		return errors.New("empty password supplied")
	}
	m.username = username
	m.password = password

	query := map[string]string{
		"action":     "login",
		"lgname":     m.username,
		"lgpassword": m.password,
	}

	if m.Domain != "" {
		query["lgdomain"] = m.Domain
	}

	body, err := m.API(query)
	if err != nil {
		return err
	}

	var response outerLogin
	err = json.Unmarshal(body, &response)
	if err != nil {
		return err
	}

	if response.Login.Result == "Success" {
		return nil
	} else if response.Login.Result != "NeedToken" {
		return errors.New("Error logging in: " + response.Login.Result)
	}

	// Need to use the login token
	query["lgtoken"] = response.Login.Token

	body, err = m.API(query)
	if err != nil {
		return err
	}

	err = json.Unmarshal(body, &response)
	if err != nil {
		return err
	}

	if response.Login.Result != "Success" {
		return errors.New("Error logging in: " + response.Login.Result)
	}
	return nil
}
314922
func Login(controller string, username string, password string, sslVerify bool) error {
	u, err := url.Parse(controller)

	if err != nil {
		return err
	}

	controllerURL, err := chooseScheme(*u)
	httpClient := client.CreateHTTPClient(sslVerify)

	if err != nil {
		return err
	}

	if err = client.CheckConnection(httpClient, controllerURL); err != nil {
		return err
	}

	if username == "" {
		fmt.Print("username: ")
		fmt.Scanln(&username)
	}

	if password == "" {
		fmt.Print("password: ")
		password, err = readPassword()
		fmt.Println()

		if err != nil {
			return err
		}
	}

	c := &client.Client{ControllerURL: controllerURL, SSLVerify: sslVerify, HTTPClient: httpClient}

	return doLogin(c, username, password)
}
1024968
func (m *MMClient) Login() error {
	// check if this is a first connect or a reconnection
	firstConnection := true
	if m.WsConnected {
		firstConnection = false
	}
	m.WsConnected = false
	if m.WsQuit {
		return nil
	}
	b := &backoff.Backoff{
		Min:    time.Second,
		Max:    5 * time.Minute,
		Jitter: true,
	}

	// do initialization setup
	if err := m.initClient(firstConnection, b); err != nil {
		return err
	}

	if err := m.doLogin(firstConnection, b); err != nil {
		return err
	}

	if err := m.initUser(); err != nil {
		return err
	}

	if m.Team == nil {
		validTeamNames := make([]string, len(m.OtherTeams))
		for i, t := range m.OtherTeams {
			validTeamNames[i] = t.Team.Name
		}
		return fmt.Errorf("Team '%s' not found in %v", m.Credentials.Team, validTeamNames)
	}

	m.wsConnect()

	return nil
}