The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/pkg/services/sqlstore/user.go

337 lines
9.0 KiB

package sqlstore
import (
"bytes"
"context"
"fmt"
"sort"
"strconv"
"strings"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util"
)
func (ss *SQLStore) getOrgIDForNewUser(sess *DBSession, args user.CreateUserCommand) (int64, error) {
if ss.Cfg.AutoAssignOrg && args.OrgID != 0 {
if err := verifyExistingOrg(sess, args.OrgID); err != nil {
return -1, err
}
return args.OrgID, nil
}
orgName := args.OrgName
if orgName == "" {
orgName = util.StringsFallback2(args.Email, args.Login)
}
return ss.getOrCreateOrg(sess, orgName)
}
// createUser creates a user in the database
// if autoAssignOrg is enabled then args.OrgID will be used
// to add to an existing Org with id=args.OrgID
// if autoAssignOrg is disabled then args.OrgName will be used
// to create a new Org with name=args.OrgName.
// If a org already exists with that name, it will error
func (ss *SQLStore) createUser(ctx context.Context, sess *DBSession, args user.CreateUserCommand) (user.User, error) {
var usr user.User
var orgID int64 = -1
if !args.SkipOrgSetup {
var err error
orgID, err = ss.getOrgIDForNewUser(sess, args)
if err != nil {
return usr, err
}
}
if args.Email == "" {
args.Email = args.Login
}
where := "email=? OR login=?"
if ss.Cfg.CaseInsensitiveLogin {
where = "LOWER(email)=LOWER(?) OR LOWER(login)=LOWER(?)"
args.Login = strings.ToLower(args.Login)
args.Email = strings.ToLower(args.Email)
}
exists, err := sess.Where(where, args.Email, args.Login).Get(&user.User{})
if err != nil {
return usr, err
}
if exists {
return usr, user.ErrUserAlreadyExists
}
// create user
usr = user.User{
Email: args.Email,
Name: args.Name,
Login: args.Login,
Company: args.Company,
IsAdmin: args.IsAdmin,
IsDisabled: args.IsDisabled,
OrgID: orgID,
EmailVerified: args.EmailVerified,
Created: TimeNow(),
Updated: TimeNow(),
LastSeenAt: TimeNow().AddDate(-10, 0, 0),
IsServiceAccount: args.IsServiceAccount,
}
salt, err := util.GetRandomString(10)
if err != nil {
return usr, err
}
usr.Salt = salt
rands, err := util.GetRandomString(10)
if err != nil {
return usr, err
}
usr.Rands = rands
if len(args.Password) > 0 {
encodedPassword, err := util.EncodePassword(args.Password, usr.Salt)
if err != nil {
return usr, err
}
usr.Password = encodedPassword
}
sess.UseBool("is_admin")
if _, err := sess.Insert(&usr); err != nil {
return usr, err
}
sess.publishAfterCommit(&events.UserCreated{
Timestamp: usr.Created,
Id: usr.ID,
Name: usr.Name,
Login: usr.Login,
Email: usr.Email,
})
// create org user link
if !args.SkipOrgSetup {
orgUser := models.OrgUser{
OrgId: orgID,
UserId: usr.ID,
Role: org.RoleAdmin,
Created: TimeNow(),
Updated: TimeNow(),
}
if ss.Cfg.AutoAssignOrg && !usr.IsAdmin {
if len(args.DefaultOrgRole) > 0 {
orgUser.Role = org.RoleType(args.DefaultOrgRole)
} else {
orgUser.Role = org.RoleType(ss.Cfg.AutoAssignOrgRole)
}
}
if _, err = sess.Insert(&orgUser); err != nil {
return usr, err
}
}
return usr, nil
}
// deprecated method, use only for tests
func (ss *SQLStore) CreateUser(ctx context.Context, cmd user.CreateUserCommand) (*user.User, error) {
var user user.User
createErr := ss.WithTransactionalDbSession(ctx, func(sess *DBSession) (err error) {
user, err = ss.createUser(ctx, sess, cmd)
return
})
return &user, createErr
}
Auth: Adds validation and ingestion of conflict file (#53014) * add users-manager command * add users-manager command * rename files * refactor: imports and renaming * Command: add conflict merge user command - MergeUser will - replace all user_ids from conflicting users to the chosen userId - delete users whose user_ids are not the chosen user - SameIdentification will - update chosen user with chosen email,login details - delete users whose user_ids are not the chosen user * refactor: clean up * refactor: create structure for read, validate, ingest * feat: ls and generate-file for conflicting users * remove usagestats * added back pkg/services/login/authinfoservice/database/stats.go * Revert "added back pkg/services/login/authinfoservice/database/stats.go" This reverts commit 2ba6e3c4d602122bda86911c56934407904eb268. * Revert "remove usagestats" This reverts commit 1e3fa978100eed48f4bead0f631b8bd03e01588b. * cherry pick * Revert "cherry pick" This reverts commit 461626c306b9501e3e4eed05a5919caa7a3de884. * validation of picked merge user * fix test * make lint * make test run * tests for ingest working * clean up and refactored to align with downstream refactoring * formatting * refactor: name list instead of ls * fix: static lint error use trimprefix * WIP: permissions for validation * fix: remove unused functions in sqlstore * fix: remove unused function * handling of multiple users and resolve discarded users * fix tests * fix: bug that did not exclude the blocks * ioutil is blacklisted * WIP: validation * tests for merging a user working * add latest changes to output print * refactor: removed conflictEmail and conflictLogin that was not used * refactor: code clean up, showChanges working * test and linting fixes * test and linting fixes * refactor: removed logging of config and added more info for vlidation command * refactor: fix order of code * fix time now * refactor: no longer need for check casesensitive login/email * removed unnessecary loop * refactor: move functions around * test: working * docs: add docuemntationf for file * Add failing test for generating the conflict login block * Fix regex * Fix some stuff/tests Co-authored-by: eleijonmarck <eric.leijonmarck@gmail.com> * add: docs for conflict file * add: conflict_email, conflict_login fields * add: conflict_email, conflict_login fields * WIP * fix: tests working as intended * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: linoman <2051016+linoman@users.noreply.github.com> * review comments * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * missspelling * trailing new line * update to use userimpl store * remove newline * remove newline * refactor: initializing of resolver for conflicts * fix: test sqlStore * refactor: removed lines * refactor: remove TODOs Co-authored-by: Mihaly Gyongyosi <mgyongyosi@users.noreply.github.com> Co-authored-by: linoman <2051016+linoman@users.noreply.github.com>
3 years ago
func NotServiceAccountFilter(ss *SQLStore) string {
return fmt.Sprintf("%s.is_service_account = %s",
ss.Dialect.Quote("user"),
ss.Dialect.BooleanStr(false))
}
func setUsingOrgInTransaction(sess *DBSession, userID int64, orgID int64) error {
user := user.User{
ID: userID,
OrgID: orgID,
}
pkg/services/sqlstore: Fix sess.Id is deprecated: use ID instead. (megacheck) See, $ gometalinter --vendor --disable-all --enable=megacheck --disable=gotype --deadline 6m ./... | grep ID alert.go:193:15:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) alert.go:252:18:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) annotation.go:113:12:warning: sess.Table("annotation").Id is deprecated: use ID instead (SA1019) (megacheck) org.go:136:24:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) org.go:169:16:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) org_users.go:24:21:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) org_users.go:88:12:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) org_users.go:141:21:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) plugin_setting.go:103:12:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) preferences.go:97:12:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) quota.go:119:17:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) quota.go:221:17:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) team.go:77:24:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:243:16:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:267:13:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:282:13:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:313:12:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:475:3:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:479:13:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck) user.go:493:13:warning: sess.Id is deprecated: use ID instead (SA1019) (megacheck)
7 years ago
_, err := sess.ID(userID).Update(&user)
return err
}
type byOrgName []*models.UserOrgDTO
// Len returns the length of an array of organisations.
func (o byOrgName) Len() int {
return len(o)
}
// Swap swaps two indices of an array of organizations.
func (o byOrgName) Swap(i, j int) {
o[i], o[j] = o[j], o[i]
}
// Less returns whether element i of an array of organizations is less than element j.
func (o byOrgName) Less(i, j int) bool {
if strings.ToLower(o[i].Name) < strings.ToLower(o[j].Name) {
return true
}
return o[i].Name < o[j].Name
}
func (ss *SQLStore) GetUserOrgList(ctx context.Context, query *models.GetUserOrgListQuery) error {
return ss.WithDbSession(ctx, func(dbSess *DBSession) error {
query.Result = make([]*models.UserOrgDTO, 0)
sess := dbSess.Table("org_user")
sess.Join("INNER", "org", "org_user.org_id=org.id")
sess.Join("INNER", ss.Dialect.Quote("user"), fmt.Sprintf("org_user.user_id=%s.id", ss.Dialect.Quote("user")))
sess.Where("org_user.user_id=?", query.UserId)
Auth: Adds validation and ingestion of conflict file (#53014) * add users-manager command * add users-manager command * rename files * refactor: imports and renaming * Command: add conflict merge user command - MergeUser will - replace all user_ids from conflicting users to the chosen userId - delete users whose user_ids are not the chosen user - SameIdentification will - update chosen user with chosen email,login details - delete users whose user_ids are not the chosen user * refactor: clean up * refactor: create structure for read, validate, ingest * feat: ls and generate-file for conflicting users * remove usagestats * added back pkg/services/login/authinfoservice/database/stats.go * Revert "added back pkg/services/login/authinfoservice/database/stats.go" This reverts commit 2ba6e3c4d602122bda86911c56934407904eb268. * Revert "remove usagestats" This reverts commit 1e3fa978100eed48f4bead0f631b8bd03e01588b. * cherry pick * Revert "cherry pick" This reverts commit 461626c306b9501e3e4eed05a5919caa7a3de884. * validation of picked merge user * fix test * make lint * make test run * tests for ingest working * clean up and refactored to align with downstream refactoring * formatting * refactor: name list instead of ls * fix: static lint error use trimprefix * WIP: permissions for validation * fix: remove unused functions in sqlstore * fix: remove unused function * handling of multiple users and resolve discarded users * fix tests * fix: bug that did not exclude the blocks * ioutil is blacklisted * WIP: validation * tests for merging a user working * add latest changes to output print * refactor: removed conflictEmail and conflictLogin that was not used * refactor: code clean up, showChanges working * test and linting fixes * test and linting fixes * refactor: removed logging of config and added more info for vlidation command * refactor: fix order of code * fix time now * refactor: no longer need for check casesensitive login/email * removed unnessecary loop * refactor: move functions around * test: working * docs: add docuemntationf for file * Add failing test for generating the conflict login block * Fix regex * Fix some stuff/tests Co-authored-by: eleijonmarck <eric.leijonmarck@gmail.com> * add: docs for conflict file * add: conflict_email, conflict_login fields * add: conflict_email, conflict_login fields * WIP * fix: tests working as intended * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: linoman <2051016+linoman@users.noreply.github.com> * review comments * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * missspelling * trailing new line * update to use userimpl store * remove newline * remove newline * refactor: initializing of resolver for conflicts * fix: test sqlStore * refactor: removed lines * refactor: remove TODOs Co-authored-by: Mihaly Gyongyosi <mgyongyosi@users.noreply.github.com> Co-authored-by: linoman <2051016+linoman@users.noreply.github.com>
3 years ago
sess.Where(NotServiceAccountFilter(ss))
sess.Cols("org.name", "org_user.role", "org_user.org_id")
sess.OrderBy("org.name")
err := sess.Find(&query.Result)
sort.Sort(byOrgName(query.Result))
return err
})
}
// GetTeamsByUser is used by the Guardian when checking a users' permissions
// TODO: use team.Service after user service is split
func (ss *SQLStore) GetTeamsByUser(ctx context.Context, query *models.GetTeamsByUserQuery) error {
return ss.WithDbSession(ctx, func(sess *DBSession) error {
query.Result = make([]*models.TeamDTO, 0)
var sql bytes.Buffer
var params []interface{}
params = append(params, query.OrgId, query.UserId)
sql.WriteString(getTeamSelectSQLBase([]string{}))
sql.WriteString(` INNER JOIN team_member on team.id = team_member.team_id`)
sql.WriteString(` WHERE team.org_id = ? and team_member.user_id = ?`)
if !ac.IsDisabled(ss.Cfg) {
acFilter, err := ac.Filter(query.SignedInUser, "team.id", "teams:id:", ac.ActionTeamsRead)
if err != nil {
return err
}
sql.WriteString(` and` + acFilter.Where)
params = append(params, acFilter.Args...)
}
err := sess.SQL(sql.String(), params...).Find(&query.Result)
return err
})
}
func getTeamMemberCount(filteredUsers []string) string {
if len(filteredUsers) > 0 {
return `(SELECT COUNT(*) FROM team_member
INNER JOIN ` + dialect.Quote("user") + ` ON team_member.user_id = ` + dialect.Quote("user") + `.id
WHERE team_member.team_id = team.id AND ` + dialect.Quote("user") + `.login NOT IN (?` +
strings.Repeat(",?", len(filteredUsers)-1) + ")" +
`) AS member_count `
}
return "(SELECT COUNT(*) FROM team_member WHERE team_member.team_id = team.id) AS member_count "
}
func getTeamSelectSQLBase(filteredUsers []string) string {
return `SELECT
team.id as id,
team.org_id,
team.name as name,
team.email as email, ` +
getTeamMemberCount(filteredUsers) +
` FROM team as team `
}
Auth: Adds validation and ingestion of conflict file (#53014) * add users-manager command * add users-manager command * rename files * refactor: imports and renaming * Command: add conflict merge user command - MergeUser will - replace all user_ids from conflicting users to the chosen userId - delete users whose user_ids are not the chosen user - SameIdentification will - update chosen user with chosen email,login details - delete users whose user_ids are not the chosen user * refactor: clean up * refactor: create structure for read, validate, ingest * feat: ls and generate-file for conflicting users * remove usagestats * added back pkg/services/login/authinfoservice/database/stats.go * Revert "added back pkg/services/login/authinfoservice/database/stats.go" This reverts commit 2ba6e3c4d602122bda86911c56934407904eb268. * Revert "remove usagestats" This reverts commit 1e3fa978100eed48f4bead0f631b8bd03e01588b. * cherry pick * Revert "cherry pick" This reverts commit 461626c306b9501e3e4eed05a5919caa7a3de884. * validation of picked merge user * fix test * make lint * make test run * tests for ingest working * clean up and refactored to align with downstream refactoring * formatting * refactor: name list instead of ls * fix: static lint error use trimprefix * WIP: permissions for validation * fix: remove unused functions in sqlstore * fix: remove unused function * handling of multiple users and resolve discarded users * fix tests * fix: bug that did not exclude the blocks * ioutil is blacklisted * WIP: validation * tests for merging a user working * add latest changes to output print * refactor: removed conflictEmail and conflictLogin that was not used * refactor: code clean up, showChanges working * test and linting fixes * test and linting fixes * refactor: removed logging of config and added more info for vlidation command * refactor: fix order of code * fix time now * refactor: no longer need for check casesensitive login/email * removed unnessecary loop * refactor: move functions around * test: working * docs: add docuemntationf for file * Add failing test for generating the conflict login block * Fix regex * Fix some stuff/tests Co-authored-by: eleijonmarck <eric.leijonmarck@gmail.com> * add: docs for conflict file * add: conflict_email, conflict_login fields * add: conflict_email, conflict_login fields * WIP * fix: tests working as intended * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: linoman <2051016+linoman@users.noreply.github.com> * review comments * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * missspelling * trailing new line * update to use userimpl store * remove newline * remove newline * refactor: initializing of resolver for conflicts * fix: test sqlStore * refactor: removed lines * refactor: remove TODOs Co-authored-by: Mihaly Gyongyosi <mgyongyosi@users.noreply.github.com> Co-authored-by: linoman <2051016+linoman@users.noreply.github.com>
3 years ago
func (ss *SQLStore) DeleteUserInSession(ctx context.Context, sess *DBSession, cmd *models.DeleteUserCommand) error {
return deleteUserInTransaction(ss, sess, cmd)
}
func deleteUserInTransaction(ss *SQLStore, sess *DBSession, cmd *models.DeleteUserCommand) error {
// Check if user exists
usr := user.User{ID: cmd.UserId}
Auth: Adds validation and ingestion of conflict file (#53014) * add users-manager command * add users-manager command * rename files * refactor: imports and renaming * Command: add conflict merge user command - MergeUser will - replace all user_ids from conflicting users to the chosen userId - delete users whose user_ids are not the chosen user - SameIdentification will - update chosen user with chosen email,login details - delete users whose user_ids are not the chosen user * refactor: clean up * refactor: create structure for read, validate, ingest * feat: ls and generate-file for conflicting users * remove usagestats * added back pkg/services/login/authinfoservice/database/stats.go * Revert "added back pkg/services/login/authinfoservice/database/stats.go" This reverts commit 2ba6e3c4d602122bda86911c56934407904eb268. * Revert "remove usagestats" This reverts commit 1e3fa978100eed48f4bead0f631b8bd03e01588b. * cherry pick * Revert "cherry pick" This reverts commit 461626c306b9501e3e4eed05a5919caa7a3de884. * validation of picked merge user * fix test * make lint * make test run * tests for ingest working * clean up and refactored to align with downstream refactoring * formatting * refactor: name list instead of ls * fix: static lint error use trimprefix * WIP: permissions for validation * fix: remove unused functions in sqlstore * fix: remove unused function * handling of multiple users and resolve discarded users * fix tests * fix: bug that did not exclude the blocks * ioutil is blacklisted * WIP: validation * tests for merging a user working * add latest changes to output print * refactor: removed conflictEmail and conflictLogin that was not used * refactor: code clean up, showChanges working * test and linting fixes * test and linting fixes * refactor: removed logging of config and added more info for vlidation command * refactor: fix order of code * fix time now * refactor: no longer need for check casesensitive login/email * removed unnessecary loop * refactor: move functions around * test: working * docs: add docuemntationf for file * Add failing test for generating the conflict login block * Fix regex * Fix some stuff/tests Co-authored-by: eleijonmarck <eric.leijonmarck@gmail.com> * add: docs for conflict file * add: conflict_email, conflict_login fields * add: conflict_email, conflict_login fields * WIP * fix: tests working as intended * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: linoman <2051016+linoman@users.noreply.github.com> * review comments * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * Update pkg/cmd/grafana-cli/commands/conflict_user_command.go Co-authored-by: Misi <mgyongyosi@users.noreply.github.com> * missspelling * trailing new line * update to use userimpl store * remove newline * remove newline * refactor: initializing of resolver for conflicts * fix: test sqlStore * refactor: removed lines * refactor: remove TODOs Co-authored-by: Mihaly Gyongyosi <mgyongyosi@users.noreply.github.com> Co-authored-by: linoman <2051016+linoman@users.noreply.github.com>
3 years ago
has, err := sess.Where(NotServiceAccountFilter(ss)).Get(&usr)
if err != nil {
return err
}
if !has {
return user.ErrUserNotFound
}
for _, sql := range UserDeletions() {
ServiceAccounts: Delete ServiceAccount (#40470) * 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 * registering as backend service 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>
4 years ago
_, err := sess.Exec(sql, cmd.UserId)
if err != nil {
return err
}
}
return deleteUserAccessControl(sess, cmd.UserId)
}
func deleteUserAccessControl(sess *DBSession, userID int64) error {
// Delete user role assignments
if _, err := sess.Exec("DELETE FROM user_role WHERE user_id = ?", userID); err != nil {
return err
}
// Delete permissions that are scoped to user
if _, err := sess.Exec("DELETE FROM permission WHERE scope = ?", ac.Scope("users", "id", strconv.FormatInt(userID, 10))); err != nil {
return err
}
var roleIDs []int64
if err := sess.SQL("SELECT id FROM role WHERE name = ?", ac.ManagedUserRoleName(userID)).Find(&roleIDs); err != nil {
return err
}
if len(roleIDs) == 0 {
return nil
}
query := "DELETE FROM permission WHERE role_id IN(? " + strings.Repeat(",?", len(roleIDs)-1) + ")"
args := make([]interface{}, 0, len(roleIDs)+1)
args = append(args, query)
for _, id := range roleIDs {
args = append(args, id)
}
// Delete managed user permissions
if _, err := sess.Exec(args...); err != nil {
return err
}
// Delete managed user roles
if _, err := sess.Exec("DELETE FROM role WHERE name = ?", ac.ManagedUserRoleName(userID)); err != nil {
return err
}
ServiceAccounts: Delete ServiceAccount (#40470) * 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 * registering as backend service 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>
4 years ago
return nil
}
func UserDeletions() []string {
deletes := []string{
"DELETE FROM star WHERE user_id = ?",
"DELETE FROM " + dialect.Quote("user") + " WHERE id = ?",
"DELETE FROM org_user WHERE user_id = ?",
"DELETE FROM dashboard_acl WHERE user_id = ?",
"DELETE FROM preferences WHERE user_id = ?",
"DELETE FROM team_member WHERE user_id = ?",
"DELETE FROM user_auth WHERE user_id = ?",
"DELETE FROM user_auth_token WHERE user_id = ?",
"DELETE FROM quota WHERE user_id = ?",
}
ServiceAccounts: Delete ServiceAccount (#40470) * 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 * registering as backend service 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>
4 years ago
return deletes
}