add context to api crud calls (#40047)

Signed-off-by: bergquist <carl.bergquist@gmail.com>
This commit is contained in:
Carl Bergquist
2021-10-11 14:35:31 +02:00
committed by GitHub
parent c9f25cf0a5
commit f20de5588b
4 changed files with 43 additions and 28 deletions

View File

@ -6,25 +6,36 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"xorm.io/xorm"
)
func init() {
bus.AddHandler("sql", GetApiKeys)
bus.AddHandlerCtx("sql", GetAPIKeys)
bus.AddHandler("sql", GetApiKeyById)
bus.AddHandler("sql", GetApiKeyByName)
bus.AddHandlerCtx("sql", DeleteApiKeyCtx)
bus.AddHandler("sql", AddApiKey)
bus.AddHandlerCtx("sql", AddAPIKey)
}
func GetApiKeys(query *models.GetApiKeysQuery) error {
sess := x.Limit(100, 0).Where("org_id=? and ( expires IS NULL or expires >= ?)",
query.OrgId, timeNow().Unix()).Asc("name")
if query.IncludeExpired {
sess = x.Limit(100, 0).Where("org_id=?", query.OrgId).Asc("name")
}
// GetAPIKeys queries the database based
// on input on GetApiKeysQuery
func GetAPIKeys(ctx context.Context, query *models.GetApiKeysQuery) error {
return withDbSession(ctx, x, func(dbSession *DBSession) error {
var sess *xorm.Session
query.Result = make([]*models.ApiKey, 0)
return sess.Find(&query.Result)
if query.IncludeExpired {
sess = dbSession.Limit(100, 0).
Where("org_id=?", query.OrgId).
Asc("name")
} else {
sess = dbSession.Limit(100, 0).
Where("org_id=? and ( expires IS NULL or expires >= ?)", query.OrgId, timeNow().Unix()).
Asc("name")
}
query.Result = make([]*models.ApiKey, 0)
return sess.Find(&query.Result)
})
}
func DeleteApiKeyCtx(ctx context.Context, cmd *models.DeleteApiKeyCommand) error {
@ -48,8 +59,9 @@ func deleteAPIKey(sess *DBSession, id, orgID int64) error {
return nil
}
func AddApiKey(cmd *models.AddApiKeyCommand) error {
return inTransaction(func(sess *DBSession) error {
// AddAPIKey adds the API key to the database.
func AddAPIKey(ctx context.Context, cmd *models.AddApiKeyCommand) error {
return inTransactionCtx(ctx, func(sess *DBSession) error {
key := models.ApiKey{OrgId: cmd.OrgId, Name: cmd.Name}
exists, _ := sess.Get(&key)
if exists {