Commit 3680b95b by Anthony Templeton Committed by Sofia Papagiannaki

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
parent 04e79703
......@@ -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{
......
......@@ -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
......
......@@ -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 {
......
......@@ -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())
})
})
})
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment