Skip to content
Snippets Groups Projects
Select Git revision
  • 10de62dad89fba342c81539f0611c248a4aa32be
  • main default protected
  • trading_hours
  • refactor_trading_hours
  • audit_cleaning_cater_for_non_struct_fields
  • remove-info-logs
  • sl-refactor
  • 18-use-scan-for-param-values
  • 17-order-search-results
  • 4-simplify-framework-2
  • 1-http-error
  • v1.297.0
  • v1.296.0
  • v1.295.0
  • v1.294.0
  • v1.293.0
  • v1.292.0
  • v1.291.0
  • v1.290.0
  • v1.289.0
  • v1.288.0
  • v1.287.0
  • v1.286.0
  • v1.285.0
  • v1.284.0
  • v1.283.0
  • v1.282.0
  • v1.281.0
  • v1.280.0
  • v1.279.0
  • v1.278.0
31 results

common.go

Blame
  • common.go 1.61 KiB
    package auth
    
    import (
    	"fmt"
    	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/handler_utils"
    	"golang.org/x/crypto/bcrypt"
    	"math/rand"
    	"strings"
    )
    
    // GetBearerTokenFromHeaders checks if a bearer token is passed as part of the Authorization header and returns that key
    func GetBearerTokenFromHeaders(headers map[string]string) string {
    	headerValue := handler_utils.FindHeaderValue(headers, "authorization")
    	if strings.HasPrefix(strings.ToLower(headerValue), "bearer ") {
    		headerValues := strings.Split(headerValue, " ")
    		return strings.TrimSpace(headerValues[1])
    	}
    	return ""
    }
    
    // HashPassword returns a hashed version of the provided password.
    func HashPassword(password string) (string, error) {
    	encryptedBytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    	if err != nil {
    		return "", err
    	}
    	return string(encryptedBytes), nil
    }
    
    // PasswordIsCorrect checks whether the password is correct by validating it against the hashed password.
    func PasswordIsCorrect(password string, hashedPassword string) bool {
    	err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
    	return err == nil
    }
    
    // Create a pseudorandom password consisting of two three-letter words and two digits
    func RandomPassword() string {
    	i := rand.Intn(100)
    	var j int
    	for {
    		j = rand.Intn(100)
    		if j != i {
    			break
    		}
    	}
    	return fmt.Sprintf("%s%s%s", words[i], words[j], RandomDigitString(2))
    }
    
    // Create a pseudorandom string of digits (0-9) with specified length
    func RandomDigitString(len int) string {
    	var str strings.Builder
    	for i := 0; i < len; i++ {
    		fmt.Fprintf(&str, "%v", rand.Intn(10))
    	}
    	return str.String()
    }