// AskUserServiceToCheckCredentials call user service to check if the credentials are correct
481005
func (s *service) AskUserServiceToCheckCredentials(username string, password string, method string) (rest.ResponseDTOUserInfo, *apihelper.ApiErrors) {

	requestBody := rest.RequestDTOUserCredentials{
		Username: username,
		Password: password,
		Method:   method,
	}

	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(requestBody)

	// call api
	req, err := http.NewRequest("POST", privateBaseUrl+"/user/check-credentials", b)
	req.Header.Set("Authorization", "Bearer YYY")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// read response
	body, _ := ioutil.ReadAll(resp.Body)

	userInfo := rest.ResponseDTOUserInfo{}
	apiErrors := apihelper.ApiErrors{}
	json.Unmarshal(body, &userInfo)
	json.Unmarshal(body, &apiErrors)

	if len(apiErrors.Errors) == 0 {
		return userInfo, nil
	}
	return rest.ResponseDTOUserInfo{}, &apiErrors
}
412520
func (c *Config) PasswordCredentialsToken(username, password string) (*oauth2.Token, error) {
	config := c.getConfig()
	token, err := config.PasswordCredentialsToken(c.getContext(), username, password)
	return token, fromError(err)
}
1110246
func Check(req *http.Request, username, password string) bool {
	auth := parseAuthorizationHeader(req.Header.Get("Authorization"))
	if auth == nil || auth.username != username {
		return false
	}
	expectedResponse := response(auth, password, req.Method, req.RequestURI)
	return compare(auth.response, expectedResponse)
}
726609
func (u *User) ProviderCredentials() map[string]*common.Credentials {
	return u.Data().Get(common.UserKeyProviderCredentials).Data().(map[string]*common.Credentials)
}
795023
func (ra PasswordAuthenticator) Credentials(req AuthCredsRequest) ([]UserPassPair, error) {
	return []UserPassPair{{
		Username: ra.Username,
		Password: ra.Password,
	}}, nil
}
875513
func (user *User) ServiceHookURL() string {
	return Config.BaseURL + "/" + user.ctx.ServiceName + "/" + user.ServiceHookToken()
}
298715
func (s *ChannelResponse) SetHasCredential(v bool) *ChannelResponse {
	s.HasCredential = &v
	return s
}
1256975
func credentialsCallback(_cred **C.git_cred, _url *C.char, _username_from_url *C.char, allowed_types uint, data unsafe.Pointer) int {
	callbacks, _ := pointerHandles.Get(data).(*RemoteCallbacks)
	if callbacks.CredentialsCallback == nil {
		return C.GIT_PASSTHROUGH
	}
	url := C.GoString(_url)
	username_from_url := C.GoString(_username_from_url)
	ret, cred := callbacks.CredentialsCallback(url, username_from_url, (CredType)(allowed_types))
	if cred != nil {
		*_cred = cred.ptr
	}
	return int(ret)
}
870029
func checkCredentialsForPasswordAuth(s *service, email string, password string) (rest.ResponseDTOUserInfo, *servicehelper.Error) {
	if entity, err := s.repo.FindByEmail(email); err != nil {
		return rest.ResponseDTOUserInfo{}, &servicehelper.Error{
			Detail: errors.New("incorrect username or password"),
		}
	} else if err := scrypt.CompareHashAndPassword([]byte(entity.Password), []byte(password)); err != nil {
		return rest.ResponseDTOUserInfo{}, &servicehelper.Error{
			Detail: errors.New("incorrect username or password"),
		}
	} else {
		return rest.ResponseDTOUserInfo{
			UserId: entity.ID,
			Email:  entity.Email,
		}, nil
	}
}
299423
func DialerCredentials(creds credentials.TransportCredentials) DialOption {
	return func(dialOptions *dialOptions) {
		dialOptions.creds = creds
	}
}
977193
func (c *KBFSContext) CheckService() error {
	// Trying to dial the service seems like the best
	// platform-agnostic way of seeing if the service is up.
	// Stat-ing the socket file, for example, doesn't work for
	// Windows named pipes.
	s, err := libkb.NewSocket(c.g)
	if err != nil {
		return err
	}
	conn, err := s.DialSocket()
	if err != nil {
		if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
			return errors.New(
				"keybase isn't running; open the Keybase app")
		}
		return errors.New(
			"keybase isn't running; try `run_keybase`")
	}
	err = conn.Close()
	if err != nil {
		return err
	}
	return nil
}
751619
func (s *SMSChannelResponse) SetHasCredential(v bool) *SMSChannelResponse {
	s.HasCredential = &v
	return s
}
186713
func (api *CloudAPI) RevokeCredentialsCheckModels(args params.RevokeCredentialArgs) (params.ErrorResults, error) {
	// TODO (anastasiamac 2018-11-13) the behavior here needs to be changed to performed promised models checks and authorise use of force.
	results := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Credentials)),
	}
	authFunc, err := api.getCredentialsAuthFunc()
	if err != nil {
		return results, err
	}

	opMessage := func(force bool) string {
		if force {
			return "will be deleted but"
		}
		return "cannot be deleted as"
	}

	for i, arg := range args.Credentials {
		tag, err := names.ParseCloudCredentialTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		// NOTE(axw) if we add ACLs for cloud credentials, we'll need
		// to change this auth check.
		if !authFunc(tag.Owner()) {
			results.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}

		models, err := api.credentialModels(tag)
		if err != nil {
			if !arg.Force {
				// Could not determine if credential has models - do not continue updating this credential...
				results.Results[i].Error = common.ServerError(err)
				continue
			}
			logger.Warningf("could not get models that use credential %v: %v", tag, err)
		}
		if len(models) != 0 {
			logger.Warningf("credential %v %v it is used by model%v",
				tag,
				opMessage(arg.Force),
				modelsPretty(models),
			)
			if !arg.Force {
				// Some models still use this credential - do not delete this credential...
				results.Results[i].Error = common.ServerError(errors.Errorf("cannot delete credential %v: it is still used by %d model%v", tag, len(models), plural(len(models))))
				continue
			}
		}

		if err := api.backend.RemoveCloudCredential(tag); err != nil {
			results.Results[i].Error = common.ServerError(err)
		}
	}
	return results, nil
}
1095652
func (u *user) checkUsername(un libkb.NormalizedUsername) error {
	var err error
	if !u.username.Eq(un) {
		err = BadUsernameError{u.username, un}
	}
	return err
}
1151461
func (api *CloudAPI) Credential(args params.Entities) (params.CloudCredentialResults, error) {
	results := params.CloudCredentialResults{
		Results: make([]params.CloudCredentialResult, len(args.Entities)),
	}
	authFunc, err := api.getCredentialsAuthFunc()
	if err != nil {
		return results, err
	}

	for i, arg := range args.Entities {
		credentialTag, err := names.ParseCloudCredentialTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if !authFunc(credentialTag.Owner()) {
			results.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}

		// Helper to look up and cache credential schemas for clouds.
		schemaCache := make(map[string]map[cloud.AuthType]cloud.CredentialSchema)
		credentialSchemas := func() (map[cloud.AuthType]cloud.CredentialSchema, error) {
			cloudName := credentialTag.Cloud().Id()
			if s, ok := schemaCache[cloudName]; ok {
				return s, nil
			}
			aCloud, err := api.backend.Cloud(cloudName)
			if err != nil {
				return nil, err
			}
			provider, err := environs.Provider(aCloud.Type)
			if err != nil {
				return nil, err
			}
			schema := provider.CredentialSchemas()
			schemaCache[cloudName] = schema
			return schema, nil
		}
		cloudCredentials, err := api.backend.CloudCredentials(credentialTag.Owner(), credentialTag.Cloud().Id())
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}

		cred, ok := cloudCredentials[credentialTag.Id()]
		if !ok {
			results.Results[i].Error = common.ServerError(errors.NotFoundf("credential %q", credentialTag.Name()))
			continue
		}

		schemas, err := credentialSchemas()
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}

		attrs := cred.Attributes
		var redacted []string
		// Mask out the secrets.
		if s, ok := schemas[cloud.AuthType(cred.AuthType)]; ok {
			for _, attr := range s {
				if attr.Hidden {
					delete(attrs, attr.Name)
					redacted = append(redacted, attr.Name)
				}
			}
		}
		results.Results[i].Result = &params.CloudCredential{
			AuthType:   cred.AuthType,
			Attributes: attrs,
			Redacted:   redacted,
		}
	}
	return results, nil
}
1064424
func (r User_Customer_Security_Answer) GetQuestion() (resp datatypes.User_Security_Question, err error) {
	err = r.Session.DoRequest("SoftLayer_User_Customer_Security_Answer", "getQuestion", nil, &r.Options, &resp)
	return
}
717239
func (a *Authenticator) refreshCredsLocked(r *clientauthentication.Response) error {
	cred := &clientauthentication.ExecCredential{
		Spec: clientauthentication.ExecCredentialSpec{
			Response:    r,
			Interactive: a.interactive,
		},
	}

	env := append(a.environ(), a.env...)
	if a.group == v1alpha1.SchemeGroupVersion {
		// Input spec disabled for beta due to lack of use. Possibly re-enable this later if
		// someone wants it back.
		//
		// See: https://github.com/kubernetes/kubernetes/issues/61796
		data, err := runtime.Encode(codecs.LegacyCodec(a.group), cred)
		if err != nil {
			return fmt.Errorf("encode ExecCredentials: %v", err)
		}
		env = append(env, fmt.Sprintf("%s=%s", execInfoEnv, data))
	}

	stdout := &bytes.Buffer{}
	cmd := exec.Command(a.cmd, a.args...)
	cmd.Env = env
	cmd.Stderr = a.stderr
	cmd.Stdout = stdout
	if a.interactive {
		cmd.Stdin = a.stdin
	}

	if err := cmd.Run(); err != nil {
		return fmt.Errorf("exec: %v", err)
	}

	_, gvk, err := codecs.UniversalDecoder(a.group).Decode(stdout.Bytes(), nil, cred)
	if err != nil {
		return fmt.Errorf("decoding stdout: %v", err)
	}
	if gvk.Group != a.group.Group || gvk.Version != a.group.Version {
		return fmt.Errorf("exec plugin is configured to use API version %s, plugin returned version %s",
			a.group, schema.GroupVersion{Group: gvk.Group, Version: gvk.Version})
	}

	if cred.Status == nil {
		return fmt.Errorf("exec plugin didn't return a status field")
	}
	if cred.Status.Token == "" && cred.Status.ClientCertificateData == "" && cred.Status.ClientKeyData == "" {
		return fmt.Errorf("exec plugin didn't return a token or cert/key pair")
	}
	if (cred.Status.ClientCertificateData == "") != (cred.Status.ClientKeyData == "") {
		return fmt.Errorf("exec plugin returned only certificate or key, not both")
	}

	if cred.Status.ExpirationTimestamp != nil {
		a.exp = cred.Status.ExpirationTimestamp.Time
	} else {
		a.exp = time.Time{}
	}

	newCreds := &credentials{
		token: cred.Status.Token,
	}
	if cred.Status.ClientKeyData != "" && cred.Status.ClientCertificateData != "" {
		cert, err := tls.X509KeyPair([]byte(cred.Status.ClientCertificateData), []byte(cred.Status.ClientKeyData))
		if err != nil {
			return fmt.Errorf("failed parsing client key/certificate: %v", err)
		}
		newCreds.cert = &cert
	}

	oldCreds := a.cachedCreds
	a.cachedCreds = newCreds
	// Only close all connections when TLS cert rotates. Token rotation doesn't
	// need the extra noise.
	if a.onRotate != nil && oldCreds != nil && !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) {
		a.onRotate()
	}
	return nil
}