File: auth.go

package info (click to toggle)
golang-github-vulcand-oxy 2.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 728 kB
  • sloc: makefile: 14
file content (43 lines) | stat: -rw-r--r-- 1,181 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package utils

import (
	"encoding/base64"
	"fmt"
	"strings"
)

// BasicAuth basic auth information.
type BasicAuth struct {
	Username string
	Password string
}

func (ba *BasicAuth) String() string {
	encoded := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.Username, ba.Password)))
	return fmt.Sprintf("Basic %s", encoded)
}

// ParseAuthHeader creates a new BasicAuth from header values.
func ParseAuthHeader(header string) (*BasicAuth, error) {
	values := strings.Fields(header)
	if len(values) != 2 {
		return nil, fmt.Errorf("failed to parse header '%s'", header)
	}

	authType := strings.ToLower(values[0])
	if authType != "basic" {
		return nil, fmt.Errorf("expected basic auth type, got '%s'", authType)
	}

	encodedString := values[1]
	decodedString, err := base64.StdEncoding.DecodeString(encodedString)
	if err != nil {
		return nil, fmt.Errorf("failed to parse header '%s', base64 failed: %w", header, err)
	}

	values = strings.SplitN(string(decodedString), ":", 2)
	if len(values) != 2 {
		return nil, fmt.Errorf("failed to parse header '%s', expected separator ':'", header)
	}
	return &BasicAuth{Username: values[0], Password: values[1]}, nil
}