// Login tries to authenticate to the aerospike server. Depending on the server configuration and ClientPolicy,
// the session information will be returned.
18229
func (lcmd *loginCommand) login(policy *ClientPolicy, conn *Connection, hashedPass []byte) error {
	switch policy.AuthMode {
	case AuthModeExternal:
		lcmd.writeHeader(_LOGIN, 3)
		lcmd.writeFieldStr(_USER, policy.User)
		lcmd.writeFieldBytes(_CREDENTIAL, hashedPass)
		lcmd.writeFieldStr(_CLEAR_PASSWORD, policy.Password)
	case AuthModeInternal:
		lcmd.writeHeader(_LOGIN, 2)
		lcmd.writeFieldStr(_USER, policy.User)
		lcmd.writeFieldBytes(_CREDENTIAL, hashedPass)
	default:
		return NewAerospikeError(ResultCode(INVALID_COMMAND), "Invalid ClientPolicy.AuthMode.")
	}

	lcmd.writeSize()

	var deadline time.Time
	if policy.LoginTimeout > 0 {
		deadline = time.Now().Add(policy.Timeout)
	}
	conn.SetTimeout(deadline, policy.LoginTimeout)

	if _, err := conn.Write(lcmd.dataBuffer[:lcmd.dataOffset]); err != nil {
		return err
	}

	if _, err := conn.Read(lcmd.dataBuffer, _HEADER_SIZE); err != nil {
		return err
	}

	result := lcmd.dataBuffer[_RESULT_CODE] & 0xFF
	if result != 0 {
		if int(result) == _INVALID_COMMAND {
			// New login not supported.  Try old authentication.
			return lcmd.authenticateInternal(conn, policy.User, hashedPass)
		}
		return NewAerospikeError(ResultCode(result))
	}

	// Read session token.
	sz := Buffer.BytesToInt64(lcmd.dataBuffer, 0)
	receiveSize := int((sz & 0xFFFFFFFFFFFF) - int64(_HEADER_REMAINING))
	fieldCount := int(lcmd.dataBuffer[11] & 0xFF)

	if receiveSize <= 0 || receiveSize > len(lcmd.dataBuffer) || fieldCount <= 0 {
		return NewAerospikeError(ResultCode(result), "Node failed to retrieve session token")
	}

	if len(lcmd.dataBuffer) < receiveSize {
		lcmd.dataBuffer = make([]byte, receiveSize)
	}

	_, err := conn.Read(lcmd.dataBuffer, receiveSize)
	if err != nil {
		Logger.Debug("Error reading data from connection for login command: %s", err.Error())
		return err
	}

	lcmd.dataOffset = 0
	for i := 0; i < fieldCount; i++ {
		mlen := int(Buffer.BytesToUint32(lcmd.dataBuffer, lcmd.dataOffset))
		lcmd.dataOffset += 4
		id := lcmd.dataBuffer[lcmd.dataOffset]
		lcmd.dataOffset++
		mlen--

		switch id {
		case _SESSION_TOKEN:
			lcmd.SessionToken = lcmd.dataBuffer[lcmd.dataOffset : lcmd.dataOffset+mlen]
		case _SESSION_TTL:
			// Subtract 60 seconds from TTL so client session expires before server session.
			seconds := int(Buffer.BytesToUint32(lcmd.dataBuffer, lcmd.dataOffset) - 60)

			if seconds > 0 {
				lcmd.SessionExpiration = time.Now().Add(time.Duration(seconds) * time.Second)
			} else {
				Logger.Warn("Invalid session TTL: %d", seconds)
			}
		}

		lcmd.dataOffset += mlen
	}

	if lcmd.SessionToken == nil {
		return NewAerospikeError(ResultCode(result), "Node failed to retrieve session token")
	}
	return nil
}
692764
func (s *Salesforce) login() error {
	if s.Username == "" || s.Password == "" {
		return errors.New("missing username or password")
	}

	body := fmt.Sprintf(`<?xml version="1.0" encoding="utf-8"?>
		<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
		  xmlns:urn="urn:enterprise.soap.sforce.com">
		  <soapenv:Body>
			<urn:login>
			  <urn:username>%s</urn:username>
			  <urn:password>%s%s</urn:password>
			</urn:login>
		  </soapenv:Body>
		</soapenv:Envelope>`,
		s.Username, s.Password, s.SecurityToken)

	loginEndpoint, err := s.getLoginEndpoint()
	if err != nil {
		return err
	}

	req, err := http.NewRequest(http.MethodPost, loginEndpoint, strings.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "text/xml")
	req.Header.Add("SOAPAction", "login")

	resp, err := s.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	soapFault := struct {
		Code    string `xml:"Body>Fault>faultcode"`
		Message string `xml:"Body>Fault>faultstring"`
	}{}

	err = xml.Unmarshal(respBody, &soapFault)
	if err != nil {
		return err
	}

	if soapFault.Code != "" {
		return fmt.Errorf("login failed: %s", soapFault.Message)
	}

	loginResult := struct {
		ServerURL      string `xml:"Body>loginResponse>result>serverUrl"`
		SessionID      string `xml:"Body>loginResponse>result>sessionId"`
		OrganizationID string `xml:"Body>loginResponse>result>userInfo>organizationId"`
	}{}

	err = xml.Unmarshal(respBody, &loginResult)
	if err != nil {
		return err
	}

	s.SessionID = loginResult.SessionID
	s.OrganizationID = loginResult.OrganizationID
	s.ServerURL, err = url.Parse(loginResult.ServerURL)

	return err
}
1238208
func (connection *VSphereConnection) login(ctx context.Context, client *vim25.Client) error {
	m := session.NewManager(client)
	connection.credentialsLock.Lock()
	defer connection.credentialsLock.Unlock()

	signer, err := connection.Signer(ctx, client)
	if err != nil {
		return err
	}

	if signer == nil {
		klog.V(3).Infof("SessionManager.Login with username %q", connection.Username)
		return m.Login(ctx, neturl.UserPassword(connection.Username, connection.Password))
	}

	klog.V(3).Infof("SessionManager.LoginByToken with certificate %q", connection.Username)

	header := soap.Header{Security: signer}

	return m.LoginByToken(client.WithHeader(ctx, header))
}
229429
func (s *SessionClient) UserLogin(ctx context.Context, email, passphrase string) error {
	// Package up login credentials for the user
	login := apitypes.UserLogin{
		Email:    email,
		Password: passphrase,
	}

	rawLogin, err := json.Marshal(login)
	if err != nil {
		return err
	}

	return performLogin(ctx, s, "user", rawLogin)
}
255924
func (c *ServerConn) Login(user, password string) error {
	code, message, err := c.cmd(-1, "USER %s", user)
	if err != nil {
		return err
	}

	switch code {
	case StatusLoggedIn:
	case StatusUserOK:
		_, _, err = c.cmd(StatusLoggedIn, "PASS %s", password)
		if err != nil {
			return err
		}
	default:
		return errors.New(message)
	}

	// Switch to binary mode
	if _, _, err = c.cmd(StatusCommandOK, "TYPE I"); err != nil {
		return err
	}

	// Switch to UTF-8
	err = c.setUTF8()

	return err
}
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
}
866294
func (m *Multiplexer) Login(entity names.Tag, model names.ModelTag, fromController bool, userData string) {
	mapConcurrent(func(o Observer) { o.Login(entity, model, fromController, userData) }, m.observers)
}
284361
func (ctn *Connection) login(sessionToken []byte) error {
	// need to authenticate
	if ctn.node.cluster.clientPolicy.RequiresAuthentication() {
		policy := &ctn.node.cluster.clientPolicy

		switch policy.AuthMode {
		case AuthModeExternal:
			var err error
			command := newLoginCommand(ctn.dataBuffer)
			if sessionToken == nil {
				err = command.login(&ctn.node.cluster.clientPolicy, ctn, ctn.node.cluster.Password())
			} else {
				err = command.authenticateViaToken(&ctn.node.cluster.clientPolicy, ctn, sessionToken)
			}

			if err != nil {
				if ctn.node != nil {
					atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1)
				}
				// Socket not authenticated. Do not put back into pool.
				ctn.Close()
				return err
			}

			if command.SessionToken != nil {
				ctn.node._sessionToken.Store(command.SessionToken)
				ctn.node._sessionExpiration.Store(command.SessionExpiration)
			}

			return nil

		case AuthModeInternal:
			return ctn.authenticateFast(policy.User, ctn.node.cluster.Password())
		}
	}

	return nil
}
770921
func (ip *Interpreter) login(args []string) {
	uid, err := ip.Backend.LoginUser(args[0], args[1])
	if err == nil {
		ip.Server.Stats.Login++
	} else {
		ip.Server.Stats.FailedLogin++
	}
	ip.intResponder(uid, err)
}
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
}
481197
func (service *Service) LogInfo(msg string, keyvals ...interface{}) {
	LogInfo(service.Context, msg, keyvals...)
}
415438
func (i *Invitation) GetLogin() string {
	if i == nil || i.Login == nil {
		return ""
	}
	return *i.Login
}
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
}
1286486
func (c *CommitAuthor) GetLogin() string {
	if c == nil || c.Login == nil {
		return ""
	}
	return *c.Login
}
879703
func (sp *ServiceProvider) InitiateLogin(w http.ResponseWriter) error {
	acsURL, _ := url.Parse(sp.AcsURL)

	binding := HTTPRedirectBinding
	bindingLocation := sp.GetSSOBindingLocation(binding)
	if bindingLocation == "" {
		binding = HTTPPostBinding
		bindingLocation = sp.GetSSOBindingLocation(binding)
	}

	req, err := sp.MakeAuthenticationRequest(bindingLocation)
	if err != nil {
		return err
	}

	relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
	state := jwt.New(jwt.GetSigningMethod("HS256"))
	claims := state.Claims.(jwt.MapClaims)
	claims["id"] = req.ID
	signedState, err := state.SignedString(sp.cookieSecret())
	if err != nil {
		return err
	}

	http.SetCookie(w, &http.Cookie{
		Name:     fmt.Sprintf("saml_%s", relayState),
		Value:    signedState,
		MaxAge:   int(MaxIssueDelay.Seconds()),
		HttpOnly: false,
		Path:     acsURL.Path,
	})

	if binding == HTTPRedirectBinding {
		redirectURL := req.Redirect(relayState)
		w.Header().Add("Location", redirectURL.String())
		w.WriteHeader(http.StatusFound)
		return nil
	}
	if binding == HTTPPostBinding {
		w.Header().Set("Content-Security-Policy", ""+
			"default-src; "+
			"script-src 'sha256-D8xB+y+rJ90RmLdP72xBqEEc0NUatn7yuCND0orkrgk='; "+
			"reflected-xss block; "+
			"referrer no-referrer;")
		w.Header().Add("Content-type", "text/html")
		w.Write([]byte(`<!DOCTYPE html><html><body>`))
		w.Write(req.Post(relayState))
		w.Write([]byte(`</body></html>`))
		return nil
	}
	panic("not reached")
}
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
}
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)
	})
}