pkg/util: Check errors (#19832)
* pkg/util: Check errors * pkg/services: DRY up code
This commit is contained in:
@@ -21,20 +21,30 @@ type ApiKeyJson struct {
|
||||
OrgId int64 `json:"id"`
|
||||
}
|
||||
|
||||
func New(orgId int64, name string) KeyGenResult {
|
||||
jsonKey := ApiKeyJson{}
|
||||
func New(orgId int64, name string) (KeyGenResult, error) {
|
||||
result := KeyGenResult{}
|
||||
|
||||
jsonKey := ApiKeyJson{}
|
||||
jsonKey.OrgId = orgId
|
||||
jsonKey.Name = name
|
||||
jsonKey.Key = util.GetRandomString(32)
|
||||
var err error
|
||||
jsonKey.Key, err = util.GetRandomString(32)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
result := KeyGenResult{}
|
||||
result.HashedKey = util.EncodePassword(jsonKey.Key, name)
|
||||
result.HashedKey, err = util.EncodePassword(jsonKey.Key, name)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
jsonString, _ := json.Marshal(jsonKey)
|
||||
jsonString, err := json.Marshal(jsonKey)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
result.ClientSecret = base64.StdEncoding.EncodeToString(jsonString)
|
||||
return result
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func Decode(keyString string) (*ApiKeyJson, error) {
|
||||
@@ -52,7 +62,10 @@ func Decode(keyString string) (*ApiKeyJson, error) {
|
||||
return &keyObj, nil
|
||||
}
|
||||
|
||||
func IsValid(key *ApiKeyJson, hashedKey string) bool {
|
||||
check := util.EncodePassword(key.Key, key.Name)
|
||||
return check == hashedKey
|
||||
func IsValid(key *ApiKeyJson, hashedKey string) (bool, error) {
|
||||
check, err := util.EncodePassword(key.Key, key.Name)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return check == hashedKey, nil
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ import (
|
||||
func TestApiKeyGen(t *testing.T) {
|
||||
|
||||
Convey("When generating new api key", t, func() {
|
||||
result := New(12, "Cool key")
|
||||
result, err := New(12, "Cool key")
|
||||
So(err, ShouldBeNil)
|
||||
|
||||
So(result.ClientSecret, ShouldNotBeEmpty)
|
||||
So(result.HashedKey, ShouldNotBeEmpty)
|
||||
@@ -19,7 +20,8 @@ func TestApiKeyGen(t *testing.T) {
|
||||
keyInfo, err := Decode(result.ClientSecret)
|
||||
So(err, ShouldBeNil)
|
||||
|
||||
keyHashed := util.EncodePassword(keyInfo.Key, keyInfo.Name)
|
||||
keyHashed, err := util.EncodePassword(keyInfo.Key, keyInfo.Name)
|
||||
So(err, ShouldBeNil)
|
||||
So(keyHashed, ShouldEqual, result.HashedKey)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user