mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Auth: You can now authenicate against api with username / password using basic auth, Closes #2218
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user