// CompleteCredentialsFromEnv gets and verifies all the required
// authentication parameters have values in the environment.
171148
func CompleteCredentialsFromEnv(keyName string) (cred *auth.Credentials, err error) {
	cred, err = credentialsFromEnv(keyName)
	if err != nil {
		return nil, err
	}
	v := reflect.ValueOf(cred).Elem()
	t := v.Type()
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i)
		if f.String() == "" {
			return nil, fmt.Errorf("Required environment variable not set for credentials attribute: %s", t.Field(i).Name)
		}
	}
	return cred, nil
}
1059382
func (ca CertAuthenticator) Credentials(req AuthCredsRequest) ([]UserPassPair, error) {
	return []UserPassPair{{
		Username: "",
		Password: "",
	}}, nil
}
475371
func (p environProviderCredentials) DetectCredentials() (*cloud.CloudCredential, error) {
	nopLogf := func(msg string, args ...interface{}) {}
	certPEM, keyPEM, err := p.readOrGenerateCert(nopLogf)
	if err != nil {
		return nil, errors.Trace(err)
	}

	remoteCertCredentials, err := p.detectRemoteCredentials(certPEM, keyPEM)
	if err != nil {
		logger.Errorf("unable to detect remote LXC credentials: %s", err)
	}

	localCertCredentials, err := p.detectLocalCredentials(certPEM, keyPEM)
	if err != nil {
		logger.Errorf("unable to detect local LXC credentials: %s", err)
	}

	authCredentials := make(map[string]cloud.Credential)
	for k, v := range remoteCertCredentials {
		authCredentials[k] = v
	}
	if localCertCredentials != nil {
		authCredentials["localhost"] = *localCertCredentials
	}
	return &cloud.CloudCredential{
		AuthCredentials: authCredentials,
	}, nil
}
1326485
func (p environProviderCredentials) ShouldFinalizeCredential(cred cloud.Credential) bool {
	// The credential is fully formed, so we assume the client
	// certificate is uploaded to the server already.
	credAttrs := cred.Attributes()
	_, ok := credAttrs[credAttrServerCert]
	return !ok
}
117727
func NewCredentials() *credentials.Credentials {
	return credentials.NewChainCredentials(
		new(credentials.EnvProvider),
		new(credentials.FileProvider),
	)
}
173192
func NewFromEnv(realm, prefix string) func(http.Handler) http.Handler {
	credentials := map[string][]string{}

	re := regexp.MustCompile(fmt.Sprintf("^%s(?P<username>.*)$", strings.ToUpper(prefix)))
	for _, envVar := range os.Environ() {
		name, value := split2(envVar, "=")

		if res := re.FindStringSubmatch(name); res != nil {
			username := strings.ToLower(res[1])
			credentials[username] = strings.Split(value, ",")
		}
	}

	return New(realm, credentials)
}
448159
func (c *Client) ValidateCredentials(user user.User) (bool, error) {
	result := false
	err := c.call("ValidateCredentials", user, &result)
	return result, err
}
1219399
func (fp *ForwardProxy) checkCredentials(r *http.Request) error {
	pa := strings.Split(r.Header.Get("Proxy-Authorization"), " ")
	if len(pa) != 2 {
		return errors.New("Proxy-Authorization is required! Expected format: <type> <credentials>")
	}
	if strings.ToLower(pa[0]) != "basic" {
		return errors.New("Auth type is not supported")
	}
	for _, creds := range fp.authCredentials {
		if subtle.ConstantTimeCompare(creds, []byte(pa[1])) == 1 {
			// Please do not consider this to be timing-attack-safe code. Simple equality is almost
			// mindlessly substituted with constant time algo and there ARE known issues with this code,
			// e.g. size of smallest credentials is guessable. TODO: protect from all the attacks! Hash?
			return nil
		}
	}
	return errors.New("Invalid credentials")
}
839059
func CompleteAuth(tripperFactory common.TripperFactory, data objx.Map, config *common.Config, provider common.Provider) (*common.Credentials, error) {

	// get the code
	codeList := data.Get(OAuth2KeyCode).Data()

	code, ok := codeList.(string)
	if !ok {

		if codeList == nil || len(codeList.([]string)) == 0 {
			return nil, &common.MissingParameterError{ParameterName: OAuth2KeyCode}
		}
		code = codeList.([]string)[0]
		if len(code) == 0 {
			return nil, &common.MissingParameterError{ParameterName: OAuth2KeyCode}
		}
	}

	client, clientErr := GetClient(tripperFactory, common.EmptyCredentials, provider)
	if clientErr != nil {
		return nil, clientErr
	}

	params := objx.MSI(OAuth2KeyGrantType, OAuth2GrantTypeAuthorizationCode,
		OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(),
		OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(),
		OAuth2KeyCode, code,
		OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(),
		OAuth2KeySecret, config.Get(OAuth2KeySecret).Str())

	// post the form
	response, requestErr := client.PostForm(config.Get(OAuth2KeyTokenURL).Str(), params.URLValues())

	if requestErr != nil {
		return nil, requestErr
	}

	// make sure we close the body
	defer func() {
		if response.Body != nil {
			response.Body.Close()
		}
	}()

	// make sure we have an OK response
	if response.StatusCode != http.StatusOK {
		return nil, &common.AuthServerError{
			ErrorMessage: fmt.Sprintf("Server replied with %s.", response.Status),
			Response: response,
		}
	}

	content, _, mimeTypeErr := mime.ParseMediaType(response.Header.Get("Content-Type"))

	if mimeTypeErr != nil {
		return nil, mimeTypeErr
	}

	// prepare the credentials object
	creds := &common.Credentials{Map: objx.MSI()}

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

	switch content {
	case "application/x-www-form-urlencoded", "text/plain":

		vals, err := objx.FromURLQuery(string(body))
		if err != nil {
			return nil, err
		}

		// did an error occur?
		if len(vals.Get("error").Str()) > 0 {
			return nil, &common.AuthServerError{
				ErrorMessage: vals.Get("error").Str(),
				Response: response,
			}
		}

		expiresIn, _ := time.ParseDuration(vals.Get(OAuth2KeyExpiresIn).Str() + "s")

		creds.Set(OAuth2KeyAccessToken, vals.Get(OAuth2KeyAccessToken).Str())
		creds.Set(OAuth2KeyRefreshToken, vals.Get(OAuth2KeyRefreshToken).Str())
		creds.Set(OAuth2KeyExpiresIn, expiresIn)

	default: // use JSON

		var data objx.Map

		jsonErr := json.Unmarshal(body, &data)

		if jsonErr != nil {
			return nil, jsonErr
		}

		// handle the time
		timeDuration := data.Get(OAuth2KeyExpiresIn).Float64()
		data.Set(OAuth2KeyExpiresIn, time.Duration(timeDuration)*time.Second)

		// merge this data into the creds
		creds.MergeHere(data)

	}

	return creds, nil
}
271547
func ValidCredentials(region string) error {
	svc, err := getService(region)
	if err != nil {
		return fmt.Errorf("failed to get AWS service: %v", err)
	}

	_, err = svc.DescribeInstances(nil)
	awsErr, isAWS := err.(awserr.Error)
	if !isAWS {
		return err
	}

	switch awsErr.Code() {
	case noCredsCode:
		return ErrNoCreds
	case noRegionCode:
		return ErrNoRegion
	}

	return nil
}
338005
func defaultPathsForLegacyCredentials() []string {
	if runtime.GOOS == "windows" { // Windows
		return []string{os.Getenv("USERPROFILE")}
	}
	return []string{os.Getenv("HOME")}
}
1245958
func NewCredentials(values map[string]string) (*Credentials, error) {
	var creds Credentials
	for k, v := range values {
		switch k {
		case OSEnvClientID:
			creds.ClientID = v
		case OSEnvClientEmail:
			creds.ClientEmail = v
		case OSEnvProjectID:
			creds.ProjectID = v
		case OSEnvPrivateKey:
			creds.PrivateKey = []byte(v)
		default:
			return nil, errors.NotSupportedf("key %q", k)
		}
	}
	if err := creds.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	jk, err := creds.buildJSONKey()
	if err != nil {
		return nil, errors.Trace(err)
	}
	creds.JSONKey = jk
	return &creds, nil
}
1187137
func (environProviderCredentials) FinalizeCredential(_ environs.FinalizeCredentialContext, args environs.FinalizeCredentialParams) (*cloud.Credential, error) {
	return &args.Credential, nil
}
1160802
func CredentialNotValid(err error) error {
	if err == nil {
		return nil
	}
	wrapped := errors.Wrap(err, &credentialNotValid{err})
	wrapped.(*errors.Err).SetLocation(1)
	return wrapped
}
747592
func (c *Client) Credentials(tags ...names.CloudCredentialTag) ([]params.CloudCredentialResult, error) {
	if len(tags) == 0 {
		return []params.CloudCredentialResult{}, nil
	}
	var results params.CloudCredentialResults
	args := params.Entities{
		Entities: make([]params.Entity, len(tags)),
	}
	for i, tag := range tags {
		args.Entities[i].Tag = tag.String()
	}
	if err := c.facade.FacadeCall("Credential", args, &results); err != nil {
		return nil, errors.Trace(err)
	}
	return results.Results, nil
}
726609
func (u *User) ProviderCredentials() map[string]*common.Credentials {
	return u.Data().Get(common.UserKeyProviderCredentials).Data().(map[string]*common.Credentials)
}
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
	}
}