// Authenticate extracts peer's identity from the incoming request.
//
// It logs detailed errors in log, but returns only generic "bad credential"
// error to the caller, to avoid leaking unnecessary information.
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
}
758520
func (c *CertChecker) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
	err := validate(key)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	perms, err := c.CertChecker.Authenticate(conn, key)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return perms, nil
}
506926
func (_m *ClientInterface) AuthenticateHost(hostID string) (string, int64, error) {
	ret := _m.Called(hostID)

	var r0 string
	if rf, ok := ret.Get(0).(func(string) string); ok {
		r0 = rf(hostID)
	} else {
		r0 = ret.Get(0).(string)
	}

	var r1 int64
	if rf, ok := ret.Get(1).(func(string) int64); ok {
		r1 = rf(hostID)
	} else {
		r1 = ret.Get(1).(int64)
	}

	var r2 error
	if rf, ok := ret.Get(2).(func(string) error); ok {
		r2 = rf(hostID)
	} else {
		r2 = ret.Error(2)
	}

	return r0, r1, r2
}
1313280
func (a *Authenticator) Authenticate(req *http.Request) (httpcontext.AuthInfo, error) {
	modelUUID := httpcontext.RequestModelUUID(req)
	if modelUUID == "" {
		return httpcontext.AuthInfo{}, errors.New("model UUID not found")
	}
	loginRequest, err := LoginRequest(req)
	if err != nil {
		return httpcontext.AuthInfo{}, errors.Trace(err)
	}
	return a.AuthenticateLoginRequest(req.Host, modelUUID, loginRequest)
}
148200
func (ldt *LogplexDrainToken) Authenticate(r *http.Request) (exists bool) {
	if token := r.Header.Get("Logplex-Drain-Token"); token != "" {
		ldt.RLock()
		_, exists = ldt.tokens[token]
		ldt.RUnlock()
	}
	return
}
1034041
func (m *middleware) authenticate(r *http.Request) (context.Context, *Error) {
	var h = r.Header.Get(authorizationHeader)
	if len(h) > 0 {
		return m.validateHeader(r, h)
	}

	cookie, err := r.Cookie(m.config.TokenCookie)
	if err == nil && cookie != nil {
		return m.validateJWT(r, cookie.Value)
	}

	// from query string
	token := r.URL.Query().Get(m.config.TokenKey)
	if len(token) > 0 {
		return m.validateJWT(r, token)
	}

	return nil, ErrBadAuthorizationHeader
}
85919
func (s userIdentityMappingStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	return validation.ValidateUserIdentityMapping(obj.(*userapi.UserIdentityMapping))
}
678277
func (a keystonePasswordAuthenticator) AuthenticatePassword(ctx context.Context, username, password string) (*authenticator.Response, bool, error) {
	defer func() {
		if e := recover(); e != nil {
			utilruntime.HandleError(fmt.Errorf("Recovered panic: %v, %s", e, debug.Stack()))
		}
	}()

	// if password is missing, fail authentication immediately
	if len(password) == 0 {
		return nil, false, nil
	}

	opts := gophercloud.AuthOptions{
		IdentityEndpoint: a.url,
		Username:         username,
		Password:         password,
		DomainName:       a.domainName,
	}

	// Calling NewClient/Authenticate manually rather than simply calling AuthenticatedClient
	// in order to pass in a transport object that supports SSL
	client, err := openstack.NewClient(opts.IdentityEndpoint)
	if err != nil {
		klog.Warningf("Failed: Initializing openstack authentication client: %v", err)
		return nil, false, err
	}

	client.HTTPClient = *a.client
	userid, err := getUserIDv3(client, &opts, gophercloud.EndpointOpts{})

	if err != nil {
		if _, ok := err.(gophercloud.ErrDefault401); ok {
			return nil, false, nil
		}
		klog.Warningf("Failed: Calling openstack AuthenticateV3: %v", err)
		return nil, false, err
	}

	providerUserID := username
	if a.useKeystoneIdentity {
		providerUserID = userid
	}

	identity := authapi.NewDefaultUserIdentityInfo(a.providerName, providerUserID)
	identity.Extra[authapi.IdentityPreferredUsernameKey] = username

	return identitymapper.ResponseFor(a.identityMapper, identity)
}
728958
func (a *Verifier) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
	if req.TLS == nil || len(req.TLS.PeerCertificates) == 0 {
		return nil, false, nil
	}

	// Use intermediates, if provided
	optsCopy := a.opts
	if optsCopy.Intermediates == nil && len(req.TLS.PeerCertificates) > 1 {
		optsCopy.Intermediates = x509.NewCertPool()
		for _, intermediate := range req.TLS.PeerCertificates[1:] {
			optsCopy.Intermediates.AddCert(intermediate)
		}
	}

	if _, err := req.TLS.PeerCertificates[0].Verify(optsCopy); err != nil {
		return nil, false, err
	}
	if err := a.verifySubject(req.TLS.PeerCertificates[0].Subject); err != nil {
		return nil, false, err
	}
	return a.auth.AuthenticateRequest(req)
}
285242
func (_ BasicAuth) Authenticate(config *Config) (*http.Client, APIResponse) {
	client := &http.Client{Transport: BasicAuthTransport{Config: config}}
	return client, apiResponse("basic auth", "", nil, nil)
}
747781
func (ud *UltraDns) Authenticate(username, password string) error {
	var authResp AuthResp
	payLoad := "grant_type=password&username=" + username + "&password=" + password

	resp, body, err := ud.Client.Post(AuthURL).Send(payLoad).End()
	if err != nil {
		return errors.New("Authentication Failed")
	}

	if resp.StatusCode != 200 {
		return errors.New("Something Bad Happened")
	}

	er := json.Unmarshal([]byte(body), &authResp)
	if er != nil {
		return errors.New("Unmarshal Error")
	}

	ud.accessToken = authResp.AccessToken
	ud.refreshToken = authResp.RefreshToken
	ud.tokenHeader = "Bearer " + ud.accessToken

	return nil
}
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
}
753996
func (c *Client) Authenticate() error {

	m, err := newMessage(bufio.NewReaderSize(c, ReadBufferSize), false)
	if err != nil {
		Error(ECouldNotCreateMessage, err)
		return err
	}

	cmr, err := m.tr.ReadMIMEHeader()
	if err != nil && err.Error() != "EOF" {
		Error(ECouldNotReadMIMEHeaders, err)
		return err
	}

	Debug("A: %v\n", cmr)

	if cmr.Get("Content-Type") != "auth/request" {
		Error(EUnexpectedAuthHeader, cmr.Get("Content-Type"))
		return fmt.Errorf(EUnexpectedAuthHeader, cmr.Get("Content-Type"))
	}

	s := "auth " + c.Passwd + "\r\n\r\n"
	_, err = io.WriteString(c, s)
	if err != nil {
		return err
	}

	am, err := m.tr.ReadMIMEHeader()
	if err != nil && err.Error() != "EOF" {
		Error(ECouldNotReadMIMEHeaders, err)
		return err
	}

	if am.Get("Reply-Text") != "+OK accepted" {
		Error(EInvalidPassword, c.Passwd)
		return fmt.Errorf(EInvalidPassword, c.Passwd)
	}

	return nil
}
1023391
func (c *cookie) Validate(ctx context.Context, r *http.Request) (Principal, error) {
	cookie, err := r.Cookie(c.Name)
	if err != nil {
		return Principal{}, ErrAuthentication
	}

	return c.Tokens.ValidPrincipal(ctx, Token(cookie.Value), c.Lifespan)
}
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)
}
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)
}
1088581
func authenticate(out *[TagSize]byte, ciphertext, additionalData []byte, key *[32]byte) {
	ctLen := uint64(len(ciphertext))
	adLen := uint64(len(additionalData))
	padAD, padCT := adLen%16, ctLen%16

	var buf [16]byte
	buf[0] = byte(adLen)
	buf[1] = byte(adLen >> 8)
	buf[2] = byte(adLen >> 16)
	buf[3] = byte(adLen >> 24)
	buf[4] = byte(adLen >> 32)
	buf[5] = byte(adLen >> 40)
	buf[6] = byte(adLen >> 48)
	buf[7] = byte(adLen >> 56)
	buf[8] = byte(ctLen)
	buf[9] = byte(ctLen >> 8)
	buf[10] = byte(ctLen >> 16)
	buf[11] = byte(ctLen >> 24)
	buf[12] = byte(ctLen >> 32)
	buf[13] = byte(ctLen >> 40)
	buf[14] = byte(ctLen >> 48)
	buf[15] = byte(ctLen >> 56)

	poly := poly1305.New(key)
	poly.Write(additionalData)
	if padAD > 0 {
		poly.Write(make([]byte, 16-padAD))
	}
	poly.Write(ciphertext)
	if padCT > 0 {
		poly.Write(make([]byte, 16-padCT))
	}
	poly.Write(buf[:])
	poly.Sum(out)
}