// ValidUsernamePassword checks that the given username and password are different.
// Also check if the chosen username only contains letters, numbers and/or underscore.
// Use the "CorrectPassword" function for checking if the password is correct.
341086
func ValidUsernamePassword(username, password string) error {
	const allAllowedLetters = "abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ_0123456789"
NEXT:
	for _, letter := range username {
		for _, allowedLetter := range allAllowedLetters {
			if letter == allowedLetter {
				continue NEXT // check the next letter in the username
			}
		}
		return errors.New("only letters, numbers and underscore are allowed in usernames")
	}
	if username == password {
		return errors.New("username and password must be different, try another password")
	}
	return nil
}
1002252
func validName(name string) bool {
	for _, r := range name {
		if !unicode.IsPrint(r) {
			return false
		}
	}
	return name != "" &&
		name != "." &&
		name != ".." &&
		!strings.ContainsAny(name, `/\`)
}
1196090
func (c *Client) ResetPassword(username string) ([]byte, error) {
	if !names.IsValidUser(username) {
		return nil, fmt.Errorf("invalid user name %q", username)
	}

	in := params.Entities{
		Entities: []params.Entity{{
			Tag: names.NewUserTag(username).String(),
		}},
	}
	var out params.AddUserResults
	err := c.facade.FacadeCall("ResetPassword", in, &out)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if count := len(out.Results); count != 1 {
		logger.Errorf("expected 1 result, got %#v", out)
		return nil, errors.Errorf("expected 1 result, got %d", count)
	}
	result := out.Results[0]
	if result.Error != nil {
		return nil, errors.Trace(result.Error)
	}
	return result.SecretKey, nil
}
198849
func BasicAuth(username, password string) Strategy {
	return &basicAuth{
		username: username,
		password: password,
	}
}
30855
func SplitUsername(username string) (string, string, error) {
	if !strings.HasPrefix(username, ServiceAccountUsernamePrefix) {
		return "", "", invalidUsernameErr
	}
	trimmed := strings.TrimPrefix(username, ServiceAccountUsernamePrefix)
	parts := strings.Split(trimmed, ServiceAccountUsernameSeparator)
	if len(parts) != 2 {
		return "", "", invalidUsernameErr
	}
	namespace, name := parts[0], parts[1]
	if len(apimachineryvalidation.ValidateNamespaceName(namespace, false)) != 0 {
		return "", "", invalidUsernameErr
	}
	if len(apimachineryvalidation.ValidateServiceAccountName(name, false)) != 0 {
		return "", "", invalidUsernameErr
	}
	return namespace, name, nil
}
1326743
func randomAdminPassword() string {
	// We want at least one each of lower-alpha, upper-alpha, and digit.
	// Allocate 16 of each (randomly), and then the remaining characters
	// will be randomly chosen from the full set.
	validRunes := append(utils.LowerAlpha, utils.Digits...)
	validRunes = append(validRunes, utils.UpperAlpha...)

	lowerAlpha := utils.RandomString(16, utils.LowerAlpha)
	upperAlpha := utils.RandomString(16, utils.UpperAlpha)
	digits := utils.RandomString(16, utils.Digits)
	mixed := utils.RandomString(16, validRunes)
	password := []rune(lowerAlpha + upperAlpha + digits + mixed)
	for i := len(password) - 1; i >= 1; i-- {
		j := rand.Intn(i + 1)
		password[i], password[j] = password[j], password[i]
	}
	return string(password)
}
775090
func (ung *uniqueNameGenerator) ensureValidName(name string) (string, error) {
	names := ung.names

	// Ensure that name meets length requirements
	if len(name) < 2 {
		return "", fmt.Errorf("invalid name: %s", name)
	}

	if !IsParameterizableValue(name) {

		// Make all names lowercase
		name = strings.ToLower(name)

		// Remove everything except [-0-9a-z]
		name = invalidNameCharactersRegexp.ReplaceAllString(name, "")

		// Remove leading hyphen(s) that may be introduced by the previous step
		name = strings.TrimLeft(name, "-")

		if len(name) > kvalidation.DNS1123SubdomainMaxLength {
			klog.V(4).Infof("Trimming %s to maximum allowable length (%d)\n", name, kvalidation.DNS1123SubdomainMaxLength)
			name = name[:kvalidation.DNS1123SubdomainMaxLength]
		}
	}

	count, existing := names[name]
	if !existing {
		names[name] = 0
		return name, nil
	}
	count++
	names[name] = count
	newName := apihelpers.GetName(name, strconv.Itoa(count), kvalidation.DNS1123SubdomainMaxLength)
	return newName, nil
}
72095
func (a *authenticator) validateCredentials(credentials *credentials) (string, int, error) {
	user, err := a.userDb.GetUser(credentials.Username)
	if err != nil {
		return "", http.StatusUnauthorized, errors.Errorf("401 unauthorized: user name or password is incorrect")
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(credentials.Password)); err != nil {
		return credentials.Username, http.StatusUnauthorized, fmt.Errorf("401 unauthorized: user name or password is incorrect")
	}
	return credentials.Username, 0, nil
}
418453
func (a *Application) PasswordValid(password string) bool {
	agentHash := utils.AgentPasswordHash(password)
	if agentHash == a.doc.PasswordHash {
		return true
	}
	return false
}
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
	}
}
148668
func (s *Service) ComparePassword(ctx context.Context, name string, password string) error {
	u, err := s.FindUser(ctx, platform.UserFilter{Name: &name})
	if err != nil {
		return EIncorrectPassword
	}
	hash, ok := s.basicAuthKV.Load(u.ID.String())
	if !ok {
		hash = []byte{}
	}

	if err := bcrypt.CompareHashAndPassword(hash.([]byte), []byte(password)); err != nil {
		return fmt.Errorf("<forbidden> your username or password is incorrect")
	}
	return nil
}
1359187
func (settings EnvironmentSettings) GetUsernamePassword() (UsernamePasswordConfig, error) {
	username := settings.Values[Username]
	password := settings.Values[Password]
	if username == "" || password == "" {
		return UsernamePasswordConfig{}, errors.New("missing username/password")
	}
	clientID, tenantID := settings.getClientAndTenant()
	config := NewUsernamePasswordConfig(username, password, clientID, tenantID)
	config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint
	config.Resource = settings.Values[Resource]
	return config, nil
}
763907
func (s *userService) GetByUsernameAndPassword(username, userPassword string) (datamodels.User, bool) {
	if username == "" || userPassword == "" {
		return datamodels.User{}, false
	}

	return s.repo.Select(func(m datamodels.User) bool {
		if m.Username == username {
			hashed := m.HashedPassword
			if ok, _ := datamodels.ValidatePassword(userPassword, hashed); ok {
				return true
			}
		}
		return false
	})
}
673086
func RFC7617UserPass(userid, password string) (string, error) {
	if strings.Index(userid, ":") > -1 {
		return "", fmt.Errorf(
			"RFC7617 user-id cannot include a colon (':') [%v]", userid)
	}

	return base64.StdEncoding.EncodeToString(
		[]byte(userid + ":" + password),
	), nil
}
863538
func IsValidName(name string) bool {
	// doesn't contain the prefix
	if !strings.HasPrefix(name, Prefix) {
		return false
	}
	// it's required to have at least the following chars `x-x-0`
	suffix := name[len(Prefix):]
	if len(suffix) < 5 {
		return false
	}
	// lastly check the last part is a number
	lastHyphen := strings.LastIndex(suffix, "-")
	revision := suffix[lastHyphen+1:]
	_, err := strconv.Atoi(revision)
	return err == nil
}
1176622
func (k *PGPKeyBundle) FindKeybaseUsername(un string) bool {

	rxx := regexp.MustCompile("(?i)< " + un + "@keybase.io>$")

	for _, id := range k.Identities {
		if rxx.MatchString(id.Name) {
			return true
		}
	}
	return false
}
749587
func (ri *ReindexRemoteInfo) Username(username string) *ReindexRemoteInfo {
	ri.username = username
	return ri
}