mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
AccessControl: upgrade apikeys by adding service accounts (#42425)
Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com> Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Change default options for cloned service account * Run in background * Add endpoint to upgrade api keys to service accounts
This commit is contained in:
@@ -4,9 +4,10 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func (ss *SQLStore) addAPIKeysQueryAndCommandHandlers() {
|
||||
@@ -38,6 +39,21 @@ func (ss *SQLStore) GetAPIKeys(ctx context.Context, query *models.GetApiKeysQuer
|
||||
})
|
||||
}
|
||||
|
||||
// GetAPIKeys queries the database based
|
||||
// on input on GetApiKeysQuery
|
||||
func (ss *SQLStore) GetNonServiceAccountAPIKeys(ctx context.Context) []*models.ApiKey {
|
||||
result := make([]*models.ApiKey, 0)
|
||||
err := ss.WithDbSession(ctx, func(dbSession *DBSession) error {
|
||||
sess := dbSession. //CHECK how many API keys do our clients have? Can we load them all?
|
||||
Where("(expires IS NULL OR expires >= ?) AND service_account_id < 1 ", timeNow().Unix()).Asc("name")
|
||||
return sess.Find(&result)
|
||||
})
|
||||
if err != nil {
|
||||
ss.log.Warn("API key not loaded", "err", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (ss *SQLStore) DeleteApiKey(ctx context.Context, cmd *models.DeleteApiKeyCommand) error {
|
||||
return ss.WithDbSession(ctx, func(sess *DBSession) error {
|
||||
return deleteAPIKey(sess, cmd.Id, cmd.OrgId)
|
||||
@@ -96,6 +112,30 @@ func (ss *SQLStore) AddAPIKey(ctx context.Context, cmd *models.AddApiKeyCommand)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateApikeyServiceAccount sets a service account for an existing API key
|
||||
func (ss *SQLStore) UpdateApikeyServiceAccount(ctx context.Context, apikeyId int64, saccountId int64) error {
|
||||
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
|
||||
key := models.ApiKey{Id: apikeyId}
|
||||
exists, err := sess.Get(&key)
|
||||
if err != nil {
|
||||
ss.log.Warn("API key not loaded", "err", err)
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
ss.log.Warn("API key not found", "err", err)
|
||||
return models.ErrApiKeyNotFound
|
||||
}
|
||||
key.ServiceAccountId = saccountId
|
||||
|
||||
if _, err := sess.ID(key.Id).Update(&key); err != nil {
|
||||
ss.log.Warn("Could not update api key", "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (ss *SQLStore) GetApiKeyById(ctx context.Context, query *models.GetApiKeyByIdQuery) error {
|
||||
return ss.WithDbSession(ctx, func(sess *DBSession) error {
|
||||
var apikey models.ApiKey
|
||||
|
||||
Reference in New Issue
Block a user