57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
/*
|
|
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
|
|
*
|
|
* This work is published and licensed under a Creative Commons
|
|
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
|
|
*
|
|
* Distribution of this work is permitted, but commercial use and
|
|
* modifications are strictly prohibited.
|
|
*/
|
|
|
|
package auxhttp
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
func EncodeBasicAuth(username, password string) string {
|
|
auth := username + ":" + password
|
|
return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
|
}
|
|
|
|
func ParseBasicAuth(basicFields string) (string, string, error) {
|
|
var err error
|
|
var username string
|
|
var password string
|
|
if basicFields == "" {
|
|
err := fmt.Errorf("Empty auth field")
|
|
return username, password, err
|
|
}
|
|
authFields := strings.SplitN(basicFields, " ", 2)
|
|
if len(authFields) < 2 {
|
|
err = fmt.Errorf("Cannot split auth field: %s", basicFields)
|
|
return username, password, err
|
|
}
|
|
authType := strings.TrimSpace(authFields[0])
|
|
if strings.ToLower(authType) != strings.ToLower("Basic") {
|
|
err = fmt.Errorf("Not basic auth type")
|
|
return username, password, err
|
|
}
|
|
authPairEncoded := authFields[1]
|
|
pairEncoded, err := base64.StdEncoding.DecodeString(authPairEncoded)
|
|
if err != nil {
|
|
err = fmt.Errorf("Cannon decode auth pair")
|
|
return username, password, err
|
|
}
|
|
authPair := strings.SplitN(string(pairEncoded), ":", 2)
|
|
if len(authPair) != 2 {
|
|
err = fmt.Errorf("Wrong auth pair")
|
|
return username, password, err
|
|
}
|
|
username = authPair[0]
|
|
password = authPair[1]
|
|
return username, password, err
|
|
}
|