mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
ServiceAccounts: Add identifiable token prefix to service account tokens (#49011)
* Add prefixed API key gen. * Retrieve API Key by hash * Handle prefixed API keys for login * Add placeholder key generator * fix spelling * add get by hash sqlstore test * reformat query * quote usage of reserved keyword key * use constant * improve error handling and pre-select key type Co-authored-by: Victor Cinaglia <victor@grafana.com> * nits Co-authored-by: Victor Cinaglia <victor@grafana.com>
This commit is contained in:
@@ -2,6 +2,7 @@ package sqlstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"xorm.io/xorm"
|
||||
@@ -144,3 +145,19 @@ func (ss *SQLStore) GetApiKeyByName(ctx context.Context, query *models.GetApiKey
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (ss *SQLStore) GetAPIKeyByHash(ctx context.Context, hash string) (*models.ApiKey, error) {
|
||||
var apikey models.ApiKey
|
||||
err := ss.WithDbSession(ctx, func(sess *DBSession) error {
|
||||
has, err := sess.Table("api_key").Where(fmt.Sprintf("%s = ?", dialect.Quote("key")), hash).Get(&apikey)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !has {
|
||||
return models.ErrInvalidApiKey
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return &apikey, err
|
||||
}
|
||||
|
||||
@@ -35,6 +35,13 @@ func TestApiKeyDataAccess(t *testing.T) {
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, query.Result)
|
||||
})
|
||||
|
||||
t.Run("Should be able to get key by hash", func(t *testing.T) {
|
||||
key, err := ss.GetAPIKeyByHash(context.Background(), cmd.Key)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.NotNil(t, key)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("Add non expiring key", func(t *testing.T) {
|
||||
|
||||
@@ -635,3 +635,7 @@ func (m *SQLStoreMock) GetDashboardPermissionsForUser(ctx context.Context, query
|
||||
func (m *SQLStoreMock) IsAdminOfTeams(ctx context.Context, query *models.IsAdminOfTeamsQuery) error {
|
||||
return m.ExpectedError
|
||||
}
|
||||
|
||||
func (m *SQLStoreMock) GetAPIKeyByHash(ctx context.Context, hash string) (*models.ApiKey, error) {
|
||||
return nil, m.ExpectedError
|
||||
}
|
||||
|
||||
@@ -128,6 +128,7 @@ type Store interface {
|
||||
AddAPIKey(ctx context.Context, cmd *models.AddApiKeyCommand) error
|
||||
GetApiKeyById(ctx context.Context, query *models.GetApiKeyByIdQuery) error
|
||||
GetApiKeyByName(ctx context.Context, query *models.GetApiKeyByNameQuery) error
|
||||
GetAPIKeyByHash(ctx context.Context, hash string) (*models.ApiKey, error)
|
||||
UpdateTempUserStatus(ctx context.Context, cmd *models.UpdateTempUserStatusCommand) error
|
||||
CreateTempUser(ctx context.Context, cmd *models.CreateTempUserCommand) error
|
||||
UpdateTempUserWithEmailSent(ctx context.Context, cmd *models.UpdateTempUserWithEmailSentCommand) error
|
||||
|
||||
Reference in New Issue
Block a user