github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/tools/blocksconvert/allowed_users.go (about)

     1  package blocksconvert
     2  
     3  import (
     4  	"bufio"
     5  	"os"
     6  	"strings"
     7  )
     8  
     9  type AllowedUsers map[string]struct{}
    10  
    11  var AllowAllUsers = AllowedUsers(nil)
    12  
    13  func (a AllowedUsers) AllUsersAllowed() bool {
    14  	return a == nil
    15  }
    16  
    17  func (a AllowedUsers) IsAllowed(user string) bool {
    18  	if a == nil {
    19  		return true
    20  	}
    21  
    22  	_, ok := a[user]
    23  	return ok
    24  }
    25  
    26  func (a AllowedUsers) GetAllowedUsers(users []string) []string {
    27  	if a == nil {
    28  		return users
    29  	}
    30  
    31  	allowed := make([]string, 0, len(users))
    32  	for _, u := range users {
    33  		if a.IsAllowed(u) {
    34  			allowed = append(allowed, u)
    35  		}
    36  	}
    37  	return allowed
    38  }
    39  
    40  func ParseAllowedUsersFromFile(file string) (AllowedUsers, error) {
    41  	result := map[string]struct{}{}
    42  
    43  	f, err := os.Open(file)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	defer func() { _ = f.Close() }()
    49  
    50  	s := bufio.NewScanner(f)
    51  	for s.Scan() {
    52  		result[s.Text()] = struct{}{}
    53  	}
    54  	return result, s.Err()
    55  }
    56  
    57  func ParseAllowedUsers(commaSeparated string) AllowedUsers {
    58  	result := map[string]struct{}{}
    59  
    60  	us := strings.Split(commaSeparated, ",")
    61  	for _, u := range us {
    62  		u = strings.TrimSpace(u)
    63  		result[u] = struct{}{}
    64  	}
    65  
    66  	return result
    67  }