mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
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 a4a674ea83
.
* API: useful http code on duplicate api key error w/ tests
* API: API Key Duplicate Handling
fixed small typo associated with error
This commit is contained in:
parent
04e7970375
commit
3680b95b44
@ -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())
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user