* Add extra fields to OSS types to support enterprise
* WIP service accounts
* Update public/app/features/api-keys/ApiKeysForm.tsx
Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com>
* Create a service account at the same time as the API key
* Use service account credentials when accessing API with APIkey
* Throw better error
* Use Boolean for "create service account button"
* Add GetRole to service, merge RoleDTO and Role structs
This patch merges the identical OSS and Enterprise data structures, which improves the code for two reasons:
1. Makes switching between OSS and Enterprise easier
2. Reduces the chance of incompatibilities developing between the same functions in OSS and Enterprise
* Start work cloning permissions onto service account
* If API key is not linked to a service account, continue login as usual
* Fallback to old auth if no service account linked to key
* Commented
* Add CloneUserToServiceAccount
* Update mock.go
* Put graphical bits behind a feature toggle
* Start adding LinkAPIKeyToServiceAccount
* Update pkg/models/user.go
Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>
* Update pkg/api/apikey.go
Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>
* Update pkg/api/apikey.go
Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>
* Finish LinkAPIKeyToServiceAccount
* Update comment
* Handle api key link error
* Update pkg/services/sqlstore/apikey.go
Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
* Feature toggle
* Update pkg/services/accesscontrol/accesscontrol.go
Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>
* Not needed (yet)
* Better error messages for OSS accesscontrol
* Set an invalid user id as default
* ServiceAccountId should be string
* Re-arrange field names
* ServiceAccountId is integer
* Update ossaccesscontrol.go
* Linter
* Remove fronend edits
* Remove console log
* Update ApiKeysForm.tsx
* feat: add serviceaccount deletion
* feat: make sure we do not accidently delete serviceaccount
* feat: ServiceAccount Type
* refactor: userDeletions function
* refactor: serviceaccount deletions\
* refactor: error name and removed attribute for userDeletecommand
* refactor:: remove serviceaccount type for now
* WIP
* add mocked function
* Remove unnecessary db query, move to right place
* Update pkg/services/accesscontrol/mock/mock.go
Co-authored-by: Gabriel MABILLE <gamab@users.noreply.github.com>
* Update pkg/services/accesscontrol/mock/mock.go
Co-authored-by: Gabriel MABILLE <gamab@users.noreply.github.com>
* Update pkg/services/accesscontrol/mock/mock.go
Co-authored-by: Gabriel MABILLE <gamab@users.noreply.github.com>
* Better error messages
* Better and correcter error messages
* add mocked function
* refactor: move function call, add error msg
* add IsServiceAccount and fix table
* add service accounts package
* WIP
* WIP
* working serviceaccountsapi registration
* WIP tests
* test
* test working
* test running for service
* moved the error out of the models package
* fixed own review
* linting errors
* Update pkg/services/serviceaccounts/database/database.go
Co-authored-by: Jeremy Price <Jeremy.price@grafana.com>
* tests running for api
* WIP
* WIP
* removed unused secrets background svc
* removed background svc for serviceaccount infavor or wire.go
* serviceaccounts manager tests
* wip
* Filtering service accounts from the user queries in frontend
* clean up
* Update pkg/services/sqlstore/org_test.go
* methods on same type should have same receiver
* _ unused variable and comment
* add additional join for results query
* remove unused code
* remove error fmt
* refactor: change to only have false
* no new variable to the left hand side
* refactor: create serviceaccount cmd
* dialect fix
Co-authored-by: Jeremy Price <jeremy.price@grafana.com>
Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com>
Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>
Co-authored-by: Gabriel MABILLE <gamab@users.noreply.github.com>
(cherry picked from commit 9c11040c3e)
Co-authored-by: Eric Leijonmarck <eric.leijonmarck@gmail.com>
301 lines
7.9 KiB
Go
301 lines
7.9 KiB
Go
package sqlstore
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/grafana/grafana/pkg/bus"
|
|
"github.com/grafana/grafana/pkg/models"
|
|
"github.com/grafana/grafana/pkg/util"
|
|
)
|
|
|
|
func (ss *SQLStore) addOrgUsersQueryAndCommandHandlers() {
|
|
bus.AddHandlerCtx("sql", ss.AddOrgUser)
|
|
bus.AddHandlerCtx("sql", ss.RemoveOrgUser)
|
|
bus.AddHandlerCtx("sql", ss.GetOrgUsers)
|
|
bus.AddHandlerCtx("sql", ss.UpdateOrgUser)
|
|
}
|
|
|
|
func (ss *SQLStore) AddOrgUser(ctx context.Context, cmd *models.AddOrgUserCommand) error {
|
|
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
|
|
// check if user exists
|
|
var user models.User
|
|
if exists, err := sess.ID(cmd.UserId).Get(&user); err != nil {
|
|
return err
|
|
} else if !exists {
|
|
return models.ErrUserNotFound
|
|
}
|
|
|
|
if res, err := sess.Query("SELECT 1 from org_user WHERE org_id=? and user_id=?", cmd.OrgId, user.Id); err != nil {
|
|
return err
|
|
} else if len(res) == 1 {
|
|
return models.ErrOrgUserAlreadyAdded
|
|
}
|
|
|
|
if res, err := sess.Query("SELECT 1 from org WHERE id=?", cmd.OrgId); err != nil {
|
|
return err
|
|
} else if len(res) != 1 {
|
|
return models.ErrOrgNotFound
|
|
}
|
|
|
|
entity := models.OrgUser{
|
|
OrgId: cmd.OrgId,
|
|
UserId: cmd.UserId,
|
|
Role: cmd.Role,
|
|
Created: time.Now(),
|
|
Updated: time.Now(),
|
|
}
|
|
|
|
_, err := sess.Insert(&entity)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var userOrgs []*models.UserOrgDTO
|
|
sess.Table("org_user")
|
|
sess.Join("INNER", "org", "org_user.org_id=org.id")
|
|
sess.Where("org_user.user_id=? AND org_user.org_id=?", user.Id, user.OrgId)
|
|
sess.Cols("org.name", "org_user.role", "org_user.org_id")
|
|
err = sess.Find(&userOrgs)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(userOrgs) == 0 {
|
|
return setUsingOrgInTransaction(sess, user.Id, cmd.OrgId)
|
|
}
|
|
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func (ss *SQLStore) UpdateOrgUser(ctx context.Context, cmd *models.UpdateOrgUserCommand) error {
|
|
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
|
|
var orgUser models.OrgUser
|
|
exists, err := sess.Where("org_id=? AND user_id=?", cmd.OrgId, cmd.UserId).Get(&orgUser)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !exists {
|
|
return models.ErrOrgUserNotFound
|
|
}
|
|
|
|
orgUser.Role = cmd.Role
|
|
orgUser.Updated = time.Now()
|
|
_, err = sess.ID(orgUser.Id).Update(&orgUser)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return validateOneAdminLeftInOrg(cmd.OrgId, sess)
|
|
})
|
|
}
|
|
|
|
func (ss *SQLStore) GetOrgUsers(ctx context.Context, query *models.GetOrgUsersQuery) error {
|
|
query.Result = make([]*models.OrgUserDTO, 0)
|
|
|
|
sess := x.Table("org_user")
|
|
sess.Join("INNER", x.Dialect().Quote("user"), fmt.Sprintf("org_user.user_id=%s.id", x.Dialect().Quote("user")))
|
|
|
|
whereConditions := make([]string, 0)
|
|
whereParams := make([]interface{}, 0)
|
|
|
|
whereConditions = append(whereConditions, "org_user.org_id = ?")
|
|
whereParams = append(whereParams, query.OrgId)
|
|
|
|
// TODO: add to chore, for cleaning up after we have created
|
|
// service accounts table in the modelling
|
|
whereConditions = append(whereConditions, fmt.Sprintf("%s.is_service_account = false", x.Dialect().Quote("user")))
|
|
|
|
if query.Query != "" {
|
|
queryWithWildcards := "%" + query.Query + "%"
|
|
whereConditions = append(whereConditions, "(email "+dialect.LikeStr()+" ? OR name "+dialect.LikeStr()+" ? OR login "+dialect.LikeStr()+" ?)")
|
|
whereParams = append(whereParams, queryWithWildcards, queryWithWildcards, queryWithWildcards)
|
|
}
|
|
|
|
if len(whereConditions) > 0 {
|
|
sess.Where(strings.Join(whereConditions, " AND "), whereParams...)
|
|
}
|
|
|
|
if query.Limit > 0 {
|
|
sess.Limit(query.Limit, 0)
|
|
}
|
|
|
|
sess.Cols(
|
|
"org_user.org_id",
|
|
"org_user.user_id",
|
|
"user.email",
|
|
"user.name",
|
|
"user.login",
|
|
"org_user.role",
|
|
"user.last_seen_at",
|
|
)
|
|
sess.Asc("user.email", "user.login")
|
|
|
|
if err := sess.Find(&query.Result); err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, user := range query.Result {
|
|
user.LastSeenAtAge = util.GetAgeString(user.LastSeenAt)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (ss *SQLStore) SearchOrgUsers(ctx context.Context, query *models.SearchOrgUsersQuery) error {
|
|
query.Result = models.SearchOrgUsersQueryResult{
|
|
OrgUsers: make([]*models.OrgUserDTO, 0),
|
|
}
|
|
|
|
sess := x.Table("org_user")
|
|
sess.Join("INNER", x.Dialect().Quote("user"), fmt.Sprintf("org_user.user_id=%s.id", x.Dialect().Quote("user")))
|
|
|
|
whereConditions := make([]string, 0)
|
|
whereParams := make([]interface{}, 0)
|
|
|
|
whereConditions = append(whereConditions, "org_user.org_id = ?")
|
|
whereParams = append(whereParams, query.OrgID)
|
|
|
|
// TODO: add to chore, for cleaning up after we have created
|
|
// service accounts table in the modelling
|
|
whereConditions = append(whereConditions, fmt.Sprintf("%s.is_service_account = false", x.Dialect().Quote("user")))
|
|
|
|
if query.Query != "" {
|
|
queryWithWildcards := "%" + query.Query + "%"
|
|
whereConditions = append(whereConditions, "(email "+dialect.LikeStr()+" ? OR name "+dialect.LikeStr()+" ? OR login "+dialect.LikeStr()+" ?)")
|
|
whereParams = append(whereParams, queryWithWildcards, queryWithWildcards, queryWithWildcards)
|
|
}
|
|
|
|
if len(whereConditions) > 0 {
|
|
sess.Where(strings.Join(whereConditions, " AND "), whereParams...)
|
|
}
|
|
|
|
if query.Limit > 0 {
|
|
offset := query.Limit * (query.Page - 1)
|
|
sess.Limit(query.Limit, offset)
|
|
}
|
|
|
|
sess.Cols(
|
|
"org_user.org_id",
|
|
"org_user.user_id",
|
|
"user.email",
|
|
"user.name",
|
|
"user.login",
|
|
"org_user.role",
|
|
"user.last_seen_at",
|
|
)
|
|
sess.Asc("user.email", "user.login")
|
|
|
|
if err := sess.Find(&query.Result.OrgUsers); err != nil {
|
|
return err
|
|
}
|
|
|
|
// get total count
|
|
orgUser := models.OrgUser{}
|
|
countSess := x.Table("org_user").
|
|
Join("INNER", x.Dialect().Quote("user"), fmt.Sprintf("org_user.user_id=%s.id", x.Dialect().Quote("user")))
|
|
|
|
if len(whereConditions) > 0 {
|
|
countSess.Where(strings.Join(whereConditions, " AND "), whereParams...)
|
|
}
|
|
|
|
count, err := countSess.Count(&orgUser)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
query.Result.TotalCount = count
|
|
|
|
for _, user := range query.Result.OrgUsers {
|
|
user.LastSeenAtAge = util.GetAgeString(user.LastSeenAt)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (ss *SQLStore) RemoveOrgUser(ctx context.Context, cmd *models.RemoveOrgUserCommand) error {
|
|
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
|
|
// check if user exists
|
|
var user models.User
|
|
if exists, err := sess.ID(cmd.UserId).Get(&user); err != nil {
|
|
return err
|
|
} else if !exists {
|
|
return models.ErrUserNotFound
|
|
}
|
|
|
|
deletes := []string{
|
|
"DELETE FROM org_user WHERE org_id=? and user_id=?",
|
|
"DELETE FROM dashboard_acl WHERE org_id=? and user_id = ?",
|
|
"DELETE FROM team_member WHERE org_id=? and user_id = ?",
|
|
}
|
|
|
|
for _, sql := range deletes {
|
|
_, err := sess.Exec(sql, cmd.OrgId, cmd.UserId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// validate that after delete there is at least one user with admin role in org
|
|
if err := validateOneAdminLeftInOrg(cmd.OrgId, sess); err != nil {
|
|
return err
|
|
}
|
|
|
|
// check user other orgs and update user current org
|
|
var userOrgs []*models.UserOrgDTO
|
|
sess.Table("org_user")
|
|
sess.Join("INNER", "org", "org_user.org_id=org.id")
|
|
sess.Where("org_user.user_id=?", user.Id)
|
|
sess.Cols("org.name", "org_user.role", "org_user.org_id")
|
|
err := sess.Find(&userOrgs)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(userOrgs) > 0 {
|
|
hasCurrentOrgSet := false
|
|
for _, userOrg := range userOrgs {
|
|
if user.OrgId == userOrg.OrgId {
|
|
hasCurrentOrgSet = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !hasCurrentOrgSet {
|
|
err = setUsingOrgInTransaction(sess, user.Id, userOrgs[0].OrgId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
} else if cmd.ShouldDeleteOrphanedUser {
|
|
// no other orgs, delete the full user
|
|
if err := deleteUserInTransaction(sess, &models.DeleteUserCommand{UserId: user.Id}); err != nil {
|
|
return err
|
|
}
|
|
|
|
cmd.UserWasDeleted = true
|
|
}
|
|
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func validateOneAdminLeftInOrg(orgId int64, sess *DBSession) error {
|
|
// validate that there is an admin user left
|
|
res, err := sess.Query("SELECT 1 from org_user WHERE org_id=? and role='Admin'", orgId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(res) == 0 {
|
|
return models.ErrLastOrgAdmin
|
|
}
|
|
|
|
return err
|
|
}
|