Select Git revision
-
Francé Wilke authoredFrancé Wilke authored
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()
}