Auth: You can now authenicate against api with username / password using basic auth, Closes #2218

This commit is contained in:
Torkel Ödegaard
2015-06-30 09:37:52 +02:00
parent d0e7d53c69
commit ae0f8c77d1
8 changed files with 126 additions and 0 deletions

View File

@@ -7,8 +7,10 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"hash"
"strings"
)
// source: https://github.com/gogits/gogs/blob/9ee80e3e5426821f03a4e99fad34418f5c736413/modules/base/tool.go#L58
@@ -80,3 +82,23 @@ func GetBasicAuthHeader(user string, password string) string {
var userAndPass = user + ":" + password
return "Basic " + base64.StdEncoding.EncodeToString([]byte(userAndPass))
}
func DecodeBasicAuthHeader(header string) (string, string, error) {
var code string
parts := strings.SplitN(header, " ", 2)
if len(parts) == 2 && parts[0] == "Basic" {
code = parts[1]
}
decoded, err := base64.StdEncoding.DecodeString(code)
if err != nil {
return "", "", err
}
userAndPass := strings.SplitN(string(decoded), ":", 2)
if len(userAndPass) != 2 {
return "", "", errors.New("Invalid basic auth header")
}
return userAndPass[0], userAndPass[1], nil
}

View File

@@ -13,4 +13,14 @@ func TestEncoding(t *testing.T) {
So(result, ShouldEqual, "Basic Z3JhZmFuYToxMjM0")
})
Convey("When decoding basic auth header", t, func() {
header := GetBasicAuthHeader("grafana", "1234")
username, password, err := DecodeBasicAuthHeader(header)
So(err, ShouldBeNil)
So(username, ShouldEqual, "grafana")
So(password, ShouldEqual, "1234")
})
}