Skip to content
Snippets Groups Projects
Select Git revision
  • 238d11db14b4d5949afd163bc4dc05bfb652e477
  • live_exam_os_ubuntu default protected
2 results

helper.go

Blame
  • helper.go 3.74 KiB
    package cmdUser
    
    import (
    	"regexp"
    	"strings"
    	"encoding/json"
    	"nexus-client/cmd"
    	u "nexus-client/utils"
    	g "nexus-client/globals"
    	"github.com/go-resty/resty/v2"
    )
    
    // Make sure these types MATCH their counterparts in nexus-server codebase!
    type (
    	Capabilities map[string]int
    
    	User struct {
    		Email string           `json:"email"     validate:"required,email"`
    		FirstName string       `json:"firstname" validate:"required,min=2,max=32"`
    		LastName string        `json:"lastname"  validate:"required,min=2,max=32"`
    		Pwd string             `json:"pwd"       validate:"required,min=8"`
    		Caps Capabilities      `json:"caps"      validate:"required"`
    	}
    )
    
    // Converts a User structure into a pretty string.
    func (user *User)String() string {
    	output, err := json.MarshalIndent(user, "", "    ")
        if err != nil {
            return err.Error()
        }
    
    	return string(output)
    }
    
    func printRegexUsage(c cmd.Command) {
    	for _, desc := range c.GetDesc() {
    		u.PrintlnErr(desc)
    	}
    	u.PrintlnErr("―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――")
    	u.PrintlnErr("USAGE: ",c.GetName()," [regex ...]")
    	u.PrintlnErr("―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――")
    }
    
    func printRegexUsageDetails() {
    	const usage string = `Only users matching the specified regexes will be listed.
    Any number of regexes can be specified.
    The regex matches the user email, first name and last name and is case-insensitive.
    Regex examples:
    "."   -> matches any users
    "bla" -> matches any users containing "bla"`
    	u.PrintlnErr(usage)
    }
    
    // Prints a list of filtered users for a given route.
    // The filter is based on regexes.
    // Remark: the regex matches the user email, first name and last name and is case-insensitive.
    // Regular expression examples:
    //   ""    -> matches everything
    //   "."   -> matches everything
    //   "bla" -> matches any user containing "bla"
    func printFilteredUsers(c cmd.Command, args []string, route string) int {
    	if len(args) < 1 {
    		c.PrintUsage()
    		return 1
    	}
    
    	// Helper function to remove an element from a string array at a given index
    	removeArgAtIndex := func (slice []string, index int) []string {
    		return append(slice[:index], slice[index+1:]...)
    	}
    
    	// Check if a "-l" argument is specified
    	foundLongOutputFlag := -1
    	for idx, arg := range args {
    		if arg == "-l" {
    			foundLongOutputFlag = idx
    		}
    	}
    
    	if foundLongOutputFlag >= 0 {
    		removeArgAtIndex(args, foundLongOutputFlag)
    	}
    
    	client := g.GetInstance().Client
    	host := g.GetInstance().Host
    
    	resp, err := client.R().Get(host+route)
    	if err != nil {
    		u.PrintlnErr("Error: "+err.Error())
    		return 1
    	}
    
    	if resp.IsSuccess() {
    		users, err := getUsers(resp)
    		if err != nil {
    			u.PrintlnErr("Error: "+err.Error())
    			return 1
    		}
    
    		for _, user := range users {
    			for _, regex := range args {
    				fieldsToMatch := user.Email+" "+user.FirstName+" "+user.LastName
    				match, err := regexp.MatchString(strings.ToLower(regex), strings.ToLower(fieldsToMatch))
    				if err != nil {
    					u.PrintlnErr("Error matching \""+regex+"\": "+err.Error())
    				} else {
    					if match {
    						if foundLongOutputFlag >= 0 {
    							u.Println(user.String())
    						} else {
    							u.Println(user.LastName+" | "+user.FirstName+" | "+user.Email)
    						}
    						break
    					}
    				}
    			}
    		}
    		return 0
    	} else {
    		u.PrintlnErr("Error: "+resp.Status()+": "+resp.String())
    		return 1
    	}
    }
    
    func getUsers(resp *resty.Response) ([]User, error) {
    	users := []User{}
    	if err := json.Unmarshal(resp.Body(), &users); err != nil {
    		return nil, err
    	}
    	return users, nil
    }