// authenticate retrieves and then validates the user:password combination provided in
// the request header. Returns 'false' if the user has not successfully authenticated.
514165
func (b *basicAuth) authenticate(r *http.Request) bool {
	const basicScheme string = "Basic "

	if r == nil {
		return false
	}

	// In simple mode, prevent authentication with empty credentials if User is
	// not set. Allow empty passwords to support non-password use-cases.
	if b.opts.AuthFunc == nil && b.opts.User == "" {
		return false
	}

	// Confirm the request is sending Basic Authentication credentials.
	auth := r.Header.Get("Authorization")
	if !strings.HasPrefix(auth, basicScheme) {
		return false
	}

	// Get the plain-text username and password from the request.
	// The first six characters are skipped - e.g. "Basic ".
	str, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])
	if err != nil {
		return false
	}

	// Split on the first ":" character only, with any subsequent colons assumed to be part
	// of the password. Note that the RFC2617 standard does not place any limitations on
	// allowable characters in the password.
	creds := bytes.SplitN(str, []byte(":"), 2)

	if len(creds) != 2 {
		return false
	}

	givenUser := string(creds[0])
	givenPass := string(creds[1])

	// Default to Simple mode if no AuthFunc is defined.
	if b.opts.AuthFunc == nil {
		b.opts.AuthFunc = b.simpleBasicAuthFunc
	}

	return b.opts.AuthFunc(givenUser, givenPass, r)
}
844032
func (d *DummyMailstore) Authenticate(username string, password string) (User, error) {
	if username != "username" {
		return &DummyUser{}, errors.New("Invalid username. Use 'username'")
	}

	if password != "password" {
		return &DummyUser{}, errors.New("Invalid password. Use 'password'")
	}

	d.User.authenticated = true
	return d.User, nil
}
1117678
func (m *OAuth2Method) Authenticate(c context.Context, r *http.Request) (*auth.User, error) {
	if info.IsDevAppServer(c) {
		// On "dev_appserver", we verify OAuth2 tokens using Google's OAuth2
		// verification endpoint.
		//
		// It is slow as hell on "dev_appserver", but good enough for local manual
		// testing.
		devMethod := auth.GoogleOAuth2Method{
			Scopes: m.Scopes,
		}
		return devMethod.Authenticate(c, r)
	}

	header := r.Header.Get("Authorization")
	if header == "" || len(m.Scopes) == 0 {
		return nil, nil // this method is not applicable
	}

	// GetOAuthUser RPC is notoriously flaky. Do a bunch of retries on errors.
	var err error
	for attemp := 0; attemp < 4; attemp++ {
		var u *user.User
		u, err = user.CurrentOAuth(c, m.Scopes...)
		if err != nil {
			logging.Warningf(c, "oauth: failed to execute GetOAuthUser - %s", err)
			continue
		}
		if u == nil {
			return nil, nil
		}
		if u.ClientID == "" {
			return nil, fmt.Errorf("oauth: ClientID is unexpectedly empty")
		}
		id, idErr := identity.MakeIdentity("user:" + u.Email)
		if idErr != nil {
			return nil, idErr
		}
		return &auth.User{
			Identity:  id,
			Superuser: u.Admin,
			Email:     u.Email,
			ClientID:  u.ClientID,
		}, nil
	}
	return nil, transient.Tag.Apply(err)
}
1223699
func (session *Session) Validate() (err error) {
	if session.accessToken == "" && session.HttpClient == nil {
		err = fmt.Errorf("access token is not set")
		return
	}

	var result Result
	result, err = session.Api("/me", GET, Params{"fields": "id"})

	if err != nil {
		return
	}

	if f := result.Get("id"); f == nil {
		err = fmt.Errorf("invalid access token")
		return
	}

	return
}
1338028
func (a denyPasswordAuthenticator) AuthenticatePassword(ctx context.Context, username, password string) (*authenticator.Response, bool, error) {
	return nil, false, nil
}
784739
func (c *Client) authenticate(ctx context.Context, filter ...string) error {
	nonce := c.nonce.GetNonce()
	payload := "AUTH" + nonce
	sig, err := c.sign(payload)
	if err != nil {
		return err
	}
	s := &SubscriptionRequest{
		Event:       "auth",
		APIKey:      c.apiKey,
		AuthSig:     sig,
		AuthPayload: payload,
		AuthNonce:   nonce,
		Filter:      filter,
		SubID:       nonce,
	}
	if c.cancelOnDisconnect {
		s.DMS = DMSCancelOnDisconnect
	}
	c.subscriptions.add(s)

	if err := c.asynchronous.Send(ctx, s); err != nil {
		return err
	}
	c.Authentication = PendingAuthentication

	return nil
}
11003
func (client *SSHClient) Validate() error {
	if client.Creds.SSHUser == "" {
		return ErrInvalidUsername
	}

	if client.Creds.SSHPrivateKey == "" && client.Creds.SSHPassword == "" {
		return ErrInvalidAuth
	}

	return nil
}
598663
func (fn AuthenticatorFunc) Authenticate(username, password, otp string) (*Session, error) {
	return fn(username, password, otp)
}
1243005
func (d *S3Driver) Authenticate(username string, password string) bool {
	return username == d.Username && password == d.Password
}
110167
func (g *GRPCServer) authenticate(ctx context.Context) (*grpcContext, error) {
	// HTTPS server expects auth  context to be set by the auth middleware
	authContext, err := g.Authorizer.Authorize(ctx)
	if err != nil {
		// propagate connection problem error so we can differentiate
		// between connection failed and access denied
		if trace.IsConnectionProblem(err) {
			return nil, trace.ConnectionProblem(err, "[10] failed to connect to the database")
		} else if trace.IsAccessDenied(err) {
			// don't print stack trace, just log the warning
			log.Warn(err)
		} else {
			log.Warn(trace.DebugReport(err))
		}
		return nil, trace.AccessDenied("[10] access denied")
	}
	return &grpcContext{
		AuthContext: authContext,
		AuthWithRoles: &AuthWithRoles{
			authServer: g.AuthServer,
			user:       authContext.User,
			checker:    authContext.Checker,
			sessions:   g.SessionService,
			alog:       g.AuthServer.IAuditLog,
		},
	}, nil
}
754479
func (config Config) Validate() error {
	if config.APIInfo == nil {
		return errors.NotValidf("nil APIInfo")
	}
	if config.Authenticator == nil {
		return errors.NotValidf("nil Authenticator")
	}
	if config.DialConn == nil {
		return errors.NotValidf("nil DialConn")
	}
	if config.Hub == nil {
		return errors.NotValidf("nil Hub")
	}
	if config.Mux == nil {
		return errors.NotValidf("nil Mux")
	}
	if config.Path == "" {
		return errors.NotValidf("empty Path")
	}
	if config.LocalID == "" {
		return errors.NotValidf("empty LocalID")
	}
	if config.TLSConfig == nil {
		return errors.NotValidf("nil TLSConfig")
	}
	return nil
}
1284179
func (mr *MockResourceOwnerPasswordCredentialsGrantStorageMockRecorder) Authenticate(arg0, arg1, arg2 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Authenticate", reflect.TypeOf((*MockResourceOwnerPasswordCredentialsGrantStorage)(nil).Authenticate), arg0, arg1, arg2)
}
445105
func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
	var lastError error
	var allowsAnon bool
	var anonAuth RouteAuthenticator

	for _, ra := range ras {
		if ra.AllowsAnonymous() {
			anonAuth = ra
			allowsAnon = true
			continue
		}
		applies, usr, err := ra.Authenticate(req, route)
		if !applies || err != nil || usr == nil {
			if err != nil {
				lastError = err
			}
			continue
		}
		return applies, usr, nil
	}

	if allowsAnon && lastError == nil {
		route.Authenticator = &anonAuth
		return true, nil, lastError
	}
	return lastError != nil, nil, lastError
}
1349747
func (v *vaultService) authenticate() (err error) {
	payload := map[string]interface{}{
		"role_id":   v.config.Auth.AppRole.ID,
		"secret_id": v.config.Auth.AppRole.Secret,
	}
	var tokenID string
	var ttl time.Duration
	var secret *vault.Secret
	secret, err = v.client.Logical().Write("auth/approle/login", payload)
	if err != nil {
		return
	}
	if secret == nil {
		err = ErrKMSAuthLogin
		return
	}

	tokenID, err = secret.TokenID()
	if err != nil {
		err = ErrKMSAuthLogin
		return
	}
	ttl, err = secret.TokenTTL()
	if err != nil {
		err = ErrKMSAuthLogin
		return
	}
	v.client.SetToken(tokenID)
	v.secret = secret
	v.leaseDuration = ttl
	return
}
130998
func (self *BcryptAuth) Authenticate() (bool, error) {
	// check password
	err := bcrypt.CompareHashAndPassword([]byte(self.UserContext.HashedSecret()), []byte(self.UserContext.Secret()))
	if err == bcrypt.ErrMismatchedHashAndPassword {
		return false, nil
	}
	if err != nil {
		return false, err
	}

	// successfully authenticated
	return true, nil
}
970688
func (m *MachineTokenAuthMethod) Authenticate(c context.Context, r *http.Request) (*auth.User, error) {
	token := r.Header.Get(MachineTokenHeader)
	if token == "" {
		return nil, nil // no token -> the auth method is not applicable
	}

	// Deserialize both envelope and the body.
	envelope, body, err := deserialize(token)
	if err != nil {
		logTokenError(c, r, body, err, "Failed to deserialize the token")
		return nil, ErrBadToken
	}

	// Construct an identity of a token server that signed the token to check that
	// it belongs to "auth-token-servers" group.
	signerServiceAccount, err := identity.MakeIdentity("user:" + body.IssuedBy)
	if err != nil {
		logTokenError(c, r, body, err, "Bad issued_by field - %q", body.IssuedBy)
		return nil, ErrBadToken
	}

	// Reject tokens from unknown token servers right away.
	db, err := auth.GetDB(c)
	if err != nil {
		return nil, transient.Tag.Apply(err)
	}
	ok, err := db.IsMember(c, signerServiceAccount, []string{TokenServersGroup})
	if err != nil {
		return nil, transient.Tag.Apply(err)
	}
	if !ok {
		logTokenError(c, r, body, nil, "Unknown token issuer - %q", body.IssuedBy)
		return nil, ErrBadToken
	}

	// Check the expiration time before doing any heavier checks.
	if err = checkExpiration(body, clock.Now(c)); err != nil {
		logTokenError(c, r, body, err, "Token has expired or not yet valid")
		return nil, ErrBadToken
	}

	// Check the token was actually signed by the server.
	if err = m.checkSignature(c, body.IssuedBy, envelope); err != nil {
		if transient.Tag.In(err) {
			return nil, err
		}
		logTokenError(c, r, body, err, "Bad signature")
		return nil, ErrBadToken
	}

	// The token is valid. Construct the bot identity.
	botIdent, err := identity.MakeIdentity("bot:" + body.MachineFqdn)
	if err != nil {
		logTokenError(c, r, body, err, "Bad machine_fqdn - %q", body.MachineFqdn)
		return nil, ErrBadToken
	}
	return &auth.User{Identity: botIdent}, nil
}
1007017
func (client Client) Authenticate(creds map[string]string, origin string, grantType constant.GrantType) (string, string, error) {
	requestBody := url.Values{
		"grant_type": {string(grantType)},
	}

	for k, v := range creds {
		requestBody.Set(k, v)
	}

	type loginHint struct {
		Origin string `json:"origin"`
	}

	originStruct := loginHint{origin}
	originParam, err := json.Marshal(originStruct)
	if err != nil {
		return "", "", err
	}

	var query url.Values
	if origin != "" {
		query = url.Values{
			"login_hint": {string(originParam)},
		}
	}

	request, err := client.newRequest(requestOptions{
		RequestName: internal.PostOAuthTokenRequest,
		Header: http.Header{
			"Content-Type": {"application/x-www-form-urlencoded"},
		},
		Body:  strings.NewReader(requestBody.Encode()),
		Query: query,
	})

	if err != nil {
		return "", "", err
	}

	if grantType == constant.GrantTypePassword {
		request.SetBasicAuth(client.config.UAAOAuthClient(), client.config.UAAOAuthClientSecret())
	}

	responseBody := AuthResponse{}
	response := Response{
		Result: &responseBody,
	}

	err = client.connection.Make(request, &response)
	return responseBody.AccessToken, responseBody.RefreshToken, err
}