mirror of
https://github.com/pikami/cosmium.git
synced 2025-12-18 08:20:56 +00:00
Implement authentication
This commit is contained in:
26
internal/authentication/authentication.go
Normal file
26
internal/authentication/authentication.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// https://learn.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources
|
||||
func GenerateSignature(verb string, resourceType string, resourceId string, date string, masterKey string) string {
|
||||
payload := fmt.Sprintf(
|
||||
"%s\n%s\n%s\n%s\n%s\n",
|
||||
strings.ToLower(verb),
|
||||
strings.ToLower(resourceType),
|
||||
resourceId,
|
||||
strings.ToLower(date),
|
||||
"")
|
||||
|
||||
masterKeyBytes, _ := base64.StdEncoding.DecodeString(masterKey)
|
||||
hash := hmac.New(sha256.New, masterKeyBytes)
|
||||
hash.Write([]byte(payload))
|
||||
signature := base64.StdEncoding.EncodeToString(hash.Sum(nil))
|
||||
return signature
|
||||
}
|
||||
30
internal/authentication/authentication_test.go
Normal file
30
internal/authentication/authentication_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package authentication_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/pikami/cosmium/api/config"
|
||||
"github.com/pikami/cosmium/internal/authentication"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const (
|
||||
testDate = "Fri, 17 Dec 1926 03:15:00 GMT"
|
||||
)
|
||||
|
||||
func Test_GenerateSignature(t *testing.T) {
|
||||
t.Run("Should generate GET signature", func(t *testing.T) {
|
||||
signature := authentication.GenerateSignature("GET", "colls", "dbs/Test Database/colls/Test Collection", testDate, config.DefaultAccountKey)
|
||||
assert.Equal(t, "cugjaA51bjCvxVi8LXg3XB+ZVKaFAZshILoJZF9nfEY=", signature)
|
||||
})
|
||||
|
||||
t.Run("Should generate POST signature", func(t *testing.T) {
|
||||
signature := authentication.GenerateSignature("POST", "colls", "dbs/Test Database", testDate, config.DefaultAccountKey)
|
||||
assert.Equal(t, "E92FgDG9JiNX+NfsI+edOFtgkZRDkrrJxIfl12Vsu8A=", signature)
|
||||
})
|
||||
|
||||
t.Run("Should generate DELETE signature", func(t *testing.T) {
|
||||
signature := authentication.GenerateSignature("DELETE", "dbs", "dbs/Test Database", testDate, config.DefaultAccountKey)
|
||||
assert.Equal(t, "LcuXXg0TcXxZG0kUCj9tZIWRy2yCzim3oiqGiHpRqGs=", signature)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user