浏览代码

Auth: Duplicate API Key Name Handle With Useful HTTP Code (#17905)

* API: Duplicate API Key Name Handle With Useful HTTP Code

* 17447: make changes requested during review

- use dialect.IsUniqueContraintViolation
- change if statement to match others
- return error properly

* Revert "17447: make changes requested during review"

This reverts commit a4a674ea83a9288701611f203f2a75531fb8a131.

* API: useful http code on duplicate api key error w/ tests

* API: API Key Duplicate Handling

fixed small typo associated with error
Anthony Templeton 6 年之前
父节点
当前提交
3680b95b44
共有 4 个文件被更改,包括 31 次插入1 次删除
  1. 4 1
      pkg/api/apikey.go
  2. 1 0
      pkg/models/apikey.go
  3. 6 0
      pkg/services/sqlstore/apikey.go
  4. 20 0
      pkg/services/sqlstore/apikey_test.go

+ 4 - 1
pkg/api/apikey.go

@@ -68,7 +68,10 @@ func (hs *HTTPServer) AddAPIKey(c *models.ReqContext, cmd models.AddApiKeyComman
 		if err == models.ErrInvalidApiKeyExpiration {
 			return Error(400, err.Error(), nil)
 		}
-		return Error(500, "Failed to add API key", err)
+		if err == models.ErrDuplicateApiKey {
+			return Error(409, err.Error(), nil)
+		}
+		return Error(500, "Failed to add API Key", err)
 	}
 
 	result := &dtos.NewApiKeyResult{

+ 1 - 0
pkg/models/apikey.go

@@ -7,6 +7,7 @@ import (
 
 var ErrInvalidApiKey = errors.New("Invalid API Key")
 var ErrInvalidApiKeyExpiration = errors.New("Negative value for SecondsToLive")
+var ErrDuplicateApiKey = errors.New("API Key Organization ID And Name Must Be Unique")
 
 type ApiKey struct {
 	Id      int64

+ 6 - 0
pkg/services/sqlstore/apikey.go

@@ -37,6 +37,12 @@ func DeleteApiKeyCtx(ctx context.Context, cmd *models.DeleteApiKeyCommand) error
 
 func AddApiKey(cmd *models.AddApiKeyCommand) error {
 	return inTransaction(func(sess *DBSession) error {
+		key := models.ApiKey{OrgId: cmd.OrgId, Name: cmd.Name}
+		exists, _ := sess.Get(&key)
+		if exists {
+			return models.ErrDuplicateApiKey
+		}
+
 		updated := timeNow()
 		var expires *int64 = nil
 		if cmd.SecondsToLive > 0 {

+ 20 - 0
pkg/services/sqlstore/apikey_test.go

@@ -115,3 +115,23 @@ func TestApiKeyDataAccess(t *testing.T) {
 		})
 	})
 }
+
+func TestApiKeyErrors(t *testing.T) {
+	mockTimeNow()
+	defer resetTimeNow()
+
+	t.Run("Testing API Duplicate Key Errors", func(t *testing.T) {
+		InitTestDB(t)
+		t.Run("Given saved api key", func(t *testing.T) {
+			cmd := models.AddApiKeyCommand{OrgId: 0, Name: "duplicate", Key: "asd"}
+			err := AddApiKey(&cmd)
+			assert.Nil(t, err)
+
+			t.Run("Add API Key with existing Org ID and Name", func(t *testing.T) {
+				cmd := models.AddApiKeyCommand{OrgId: 0, Name: "duplicate", Key: "asd"}
+				err = AddApiKey(&cmd)
+				assert.EqualError(t, err, models.ErrDuplicateApiKey.Error())
+			})
+		})
+	})
+}