2021-11-11 09:10:24 -06:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2021-12-14 07:39:25 -06:00
|
|
|
"github.com/google/uuid"
|
2021-11-11 09:10:24 -06:00
|
|
|
"github.com/grafana/grafana/pkg/models"
|
|
|
|
"github.com/grafana/grafana/pkg/services/serviceaccounts"
|
|
|
|
"github.com/grafana/grafana/pkg/services/sqlstore"
|
2021-12-14 07:39:25 -06:00
|
|
|
"github.com/pkg/errors"
|
2021-11-11 09:10:24 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
type ServiceAccountsStoreImpl struct {
|
|
|
|
sqlStore *sqlstore.SQLStore
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewServiceAccountsStore(store *sqlstore.SQLStore) *ServiceAccountsStoreImpl {
|
|
|
|
return &ServiceAccountsStoreImpl{
|
|
|
|
sqlStore: store,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-14 07:39:25 -06:00
|
|
|
func (s *ServiceAccountsStoreImpl) CreateServiceAccount(ctx context.Context, sa *serviceaccounts.CreateServiceaccountForm) (user *models.User, err error) {
|
|
|
|
// create a new service account - "user" with empty permissions
|
|
|
|
cmd := models.CreateUserCommand{
|
|
|
|
Login: "Service-Account-" + uuid.New().String(),
|
|
|
|
Name: sa.Name + "-Service-Account-" + uuid.New().String(),
|
|
|
|
OrgId: sa.OrgID,
|
|
|
|
IsServiceAccount: true,
|
|
|
|
}
|
|
|
|
newuser, err := s.sqlStore.CreateUser(ctx, cmd)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Errorf("Failed to create user: %v", err)
|
|
|
|
}
|
|
|
|
return newuser, nil
|
|
|
|
}
|
|
|
|
|
2021-11-11 09:10:24 -06:00
|
|
|
func (s *ServiceAccountsStoreImpl) DeleteServiceAccount(ctx context.Context, orgID, serviceaccountID int64) error {
|
|
|
|
return s.sqlStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
|
|
|
|
return deleteServiceAccountInTransaction(sess, orgID, serviceaccountID)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func deleteServiceAccountInTransaction(sess *sqlstore.DBSession, orgID, serviceAccountID int64) error {
|
|
|
|
user := models.User{}
|
|
|
|
has, err := sess.Where(`org_id = ? and id = ? and is_service_account = true`, orgID, serviceAccountID).Get(&user)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !has {
|
|
|
|
return serviceaccounts.ErrServiceAccountNotFound
|
|
|
|
}
|
|
|
|
for _, sql := range sqlstore.ServiceAccountDeletions() {
|
|
|
|
_, err := sess.Exec(sql, user.Id)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|