From 9256a520a41c72e1b2635b2a99b74069112776d5 Mon Sep 17 00:00:00 2001 From: Kristin Laemmert Date: Fri, 27 Jan 2023 13:36:54 -0500 Subject: [PATCH] chore: move user_auth models to (mostly) login service (#62269) * chore: move user_auth models to (mostly) login service --- pkg/api/admin_users.go | 5 +- pkg/api/ldap_debug.go | 23 ++- pkg/api/ldap_debug_test.go | 28 ++-- pkg/api/login.go | 13 +- pkg/api/login_oauth.go | 18 +-- pkg/api/login_test.go | 22 +-- pkg/api/org_users.go | 3 +- pkg/api/password.go | 2 +- pkg/api/pluginproxy/ds_proxy_test.go | 8 +- pkg/api/user.go | 6 +- pkg/api/user_test.go | 12 +- pkg/login/auth.go | 5 +- pkg/login/auth_test.go | 16 +- pkg/login/grafana_login.go | 4 +- pkg/login/grafana_login_test.go | 6 +- pkg/login/ldap_login.go | 7 +- pkg/login/ldap_login_test.go | 19 +-- pkg/middleware/middleware_test.go | 16 +- pkg/models/user_auth.go | 138 ------------------ pkg/services/auth/authtest/testing.go | 13 +- pkg/services/authn/authn.go | 8 +- .../authnimpl/sync/oauth_token_sync_test.go | 20 +-- .../authn/authnimpl/sync/org_sync_test.go | 9 +- .../authn/authnimpl/sync/user_sync.go | 11 +- .../authn/authnimpl/sync/user_sync_test.go | 40 ++--- pkg/services/authn/clients/grafana_test.go | 9 +- pkg/services/authn/clients/jwt_test.go | 4 +- pkg/services/authn/clients/ldap.go | 16 +- pkg/services/authn/clients/ldap_test.go | 22 +-- pkg/services/contexthandler/auth_jwt.go | 9 +- .../contexthandler/auth_proxy_test.go | 4 +- .../contexthandler/authproxy/authproxy.go | 11 +- pkg/services/contexthandler/contexthandler.go | 5 +- pkg/services/hooks/hooks.go | 6 +- pkg/services/ldap/ldap.go | 23 ++- pkg/services/ldap/ldap_groups.go | 6 +- pkg/services/ldap/ldap_login_test.go | 4 +- pkg/services/ldap/ldap_private_test.go | 8 +- pkg/services/ldap/model.go | 7 + pkg/services/login/authinfo.go | 13 +- .../authinfoservice/database/database.go | 29 ++-- pkg/services/login/authinfoservice/service.go | 29 ++-- .../login/authinfoservice/user_auth_test.go | 113 +++++++------- pkg/services/login/login.go | 5 +- .../login/loginservice/loginservice.go | 17 +-- .../login/loginservice/loginservice_mock.go | 5 +- .../login/loginservice/loginservice_test.go | 46 +++--- pkg/services/login/logintest/logintest.go | 25 ++-- pkg/services/login/model.go | 126 ++++++++++++++++ pkg/services/login/userprotection.go | 15 +- pkg/services/multildap/multidap_mock.go | 14 +- pkg/services/multildap/multildap.go | 20 +-- pkg/services/multildap/multildap_test.go | 36 ++--- pkg/services/oauthtoken/oauth_token.go | 27 ++-- pkg/services/oauthtoken/oauth_token_test.go | 50 +++---- .../oauthtoken/oauthtokentest/mock.go | 19 +-- .../oauthtokentest/oauthtokentest.go | 11 +- 57 files changed, 583 insertions(+), 603 deletions(-) delete mode 100644 pkg/models/user_auth.go create mode 100644 pkg/services/ldap/model.go diff --git a/pkg/api/admin_users.go b/pkg/api/admin_users.go index af03d961188..0a437904f9c 100644 --- a/pkg/api/admin_users.go +++ b/pkg/api/admin_users.go @@ -16,6 +16,7 @@ import ( "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/auth" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/util" @@ -293,7 +294,7 @@ func (hs *HTTPServer) AdminDisableUser(c *contextmodel.ReqContext) response.Resp } // External users shouldn't be disabled from API - authInfoQuery := &models.GetAuthInfoQuery{UserId: userID} + authInfoQuery := &login.GetAuthInfoQuery{UserId: userID} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), authInfoQuery); !errors.Is(err, user.ErrUserNotFound) { return response.Error(500, "Could not disable external user", nil) } @@ -336,7 +337,7 @@ func (hs *HTTPServer) AdminEnableUser(c *contextmodel.ReqContext) response.Respo } // External users shouldn't be disabled from API - authInfoQuery := &models.GetAuthInfoQuery{UserId: userID} + authInfoQuery := &login.GetAuthInfoQuery{UserId: userID} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), authInfoQuery); !errors.Is(err, user.ErrUserNotFound) { return response.Error(500, "Could not enable external user", nil) } diff --git a/pkg/api/ldap_debug.go b/pkg/api/ldap_debug.go index 501b303ca84..a6907ad7b93 100644 --- a/pkg/api/ldap_debug.go +++ b/pkg/api/ldap_debug.go @@ -10,7 +10,6 @@ import ( "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/login" @@ -48,14 +47,14 @@ type LDAPRoleDTO struct { // LDAPUserDTO is a serializer for users mapped from LDAP type LDAPUserDTO struct { - Name *LDAPAttribute `json:"name"` - Surname *LDAPAttribute `json:"surname"` - Email *LDAPAttribute `json:"email"` - Username *LDAPAttribute `json:"login"` - IsGrafanaAdmin *bool `json:"isGrafanaAdmin"` - IsDisabled bool `json:"isDisabled"` - OrgRoles []LDAPRoleDTO `json:"roles"` - Teams []models.TeamOrgGroupDTO `json:"teams"` + Name *LDAPAttribute `json:"name"` + Surname *LDAPAttribute `json:"surname"` + Email *LDAPAttribute `json:"email"` + Username *LDAPAttribute `json:"login"` + IsGrafanaAdmin *bool `json:"isGrafanaAdmin"` + IsDisabled bool `json:"isDisabled"` + OrgRoles []LDAPRoleDTO `json:"roles"` + Teams []ldap.TeamOrgGroupDTO `json:"teams"` } // LDAPServerDTO is a serializer for LDAP server statuses @@ -223,7 +222,7 @@ func (hs *HTTPServer) PostSyncUserWithLDAP(c *contextmodel.ReqContext) response. return response.Error(500, "Failed to get user", err) } - authModuleQuery := &models.GetAuthInfoQuery{UserId: usr.ID, AuthModule: login.LDAPAuthModule} + authModuleQuery := &login.GetAuthInfoQuery{UserId: usr.ID, AuthModule: login.LDAPAuthModule} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), authModuleQuery); err != nil { // validate the userId comes from LDAP if errors.Is(err, user.ErrUserNotFound) { return response.Error(404, user.ErrUserNotFound.Error(), nil) @@ -260,11 +259,11 @@ func (hs *HTTPServer) PostSyncUserWithLDAP(c *contextmodel.ReqContext) response. return response.Error(http.StatusBadRequest, "Something went wrong while finding the user in LDAP", err) } - upsertCmd := &models.UpsertUserCommand{ + upsertCmd := &login.UpsertUserCommand{ ReqContext: c, ExternalUser: userInfo, SignupAllowed: hs.Cfg.LDAPAllowSignup, - UserLookupParams: models.UserLookupParams{ + UserLookupParams: login.UserLookupParams{ UserID: &usr.ID, // Upsert by ID only Email: nil, Login: nil, diff --git a/pkg/api/ldap_debug_test.go b/pkg/api/ldap_debug_test.go index cf969dc9822..5e4e51fd750 100644 --- a/pkg/api/ldap_debug_test.go +++ b/pkg/api/ldap_debug_test.go @@ -14,11 +14,11 @@ import ( "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/infra/db/dbtest" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/auth/authtest" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/ldap" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/multildap" @@ -31,10 +31,10 @@ import ( ) type LDAPMock struct { - Results []*models.ExternalUserInfo + Results []*login.ExternalUserInfo } -var userSearchResult *models.ExternalUserInfo +var userSearchResult *login.ExternalUserInfo var userSearchConfig ldap.ServerConfig var userSearchError error var pingResult []*multildap.ServerStatus @@ -44,16 +44,16 @@ func (m *LDAPMock) Ping() ([]*multildap.ServerStatus, error) { return pingResult, pingError } -func (m *LDAPMock) Login(query *models.LoginUserQuery) (*models.ExternalUserInfo, error) { - return &models.ExternalUserInfo{}, nil +func (m *LDAPMock) Login(query *login.LoginUserQuery) (*login.ExternalUserInfo, error) { + return &login.ExternalUserInfo{}, nil } -func (m *LDAPMock) Users(logins []string) ([]*models.ExternalUserInfo, error) { - s := []*models.ExternalUserInfo{} +func (m *LDAPMock) Users(logins []string) ([]*login.ExternalUserInfo, error) { + s := []*login.ExternalUserInfo{} return s, nil } -func (m *LDAPMock) User(login string) (*models.ExternalUserInfo, ldap.ServerConfig, error) { +func (m *LDAPMock) User(login string) (*login.ExternalUserInfo, ldap.ServerConfig, error) { return userSearchResult, userSearchConfig, userSearchError } @@ -106,7 +106,7 @@ func TestGetUserFromLDAPAPIEndpoint_UserNotFound(t *testing.T) { func TestGetUserFromLDAPAPIEndpoint_OrgNotfound(t *testing.T) { isAdmin := true - userSearchResult = &models.ExternalUserInfo{ + userSearchResult = &login.ExternalUserInfo{ Name: "John Doe", Email: "john.doe@example.com", Login: "johndoe", @@ -161,7 +161,7 @@ func TestGetUserFromLDAPAPIEndpoint_OrgNotfound(t *testing.T) { func TestGetUserFromLDAPAPIEndpoint(t *testing.T) { isAdmin := true - userSearchResult = &models.ExternalUserInfo{ + userSearchResult = &login.ExternalUserInfo{ Name: "John Doe", Email: "john.doe@example.com", Login: "johndoe", @@ -236,7 +236,7 @@ func TestGetUserFromLDAPAPIEndpoint(t *testing.T) { func TestGetUserFromLDAPAPIEndpoint_WithTeamHandler(t *testing.T) { isAdmin := true - userSearchResult = &models.ExternalUserInfo{ + userSearchResult = &login.ExternalUserInfo{ Name: "John Doe", Email: "john.doe@example.com", Login: "johndoe", @@ -418,7 +418,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_Success(t *testing.T) { return &LDAPMock{} } - userSearchResult = &models.ExternalUserInfo{ + userSearchResult = &login.ExternalUserInfo{ Login: "ldap-daniel", } }, userServiceMock) @@ -487,7 +487,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotInLDAP(t *testing.T) { userServiceMock := usertest.NewUserServiceFake() userServiceMock.ExpectedUser = &user.User{Login: "ldap-daniel", ID: 34} sc := postSyncUserWithLDAPContext(t, "/api/admin/ldap/sync/34", func(t *testing.T, sc *scenarioContext) { - sc.authInfoService.ExpectedExternalUser = &models.ExternalUserInfo{IsDisabled: true, UserId: 34} + sc.authInfoService.ExpectedExternalUser = &login.ExternalUserInfo{IsDisabled: true, UserId: 34} getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) { return &ldap.Config{}, nil } @@ -625,7 +625,7 @@ func TestLDAP_AccessControl(t *testing.T) { hs.authInfoService = &logintest.AuthInfoServiceFake{} }) // Add minimal setup to pass handler - userSearchResult = &models.ExternalUserInfo{} + userSearchResult = &login.ExternalUserInfo{} userSearchError = nil newLDAP = func(_ []*ldap.ServerConfig) multildap.IMultiLDAP { return &LDAPMock{} diff --git a/pkg/api/login.go b/pkg/api/login.go index 429f080339f..8d041941ff4 100644 --- a/pkg/api/login.go +++ b/pkg/api/login.go @@ -15,12 +15,11 @@ import ( "github.com/grafana/grafana/pkg/infra/network" "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/middleware/cookies" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/authn" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/featuremgmt" - loginService "github.com/grafana/grafana/pkg/services/login" + loginservice "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/secrets" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/setting" @@ -236,7 +235,7 @@ func (hs *HTTPServer) LoginPost(c *contextmodel.ReqContext) response.Response { if err == nil && resp.ErrMessage() != "" { err = errors.New(resp.ErrMessage()) } - hs.HooksService.RunLoginHook(&models.LoginInfo{ + hs.HooksService.RunLoginHook(&loginservice.LoginInfo{ AuthModule: authModule, User: usr, LoginUsername: cmd.User, @@ -250,7 +249,7 @@ func (hs *HTTPServer) LoginPost(c *contextmodel.ReqContext) response.Response { return resp } - authQuery := &models.LoginUserQuery{ + authQuery := &loginservice.LoginUserQuery{ ReqContext: c, Username: cmd.User, Password: cmd.Password, @@ -327,7 +326,7 @@ func (hs *HTTPServer) loginUserWithUser(user *user.User, c *contextmodel.ReqCont } hs.log.Debug("Got IP address from client address", "addr", addr, "ip", ip) - ctx := context.WithValue(c.Req.Context(), models.RequestURIKey{}, c.Req.RequestURI) + ctx := context.WithValue(c.Req.Context(), loginservice.RequestURIKey{}, c.Req.RequestURI) userToken, err := hs.AuthTokenService.CreateToken(ctx, user, ip, c.Req.UserAgent()) if err != nil { return fmt.Errorf("%v: %w", "failed to create auth token", err) @@ -342,9 +341,9 @@ func (hs *HTTPServer) loginUserWithUser(user *user.User, c *contextmodel.ReqCont func (hs *HTTPServer) Logout(c *contextmodel.ReqContext) { // If SAML is enabled and this is a SAML user use saml logout if hs.samlSingleLogoutEnabled() { - getAuthQuery := models.GetAuthInfoQuery{UserId: c.UserID} + getAuthQuery := loginservice.GetAuthInfoQuery{UserId: c.UserID} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), &getAuthQuery); err == nil { - if getAuthQuery.Result.AuthModule == loginService.SAMLAuthModule { + if getAuthQuery.Result.AuthModule == loginservice.SAMLAuthModule { c.Redirect(hs.Cfg.AppSubURL + "/logout/saml") return } diff --git a/pkg/api/login_oauth.go b/pkg/api/login_oauth.go index 35fe2b156a5..f444615081b 100644 --- a/pkg/api/login_oauth.go +++ b/pkg/api/login_oauth.go @@ -17,8 +17,8 @@ import ( "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/middleware/cookies" - "github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + loginservice "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/setting" @@ -70,7 +70,7 @@ func genPKCECode() (string, string, error) { } func (hs *HTTPServer) OAuthLogin(ctx *contextmodel.ReqContext) { - loginInfo := models.LoginInfo{ + loginInfo := loginservice.LoginInfo{ AuthModule: "oauth", } name := web.Params(ctx.Req)[":name"] @@ -271,10 +271,10 @@ func (hs *HTTPServer) OAuthLogin(ctx *contextmodel.ReqContext) { } // buildExternalUserInfo returns a ExternalUserInfo struct from OAuth user profile -func (hs *HTTPServer) buildExternalUserInfo(token *oauth2.Token, userInfo *social.BasicUserInfo, name string) *models.ExternalUserInfo { +func (hs *HTTPServer) buildExternalUserInfo(token *oauth2.Token, userInfo *social.BasicUserInfo, name string) *loginservice.ExternalUserInfo { oauthLogger.Debug("Building external user info from OAuth user info") - extUser := &models.ExternalUserInfo{ + extUser := &loginservice.ExternalUserInfo{ AuthModule: fmt.Sprintf("oauth_%s", name), OAuthToken: token, AuthId: userInfo.Id, @@ -310,16 +310,16 @@ func (hs *HTTPServer) buildExternalUserInfo(token *oauth2.Token, userInfo *socia // SyncUser syncs a Grafana user profile with the corresponding OAuth profile. func (hs *HTTPServer) SyncUser( ctx *contextmodel.ReqContext, - extUser *models.ExternalUserInfo, + extUser *loginservice.ExternalUserInfo, connect social.SocialConnector, ) (*user.User, error) { oauthLogger.Debug("Syncing Grafana user with corresponding OAuth profile") // add/update user in Grafana - cmd := &models.UpsertUserCommand{ + cmd := &loginservice.UpsertUserCommand{ ReqContext: ctx, ExternalUser: extUser, SignupAllowed: connect.IsSignupAllowed(), - UserLookupParams: models.UserLookupParams{ + UserLookupParams: loginservice.UserLookupParams{ Email: &extUser.Email, UserID: nil, Login: nil, @@ -351,7 +351,7 @@ type LoginError struct { Err error } -func (hs *HTTPServer) handleOAuthLoginError(ctx *contextmodel.ReqContext, info models.LoginInfo, err LoginError) { +func (hs *HTTPServer) handleOAuthLoginError(ctx *contextmodel.ReqContext, info loginservice.LoginInfo, err LoginError) { ctx.Handle(hs.Cfg, err.HttpStatus, err.PublicMessage, err.Err) info.Error = err.Err @@ -363,7 +363,7 @@ func (hs *HTTPServer) handleOAuthLoginError(ctx *contextmodel.ReqContext, info m hs.HooksService.RunLoginHook(&info, ctx) } -func (hs *HTTPServer) handleOAuthLoginErrorWithRedirect(ctx *contextmodel.ReqContext, info models.LoginInfo, err error, v ...interface{}) { +func (hs *HTTPServer) handleOAuthLoginErrorWithRedirect(ctx *contextmodel.ReqContext, info loginservice.LoginInfo, err error, v ...interface{}) { hs.redirectWithError(ctx, err, v...) info.Error = err diff --git a/pkg/api/login_test.go b/pkg/api/login_test.go index 45fd7cef0ea..402d9d77b7e 100644 --- a/pkg/api/login_test.go +++ b/pkg/api/login_test.go @@ -12,6 +12,9 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" @@ -19,7 +22,6 @@ import ( "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login/social" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth/authtest" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/featuremgmt" @@ -32,8 +34,6 @@ import ( secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/setting" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func fakeSetIndexViewData(t *testing.T) { @@ -590,10 +590,10 @@ func setupAuthProxyLoginTest(t *testing.T, enableLoginToken bool) *scenarioConte } type loginHookTest struct { - info *models.LoginInfo + info *loginservice.LoginInfo } -func (r *loginHookTest) LoginHook(loginInfo *models.LoginInfo, req *contextmodel.ReqContext) { +func (r *loginHookTest) LoginHook(loginInfo *loginservice.LoginInfo, req *contextmodel.ReqContext) { r.info = loginInfo } @@ -629,12 +629,12 @@ func TestLoginPostRunLokingHook(t *testing.T) { authUser *user.User authModule string authErr error - info models.LoginInfo + info loginservice.LoginInfo }{ { desc: "invalid credentials", authErr: login.ErrInvalidCredentials, - info: models.LoginInfo{ + info: loginservice.LoginInfo{ AuthModule: "", HTTPStatus: 401, Error: login.ErrInvalidCredentials, @@ -643,7 +643,7 @@ func TestLoginPostRunLokingHook(t *testing.T) { { desc: "user disabled", authErr: login.ErrUserDisabled, - info: models.LoginInfo{ + info: loginservice.LoginInfo{ AuthModule: "", HTTPStatus: 401, Error: login.ErrUserDisabled, @@ -653,7 +653,7 @@ func TestLoginPostRunLokingHook(t *testing.T) { desc: "valid Grafana user", authUser: testUser, authModule: "grafana", - info: models.LoginInfo{ + info: loginservice.LoginInfo{ AuthModule: "grafana", User: testUser, HTTPStatus: 200, @@ -663,7 +663,7 @@ func TestLoginPostRunLokingHook(t *testing.T) { desc: "valid LDAP user", authUser: testUser, authModule: loginservice.LDAPAuthModule, - info: models.LoginInfo{ + info: loginservice.LoginInfo{ AuthModule: loginservice.LDAPAuthModule, User: testUser, HTTPStatus: 200, @@ -726,7 +726,7 @@ type fakeAuthenticator struct { ExpectedError error } -func (fa *fakeAuthenticator) AuthenticateUser(c context.Context, query *models.LoginUserQuery) error { +func (fa *fakeAuthenticator) AuthenticateUser(c context.Context, query *loginservice.LoginUserQuery) error { query.User = fa.ExpectedUser query.AuthModule = fa.ExpectedAuthModule return fa.ExpectedError diff --git a/pkg/api/org_users.go b/pkg/api/org_users.go index 264c833d77b..b0c7c807cc0 100644 --- a/pkg/api/org_users.go +++ b/pkg/api/org_users.go @@ -9,7 +9,6 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/accesscontrol" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/login" @@ -300,7 +299,7 @@ func (hs *HTTPServer) searchOrgUsersHelper(c *contextmodel.ReqContext, query *or filteredUsers = append(filteredUsers, user) } - modules, err := hs.authInfoService.GetUserLabels(c.Req.Context(), models.GetUserLabelsQuery{ + modules, err := hs.authInfoService.GetUserLabels(c.Req.Context(), login.GetUserLabelsQuery{ UserIDs: authLabelsUserIDs, }) diff --git a/pkg/api/password.go b/pkg/api/password.go index 585c11f2909..80753bad9c7 100644 --- a/pkg/api/password.go +++ b/pkg/api/password.go @@ -39,7 +39,7 @@ func (hs *HTTPServer) SendResetPasswordEmail(c *contextmodel.ReqContext) respons return response.Error(http.StatusOK, "Email sent", nil) } - getAuthQuery := models.GetAuthInfoQuery{UserId: usr.ID} + getAuthQuery := login.GetAuthInfoQuery{UserId: usr.ID} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), &getAuthQuery); err == nil { authModule := getAuthQuery.Result.AuthModule if authModule == login.LDAPAuthModule || authModule == login.AuthProxyAuthModule { diff --git a/pkg/api/pluginproxy/ds_proxy_test.go b/pkg/api/pluginproxy/ds_proxy_test.go index ff085671da7..bf9fa018d77 100644 --- a/pkg/api/pluginproxy/ds_proxy_test.go +++ b/pkg/api/pluginproxy/ds_proxy_test.go @@ -25,13 +25,13 @@ import ( "github.com/grafana/grafana/pkg/infra/httpclient" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/tracing" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/datasources" datasourceservice "github.com/grafana/grafana/pkg/services/datasources/service" "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/oauthtoken" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/quota/quotatest" @@ -1126,14 +1126,14 @@ func (m *mockOAuthTokenService) IsOAuthPassThruEnabled(ds *datasources.DataSourc return m.oAuthEnabled } -func (m *mockOAuthTokenService) HasOAuthEntry(context.Context, *user.SignedInUser) (*models.UserAuth, bool, error) { +func (m *mockOAuthTokenService) HasOAuthEntry(context.Context, *user.SignedInUser) (*login.UserAuth, bool, error) { return nil, false, nil } -func (m *mockOAuthTokenService) TryTokenRefresh(context.Context, *models.UserAuth) error { +func (m *mockOAuthTokenService) TryTokenRefresh(context.Context, *login.UserAuth) error { return nil } -func (m *mockOAuthTokenService) InvalidateOAuthTokens(context.Context, *models.UserAuth) error { +func (m *mockOAuthTokenService) InvalidateOAuthTokens(context.Context, *login.UserAuth) error { return nil } diff --git a/pkg/api/user.go b/pkg/api/user.go index 90f5bb152af..997b86881fa 100644 --- a/pkg/api/user.go +++ b/pkg/api/user.go @@ -63,7 +63,7 @@ func (hs *HTTPServer) getUserUserProfile(c *contextmodel.ReqContext, userID int6 return response.Error(500, "Failed to get user", err) } - getAuthQuery := models.GetAuthInfoQuery{UserId: userID} + getAuthQuery := login.GetAuthInfoQuery{UserId: userID} userProfile.AuthLabels = []string{} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), &getAuthQuery); err == nil { authLabel := login.GetAuthProviderLabel(getAuthQuery.Result.AuthModule) @@ -224,7 +224,7 @@ func (hs *HTTPServer) handleUpdateUser(ctx context.Context, cmd user.UpdateUserC } func (hs *HTTPServer) isExternalUser(ctx context.Context, userID int64) (bool, error) { - getAuthQuery := models.GetAuthInfoQuery{UserId: userID} + getAuthQuery := login.GetAuthInfoQuery{UserId: userID} var err error if err = hs.authInfoService.GetAuthInfo(ctx, &getAuthQuery); err == nil { return true, nil @@ -434,7 +434,7 @@ func (hs *HTTPServer) ChangeUserPassword(c *contextmodel.ReqContext) response.Re return response.Error(500, "Could not read user from database", err) } - getAuthQuery := models.GetAuthInfoQuery{UserId: user.ID} + getAuthQuery := login.GetAuthInfoQuery{UserId: user.ID} if err := hs.authInfoService.GetAuthInfo(c.Req.Context(), &getAuthQuery); err == nil { authModule := getAuthQuery.Result.AuthModule if authModule == login.LDAPAuthModule || authModule == login.AuthProxyAuthModule { diff --git a/pkg/api/user_test.go b/pkg/api/user_test.go index 8ef586ccf21..50be2a76ed1 100644 --- a/pkg/api/user_test.go +++ b/pkg/api/user_test.go @@ -19,9 +19,9 @@ import ( "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/usagestats" - "github.com/grafana/grafana/pkg/models" acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/authinfoservice" authinfostore "github.com/grafana/grafana/pkg/services/login/authinfoservice/database" "github.com/grafana/grafana/pkg/services/login/logintest" @@ -90,9 +90,9 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) { } idToken := "testidtoken" token = token.WithExtra(map[string]interface{}{"id_token": idToken}) - login := "loginuser" - query := &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test", UserLookupParams: models.UserLookupParams{Login: &login}} - cmd := &models.UpdateAuthInfoCommand{ + userlogin := "loginuser" + query := &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test", UserLookupParams: login.UserLookupParams{Login: &userlogin}} + cmd := &login.UpdateAuthInfoCommand{ UserId: usr.ID, AuthId: query.AuthId, AuthModule: query.AuthModule, @@ -234,7 +234,7 @@ func TestHTTPServer_UpdateUser(t *testing.T) { routePattern: "/api/users/:id", cmd: updateUserCommand, fn: func(sc *scenarioContext) { - sc.authInfoService.ExpectedUserAuth = &models.UserAuth{} + sc.authInfoService.ExpectedUserAuth = &login.UserAuth{} sc.fakeReqWithParams("PUT", sc.url, map[string]string{"id": "1"}).exec() assert.Equal(t, 403, sc.resp.Code) }, @@ -295,7 +295,7 @@ func TestHTTPServer_UpdateSignedInUser(t *testing.T) { routePattern: "/api/users/", cmd: updateUserCommand, fn: func(sc *scenarioContext) { - sc.authInfoService.ExpectedUserAuth = &models.UserAuth{} + sc.authInfoService.ExpectedUserAuth = &login.UserAuth{} sc.fakeReqWithParams("PUT", sc.url, map[string]string{"id": "1"}).exec() assert.Equal(t, 403, sc.resp.Code) }, diff --git a/pkg/login/auth.go b/pkg/login/auth.go index 382b4b4f288..0a22319f0f9 100644 --- a/pkg/login/auth.go +++ b/pkg/login/auth.go @@ -6,7 +6,6 @@ import ( "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/loginattempt" @@ -30,7 +29,7 @@ var ( var loginLogger = log.New("login") type Authenticator interface { - AuthenticateUser(context.Context, *models.LoginUserQuery) error + AuthenticateUser(context.Context, *login.LoginUserQuery) error } type AuthenticatorService struct { @@ -49,7 +48,7 @@ func ProvideService(store db.DB, loginService login.Service, loginAttemptService } // AuthenticateUser authenticates the user via username & password -func (a *AuthenticatorService) AuthenticateUser(ctx context.Context, query *models.LoginUserQuery) error { +func (a *AuthenticatorService) AuthenticateUser(ctx context.Context, query *login.LoginUserQuery) error { ok, err := a.loginAttemptService.Validate(ctx, query.Username) if err != nil { return err diff --git a/pkg/login/auth_test.go b/pkg/login/auth_test.go index edc8f4ed3d8..8720c6e0ea4 100644 --- a/pkg/login/auth_test.go +++ b/pkg/login/auth_test.go @@ -5,15 +5,15 @@ import ( "errors" "testing" - "github.com/grafana/grafana/pkg/models" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/loginattempt/loginattempttest" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/setting" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestAuthenticateUser(t *testing.T) { @@ -23,7 +23,7 @@ func TestAuthenticateUser(t *testing.T) { loginAttemptService := &loginattempttest.FakeLoginAttemptService{ExpectedValid: true} a := AuthenticatorService{loginAttemptService: loginAttemptService, loginService: &logintest.LoginServiceFake{}} - err := a.AuthenticateUser(context.Background(), &models.LoginUserQuery{ + err := a.AuthenticateUser(context.Background(), &login.LoginUserQuery{ Username: "user", Password: "", }) @@ -180,7 +180,7 @@ func TestAuthenticateUser(t *testing.T) { } type authScenarioContext struct { - loginUserQuery *models.LoginUserQuery + loginUserQuery *login.LoginUserQuery grafanaLoginWasCalled bool ldapLoginWasCalled bool } @@ -188,14 +188,14 @@ type authScenarioContext struct { type authScenarioFunc func(sc *authScenarioContext) func mockLoginUsingGrafanaDB(err error, sc *authScenarioContext) { - loginUsingGrafanaDB = func(ctx context.Context, query *models.LoginUserQuery, _ user.Service) error { + loginUsingGrafanaDB = func(ctx context.Context, query *login.LoginUserQuery, _ user.Service) error { sc.grafanaLoginWasCalled = true return err } } func mockLoginUsingLDAP(enabled bool, err error, sc *authScenarioContext) { - loginUsingLDAP = func(ctx context.Context, query *models.LoginUserQuery, _ login.Service) (bool, error) { + loginUsingLDAP = func(ctx context.Context, query *login.LoginUserQuery, _ login.Service) (bool, error) { sc.ldapLoginWasCalled = true return enabled, err } @@ -209,7 +209,7 @@ func authScenario(t *testing.T, desc string, fn authScenarioFunc) { origLoginUsingLDAP := loginUsingLDAP cfg := setting.Cfg{DisableLogin: false} sc := &authScenarioContext{ - loginUserQuery: &models.LoginUserQuery{ + loginUserQuery: &login.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", diff --git a/pkg/login/grafana_login.go b/pkg/login/grafana_login.go index 64bc19362e1..3ef14a39f79 100644 --- a/pkg/login/grafana_login.go +++ b/pkg/login/grafana_login.go @@ -4,7 +4,7 @@ import ( "context" "crypto/subtle" - "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/util" ) @@ -21,7 +21,7 @@ var validatePassword = func(providedPassword string, userPassword string, userSa return nil } -var loginUsingGrafanaDB = func(ctx context.Context, query *models.LoginUserQuery, userService user.Service) error { +var loginUsingGrafanaDB = func(ctx context.Context, query *login.LoginUserQuery, userService user.Service) error { userQuery := user.GetUserByLoginQuery{LoginOrEmail: query.Username} user, err := userService.GetByLogin(ctx, &userQuery) diff --git a/pkg/login/grafana_login_test.go b/pkg/login/grafana_login_test.go index 531f6a1dcc3..cd68019de97 100644 --- a/pkg/login/grafana_login_test.go +++ b/pkg/login/grafana_login_test.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db/dbtest" - "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user/usertest" ) @@ -59,7 +59,7 @@ func TestLoginUsingGrafanaDB(t *testing.T) { type grafanaLoginScenarioContext struct { store db.DB userService *usertest.FakeUserService - loginUserQuery *models.LoginUserQuery + loginUserQuery *login.LoginUserQuery validatePasswordCalled bool } @@ -73,7 +73,7 @@ func grafanaLoginScenario(t *testing.T, desc string, fn grafanaLoginScenarioFunc sc := &grafanaLoginScenarioContext{ store: dbtest.NewFakeDB(), - loginUserQuery: &models.LoginUserQuery{ + loginUserQuery: &login.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", diff --git a/pkg/login/ldap_login.go b/pkg/login/ldap_login.go index bf2b23a9e24..a2f0b4f3321 100644 --- a/pkg/login/ldap_login.go +++ b/pkg/login/ldap_login.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/multildap" @@ -27,7 +26,7 @@ var ldapLogger = log.New("login.ldap") // loginUsingLDAP logs in user using LDAP. It returns whether LDAP is enabled and optional error and query arg will be // populated with the logged in user if successful. -var loginUsingLDAP = func(ctx context.Context, query *models.LoginUserQuery, loginService login.Service) (bool, error) { +var loginUsingLDAP = func(ctx context.Context, query *login.LoginUserQuery, loginService login.Service) (bool, error) { enabled := isLDAPEnabled() if !enabled { @@ -54,11 +53,11 @@ var loginUsingLDAP = func(ctx context.Context, query *models.LoginUserQuery, log return true, err } - upsert := &models.UpsertUserCommand{ + upsert := &login.UpsertUserCommand{ ReqContext: query.ReqContext, ExternalUser: externalUser, SignupAllowed: setting.LDAPAllowSignup, - UserLookupParams: models.UserLookupParams{ + UserLookupParams: login.UserLookupParams{ Login: &externalUser.Login, Email: &externalUser.Email, UserID: nil, diff --git a/pkg/login/ldap_login_test.go b/pkg/login/ldap_login_test.go index 4503b272e92..ac4dc47205c 100644 --- a/pkg/login/ldap_login_test.go +++ b/pkg/login/ldap_login_test.go @@ -5,13 +5,14 @@ import ( "errors" "testing" - "github.com/grafana/grafana/pkg/models" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/services/ldap" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/setting" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) var errTest = errors.New("test error") @@ -62,8 +63,8 @@ func (auth *mockAuth) Ping() ([]*multildap.ServerStatus, error) { return nil, nil } -func (auth *mockAuth) Login(query *models.LoginUserQuery) ( - *models.ExternalUserInfo, +func (auth *mockAuth) Login(query *login.LoginUserQuery) ( + *login.ExternalUserInfo, error, ) { auth.loginCalled = true @@ -76,14 +77,14 @@ func (auth *mockAuth) Login(query *models.LoginUserQuery) ( } func (auth *mockAuth) Users(logins []string) ( - []*models.ExternalUserInfo, + []*login.ExternalUserInfo, error, ) { return nil, nil } func (auth *mockAuth) User(login string) ( - *models.ExternalUserInfo, + *login.ExternalUserInfo, ldap.ServerConfig, error, ) { @@ -111,7 +112,7 @@ func mockLDAPAuthenticator(valid bool) *mockAuth { } type LDAPLoginScenarioContext struct { - loginUserQuery *models.LoginUserQuery + loginUserQuery *login.LoginUserQuery LDAPAuthenticatorMock *mockAuth } @@ -124,7 +125,7 @@ func LDAPLoginScenario(t *testing.T, desc string, fn LDAPLoginScenarioFunc) { mock := &mockAuth{} sc := &LDAPLoginScenarioContext{ - loginUserQuery: &models.LoginUserQuery{ + loginUserQuery: &login.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", diff --git a/pkg/middleware/middleware_test.go b/pkg/middleware/middleware_test.go index 5aeda6a8a83..ac6d530749d 100644 --- a/pkg/middleware/middleware_test.go +++ b/pkg/middleware/middleware_test.go @@ -24,7 +24,6 @@ import ( "github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/login" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/apikey" "github.com/grafana/grafana/pkg/services/apikey/apikeytest" "github.com/grafana/grafana/pkg/services/auth" @@ -35,6 +34,7 @@ import ( "github.com/grafana/grafana/pkg/services/contexthandler/authproxy" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/featuremgmt" + loginsvc "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/navtree" @@ -437,7 +437,7 @@ func TestMiddlewareContext(t *testing.T) { sc.withTokenSessionCookie("token") sc.userService.ExpectedSignedInUser = &user.SignedInUser{OrgID: 2, UserID: userID} - sc.oauthTokenService.ExpectedAuthUser = &models.UserAuth{UserId: userID, OAuthExpiry: fakeGetTime()().Add(11 * time.Second)} + sc.oauthTokenService.ExpectedAuthUser = &loginsvc.UserAuth{UserId: userID, OAuthExpiry: fakeGetTime()().Add(11 * time.Second)} sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*auth.UserToken, error) { return &auth.UserToken{ @@ -465,7 +465,7 @@ func TestMiddlewareContext(t *testing.T) { sc.withTokenSessionCookie("token") signedInUser := &user.SignedInUser{OrgID: 2, UserID: userID} sc.userService.ExpectedSignedInUser = signedInUser - sc.oauthTokenService.ExpectedAuthUser = &models.UserAuth{ + sc.oauthTokenService.ExpectedAuthUser = &loginsvc.UserAuth{ UserId: userID, OAuthExpiry: fakeGetTime()().Add(-1 * time.Second), OAuthAccessToken: "access_token", @@ -500,7 +500,7 @@ func TestMiddlewareContext(t *testing.T) { sc.withTokenSessionCookie("token") sc.userService.ExpectedSignedInUser = &user.SignedInUser{OrgID: 2, UserID: userID} - sc.oauthTokenService.ExpectedAuthUser = &models.UserAuth{UserId: userID, OAuthExpiry: fakeGetTime()().Add(-5 * time.Second), OAuthRefreshToken: "refreshtoken"} + sc.oauthTokenService.ExpectedAuthUser = &loginsvc.UserAuth{UserId: userID, OAuthExpiry: fakeGetTime()().Add(-5 * time.Second), OAuthRefreshToken: "refreshtoken"} sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*auth.UserToken, error) { return &auth.UserToken{ @@ -527,7 +527,7 @@ func TestMiddlewareContext(t *testing.T) { sc.withTokenSessionCookie("token") sc.userService.ExpectedSignedInUser = &user.SignedInUser{OrgID: 2, UserID: userID} - sc.oauthTokenService.ExpectedAuthUser = &models.UserAuth{UserId: userID} + sc.oauthTokenService.ExpectedAuthUser = &loginsvc.UserAuth{UserId: userID} sc.userAuthTokenService.LookupTokenProvider = func(ctx context.Context, unhashedToken string) (*auth.UserToken, error) { return &auth.UserToken{ @@ -610,7 +610,7 @@ func TestMiddlewareContext(t *testing.T) { middlewareScenario(t, "Should respect auto signup option", func(t *testing.T, sc *scenarioContext) { var actualAuthProxyAutoSignUp *bool = nil - sc.loginService.ExpectedUserFunc = func(cmd *models.UpsertUserCommand) *user.User { + sc.loginService.ExpectedUserFunc = func(cmd *loginsvc.UpsertUserCommand) *user.User { actualAuthProxyAutoSignUp = &cmd.SignupAllowed return nil } @@ -652,7 +652,7 @@ func TestMiddlewareContext(t *testing.T) { middlewareScenario(t, "Should assign role from header to default org", func(t *testing.T, sc *scenarioContext) { var storedRoleInfo map[int64]org.RoleType = nil - sc.loginService.ExpectedUserFunc = func(cmd *models.UpsertUserCommand) *user.User { + sc.loginService.ExpectedUserFunc = func(cmd *loginsvc.UpsertUserCommand) *user.User { storedRoleInfo = cmd.ExternalUser.OrgRoles sc.userService.ExpectedSignedInUser = &user.SignedInUser{OrgID: defaultOrgId, UserID: userID, OrgRole: storedRoleInfo[defaultOrgId]} return &user.User{ID: userID} @@ -675,7 +675,7 @@ func TestMiddlewareContext(t *testing.T) { middlewareScenario(t, "Should NOT assign role from header to non-default org", func(t *testing.T, sc *scenarioContext) { var storedRoleInfo map[int64]org.RoleType = nil - sc.loginService.ExpectedUserFunc = func(cmd *models.UpsertUserCommand) *user.User { + sc.loginService.ExpectedUserFunc = func(cmd *loginsvc.UpsertUserCommand) *user.User { storedRoleInfo = cmd.ExternalUser.OrgRoles sc.userService.ExpectedSignedInUser = &user.SignedInUser{OrgID: orgID, UserID: userID, OrgRole: storedRoleInfo[orgID]} return &user.User{ID: userID} diff --git a/pkg/models/user_auth.go b/pkg/models/user_auth.go deleted file mode 100644 index 7b2697778dc..00000000000 --- a/pkg/models/user_auth.go +++ /dev/null @@ -1,138 +0,0 @@ -package models - -import ( - "fmt" - "time" - - contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" - "github.com/grafana/grafana/pkg/services/org" - "github.com/grafana/grafana/pkg/services/user" - "github.com/grafana/grafana/pkg/setting" - - "golang.org/x/oauth2" -) - -type UserAuth struct { - Id int64 - UserId int64 - AuthModule string - AuthId string - Created time.Time - OAuthAccessToken string - OAuthRefreshToken string - OAuthIdToken string - OAuthTokenType string - OAuthExpiry time.Time -} - -type ExternalUserInfo struct { - OAuthToken *oauth2.Token - AuthModule string - AuthId string - UserId int64 - Email string - Login string - Name string - Groups []string - OrgRoles map[int64]org.RoleType - IsGrafanaAdmin *bool // This is a pointer to know if we should sync this or not (nil = ignore sync) - IsDisabled bool - SkipTeamSync bool -} - -func (e *ExternalUserInfo) String() string { - return fmt.Sprintf("%+v", *e) -} - -type LoginInfo struct { - AuthModule string - User *user.User - ExternalUser ExternalUserInfo - LoginUsername string - HTTPStatus int - Error error -} - -// RequestURIKey is used as key to save request URI in contexts -// (used for the Enterprise auditing feature) -type RequestURIKey struct{} - -// --------------------- -// COMMANDS - -type UpsertUserCommand struct { - ReqContext *contextmodel.ReqContext - ExternalUser *ExternalUserInfo - UserLookupParams - SignupAllowed bool - - Result *user.User -} - -type SetAuthInfoCommand struct { - AuthModule string - AuthId string - UserId int64 - OAuthToken *oauth2.Token -} - -type UpdateAuthInfoCommand struct { - AuthModule string - AuthId string - UserId int64 - OAuthToken *oauth2.Token -} - -type DeleteAuthInfoCommand struct { - UserAuth *UserAuth -} - -// ---------------------- -// QUERIES - -type LoginUserQuery struct { - ReqContext *contextmodel.ReqContext - Username string - Password string - User *user.User - IpAddress string - AuthModule string - Cfg *setting.Cfg -} - -type GetUserByAuthInfoQuery struct { - AuthModule string - AuthId string - UserLookupParams -} - -type UserLookupParams struct { - // Describes lookup order as well - UserID *int64 // if set, will try to find the user by id - Email *string // if set, will try to find the user by email - Login *string // if set, will try to find the user by login -} - -type GetExternalUserInfoByLoginQuery struct { - LoginOrEmail string - - Result *ExternalUserInfo -} - -type GetAuthInfoQuery struct { - UserId int64 - AuthModule string - AuthId string - - Result *UserAuth -} - -type GetUserLabelsQuery struct { - UserIDs []int64 -} - -type TeamOrgGroupDTO struct { - TeamName string `json:"teamName"` - OrgName string `json:"orgName"` - GroupDN string `json:"groupDN"` -} diff --git a/pkg/services/auth/authtest/testing.go b/pkg/services/auth/authtest/testing.go index d2bbd09b46b..6a924c5ebf4 100644 --- a/pkg/services/auth/authtest/testing.go +++ b/pkg/services/auth/authtest/testing.go @@ -5,11 +5,12 @@ import ( "net" "time" - "github.com/grafana/grafana/pkg/models" + "golang.org/x/oauth2" + "github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/datasources" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" - "golang.org/x/oauth2" ) type FakeUserAuthTokenService struct { @@ -112,7 +113,7 @@ func (s *FakeUserAuthTokenService) BatchRevokeAllUserTokens(ctx context.Context, type FakeOAuthTokenService struct { passThruEnabled bool - ExpectedAuthUser *models.UserAuth + ExpectedAuthUser *login.UserAuth ExpectedErrors map[string]error } @@ -129,7 +130,7 @@ func (ts *FakeOAuthTokenService) IsOAuthPassThruEnabled(*datasources.DataSource) return ts.passThruEnabled } -func (ts *FakeOAuthTokenService) HasOAuthEntry(context.Context, *user.SignedInUser) (*models.UserAuth, bool, error) { +func (ts *FakeOAuthTokenService) HasOAuthEntry(context.Context, *user.SignedInUser) (*login.UserAuth, bool, error) { if ts.ExpectedAuthUser != nil { return ts.ExpectedAuthUser, true, nil } @@ -139,14 +140,14 @@ func (ts *FakeOAuthTokenService) HasOAuthEntry(context.Context, *user.SignedInUs return nil, false, nil } -func (ts *FakeOAuthTokenService) InvalidateOAuthTokens(ctx context.Context, usr *models.UserAuth) error { +func (ts *FakeOAuthTokenService) InvalidateOAuthTokens(ctx context.Context, usr *login.UserAuth) error { ts.ExpectedAuthUser.OAuthAccessToken = "" ts.ExpectedAuthUser.OAuthRefreshToken = "" ts.ExpectedAuthUser.OAuthExpiry = time.Time{} return nil } -func (ts *FakeOAuthTokenService) TryTokenRefresh(ctx context.Context, usr *models.UserAuth) error { +func (ts *FakeOAuthTokenService) TryTokenRefresh(ctx context.Context, usr *login.UserAuth) error { if err, ok := ts.ExpectedErrors["TryTokenRefresh"]; ok { return err } diff --git a/pkg/services/authn/authn.go b/pkg/services/authn/authn.go index a6c435259c4..64522ff26b5 100644 --- a/pkg/services/authn/authn.go +++ b/pkg/services/authn/authn.go @@ -10,8 +10,8 @@ import ( "golang.org/x/oauth2" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/web" @@ -45,7 +45,7 @@ type ClientParams struct { // EnableDisabledUsers is a hint to the auth service that it should reenable disabled users EnableDisabledUsers bool // LookUpParams are the arguments used to look up the entity in the DB. - LookUpParams models.UserLookupParams + LookUpParams login.UserLookupParams } type PostAuthHookFn func(ctx context.Context, identity *Identity, r *Request) error @@ -247,9 +247,9 @@ func (i *Identity) SignedInUser() *user.SignedInUser { return u } -func (i *Identity) ExternalUserInfo() models.ExternalUserInfo { +func (i *Identity) ExternalUserInfo() login.ExternalUserInfo { _, id := i.NamespacedID() - return models.ExternalUserInfo{ + return login.ExternalUserInfo{ OAuthToken: i.OAuthToken, AuthModule: i.AuthModule, AuthId: i.AuthID, diff --git a/pkg/services/authn/authnimpl/sync/oauth_token_sync_test.go b/pkg/services/authn/authnimpl/sync/oauth_token_sync_test.go index 27a06408674..a180cab31a1 100644 --- a/pkg/services/authn/authnimpl/sync/oauth_token_sync_test.go +++ b/pkg/services/authn/authnimpl/sync/oauth_token_sync_test.go @@ -9,10 +9,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/authn" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/oauthtoken/oauthtokentest" "github.com/grafana/grafana/pkg/services/user" ) @@ -22,7 +22,7 @@ func TestOauthTokenSync_SyncOauthToken(t *testing.T) { desc string identity *authn.Identity - expectedHasEntryToken *models.UserAuth + expectedHasEntryToken *login.UserAuth expectHasEntryCalled bool expectedTryRefreshErr error @@ -52,26 +52,26 @@ func TestOauthTokenSync_SyncOauthToken(t *testing.T) { desc: "should skip sync for when access token don't have expire time", identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}}, expectHasEntryCalled: true, - expectedHasEntryToken: &models.UserAuth{}, + expectedHasEntryToken: &login.UserAuth{}, }, { desc: "should skip sync when access token has no expired yet", identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}}, expectHasEntryCalled: true, - expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(10 * time.Minute)}, + expectedHasEntryToken: &login.UserAuth{OAuthExpiry: time.Now().Add(10 * time.Minute)}, }, { desc: "should skip sync when access token has no expired yet", identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}}, expectHasEntryCalled: true, - expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(10 * time.Minute)}, + expectedHasEntryToken: &login.UserAuth{OAuthExpiry: time.Now().Add(10 * time.Minute)}, }, { desc: "should refresh access token when is has expired", identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}}, expectHasEntryCalled: true, expectTryRefreshTokenCalled: true, - expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(-10 * time.Minute)}, + expectedHasEntryToken: &login.UserAuth{OAuthExpiry: time.Now().Add(-10 * time.Minute)}, }, { desc: "should invalidate access token and session token if access token can't be refreshed", @@ -81,7 +81,7 @@ func TestOauthTokenSync_SyncOauthToken(t *testing.T) { expectTryRefreshTokenCalled: true, expectInvalidateOauthTokensCalled: true, expectRevokeTokenCalled: true, - expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(-10 * time.Minute)}, + expectedHasEntryToken: &login.UserAuth{OAuthExpiry: time.Now().Add(-10 * time.Minute)}, expectedErr: errExpiredAccessToken, }, } @@ -96,15 +96,15 @@ func TestOauthTokenSync_SyncOauthToken(t *testing.T) { ) service := &oauthtokentest.MockOauthTokenService{ - HasOAuthEntryFunc: func(ctx context.Context, usr *user.SignedInUser) (*models.UserAuth, bool, error) { + HasOAuthEntryFunc: func(ctx context.Context, usr *user.SignedInUser) (*login.UserAuth, bool, error) { hasEntryCalled = true return tt.expectedHasEntryToken, tt.expectedHasEntryToken != nil, nil }, - InvalidateOAuthTokensFunc: func(ctx context.Context, usr *models.UserAuth) error { + InvalidateOAuthTokensFunc: func(ctx context.Context, usr *login.UserAuth) error { invalidateTokensCalled = true return nil }, - TryTokenRefreshFunc: func(ctx context.Context, usr *models.UserAuth) error { + TryTokenRefreshFunc: func(ctx context.Context, usr *login.UserAuth) error { tryRefreshCalled = true return tt.expectedTryRefreshErr }, diff --git a/pkg/services/authn/authnimpl/sync/org_sync_test.go b/pkg/services/authn/authnimpl/sync/org_sync_test.go index 4fd87ba7d9a..4c4f6d6ea06 100644 --- a/pkg/services/authn/authnimpl/sync/org_sync_test.go +++ b/pkg/services/authn/authnimpl/sync/org_sync_test.go @@ -4,17 +4,18 @@ import ( "context" "testing" + "github.com/stretchr/testify/assert" + "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models/roletype" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol/actest" "github.com/grafana/grafana/pkg/services/authn" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user/usertest" - "github.com/stretchr/testify/assert" ) func TestOrgSync_SyncOrgUser(t *testing.T) { @@ -79,7 +80,7 @@ func TestOrgSync_SyncOrgUser(t *testing.T) { IsGrafanaAdmin: ptrBool(false), ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test"), Login: nil, @@ -97,7 +98,7 @@ func TestOrgSync_SyncOrgUser(t *testing.T) { IsGrafanaAdmin: ptrBool(false), ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test"), Login: nil, diff --git a/pkg/services/authn/authnimpl/sync/user_sync.go b/pkg/services/authn/authnimpl/sync/user_sync.go index f1740a33b0b..a054a7032ad 100644 --- a/pkg/services/authn/authnimpl/sync/user_sync.go +++ b/pkg/services/authn/authnimpl/sync/user_sync.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/authn" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" @@ -140,7 +139,7 @@ func (s *UserSync) updateAuthInfo(ctx context.Context, id *authn.Identity) error return fmt.Errorf("invalid namespace %q for user ID %q", namespace, userID) } - updateCmd := &models.UpdateAuthInfoCommand{ + updateCmd := &login.UpdateAuthInfoCommand{ AuthModule: id.AuthModule, AuthId: id.AuthID, UserId: userID, @@ -222,7 +221,7 @@ func (s *UserSync) createUser(ctx context.Context, id *authn.Identity) (*user.Us } if id.AuthModule != "" && id.AuthID != "" { - if errSetAuth := s.authInfoService.SetAuthInfo(ctx, &models.SetAuthInfoCommand{ + if errSetAuth := s.authInfoService.SetAuthInfo(ctx, &login.SetAuthInfoCommand{ UserId: usr.ID, AuthModule: id.AuthModule, AuthId: id.AuthID, @@ -241,10 +240,10 @@ func (s *UserSync) createUser(ctx context.Context, id *authn.Identity) (*user.Us func (s *UserSync) UserInDB(ctx context.Context, authID *string, authModule *string, - params models.UserLookupParams) (*user.User, error) { + params login.UserLookupParams) (*user.User, error) { // Check authinfo table if authID != nil && authModule != nil { - query := &models.GetAuthInfoQuery{ + query := &login.GetAuthInfoQuery{ AuthModule: *authModule, AuthId: *authID, } @@ -269,7 +268,7 @@ func (s *UserSync) UserInDB(ctx context.Context, return s.LookupByOneOf(ctx, ¶ms) } -func (s *UserSync) LookupByOneOf(ctx context.Context, params *models.UserLookupParams) (*user.User, error) { +func (s *UserSync) LookupByOneOf(ctx context.Context, params *login.UserLookupParams) (*user.User, error) { var usr *user.User var err error diff --git a/pkg/services/authn/authnimpl/sync/user_sync_test.go b/pkg/services/authn/authnimpl/sync/user_sync_test.go index cb92d1112e2..544419c76a8 100644 --- a/pkg/services/authn/authnimpl/sync/user_sync_test.go +++ b/pkg/services/authn/authnimpl/sync/user_sync_test.go @@ -4,7 +4,8 @@ import ( "context" "testing" - "github.com/grafana/grafana/pkg/models" + "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/services/authn" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/authinfoservice" @@ -13,7 +14,6 @@ import ( "github.com/grafana/grafana/pkg/services/quota/quotatest" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user/usertest" - "github.com/stretchr/testify/require" ) func ptrString(s string) *string { @@ -34,17 +34,17 @@ func TestUserSync_SyncUser(t *testing.T) { authFakeNil := &logintest.AuthInfoServiceFake{ ExpectedUser: nil, ExpectedError: user.ErrUserNotFound, - SetAuthInfoFn: func(ctx context.Context, cmd *models.SetAuthInfoCommand) error { + SetAuthInfoFn: func(ctx context.Context, cmd *login.SetAuthInfoCommand) error { return nil }, - UpdateAuthInfoFn: func(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error { + UpdateAuthInfoFn: func(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error { return nil }, } authFakeUserID := &logintest.AuthInfoServiceFake{ ExpectedUser: nil, ExpectedError: nil, - ExpectedUserAuth: &models.UserAuth{ + ExpectedUserAuth: &login.UserAuth{ AuthModule: "oauth", AuthId: "2032", UserId: 1, @@ -111,7 +111,7 @@ func TestUserSync_SyncUser(t *testing.T) { Name: "test", Email: "test", ClientParams: authn.ClientParams{ - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test"), Login: nil, @@ -126,7 +126,7 @@ func TestUserSync_SyncUser(t *testing.T) { Name: "test", Email: "test", ClientParams: authn.ClientParams{ - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test"), Login: nil, @@ -150,7 +150,7 @@ func TestUserSync_SyncUser(t *testing.T) { Email: "test", ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test"), Login: nil, @@ -167,7 +167,7 @@ func TestUserSync_SyncUser(t *testing.T) { IsGrafanaAdmin: ptrBool(false), ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test"), Login: nil, @@ -191,7 +191,7 @@ func TestUserSync_SyncUser(t *testing.T) { Email: "test", ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: nil, Login: ptrString("test"), @@ -207,7 +207,7 @@ func TestUserSync_SyncUser(t *testing.T) { Email: "test", IsGrafanaAdmin: ptrBool(false), ClientParams: authn.ClientParams{ - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: nil, Login: ptrString("test"), @@ -232,7 +232,7 @@ func TestUserSync_SyncUser(t *testing.T) { Email: "test", ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: ptrInt64(1), Email: nil, Login: nil, @@ -249,7 +249,7 @@ func TestUserSync_SyncUser(t *testing.T) { IsGrafanaAdmin: ptrBool(false), ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: ptrInt64(1), Email: nil, Login: nil, @@ -274,7 +274,7 @@ func TestUserSync_SyncUser(t *testing.T) { Email: "test", ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: nil, Login: nil, @@ -291,7 +291,7 @@ func TestUserSync_SyncUser(t *testing.T) { IsGrafanaAdmin: ptrBool(false), ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: nil, Login: nil, @@ -317,7 +317,7 @@ func TestUserSync_SyncUser(t *testing.T) { AuthID: "2032", ClientParams: authn.ClientParams{ SyncUser: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: nil, Login: nil, @@ -348,7 +348,7 @@ func TestUserSync_SyncUser(t *testing.T) { SyncUser: true, AllowSignUp: true, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test_create"), Login: nil, @@ -369,7 +369,7 @@ func TestUserSync_SyncUser(t *testing.T) { SyncUser: true, AllowSignUp: true, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: ptrString("test_create"), Login: nil, @@ -396,7 +396,7 @@ func TestUserSync_SyncUser(t *testing.T) { ClientParams: authn.ClientParams{ SyncUser: true, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: ptrInt64(3), Email: nil, Login: nil, @@ -415,7 +415,7 @@ func TestUserSync_SyncUser(t *testing.T) { ClientParams: authn.ClientParams{ SyncUser: true, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: ptrInt64(3), Email: nil, Login: nil, diff --git a/pkg/services/authn/clients/grafana_test.go b/pkg/services/authn/clients/grafana_test.go index 918888f5a23..9bf3ce88a13 100644 --- a/pkg/services/authn/clients/grafana_test.go +++ b/pkg/services/authn/clients/grafana_test.go @@ -5,14 +5,15 @@ import ( "net/http" "testing" - "github.com/grafana/grafana/pkg/models" + "github.com/stretchr/testify/assert" + "github.com/grafana/grafana/pkg/services/authn" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user/usertest" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" - "github.com/stretchr/testify/assert" ) func TestGrafana_AuthenticateProxy(t *testing.T) { @@ -51,7 +52,7 @@ func TestGrafana_AuthenticateProxy(t *testing.T) { SyncUser: true, SyncTeamMembers: true, AllowSignUp: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ Email: strPtr("email@email.com"), Login: strPtr("test"), }, @@ -72,7 +73,7 @@ func TestGrafana_AuthenticateProxy(t *testing.T) { SyncUser: true, SyncTeamMembers: true, AllowSignUp: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ Email: strPtr("test@test.com"), Login: strPtr("test@test.com"), }, diff --git a/pkg/services/authn/clients/jwt_test.go b/pkg/services/authn/clients/jwt_test.go index d95876fd4f6..29035b19145 100644 --- a/pkg/services/authn/clients/jwt_test.go +++ b/pkg/services/authn/clients/jwt_test.go @@ -10,10 +10,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models/roletype" "github.com/grafana/grafana/pkg/services/auth/jwt" "github.com/grafana/grafana/pkg/services/authn" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/setting" ) @@ -52,7 +52,7 @@ func TestAuthenticateJWT(t *testing.T) { SyncTeamMembers: false, SyncUser: true, AllowSignUp: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ UserID: nil, Email: stringPtr("eai.doe@cor.po"), Login: stringPtr("eai-doe"), diff --git a/pkg/services/authn/clients/ldap.go b/pkg/services/authn/clients/ldap.go index 0e8f14a5be0..943601abf42 100644 --- a/pkg/services/authn/clients/ldap.go +++ b/pkg/services/authn/clients/ldap.go @@ -4,8 +4,8 @@ import ( "context" "errors" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/authn" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/setting" ) @@ -36,7 +36,7 @@ func (c *LDAP) AuthenticateProxy(ctx context.Context, r *authn.Request, username } func (c *LDAP) AuthenticatePassword(ctx context.Context, r *authn.Request, username, password string) (*authn.Identity, error) { - info, err := c.service.Login(&models.LoginUserQuery{ + info, err := c.service.Login(&login.LoginUserQuery{ Username: username, Password: password, }) @@ -61,8 +61,8 @@ func (c *LDAP) AuthenticatePassword(ctx context.Context, r *authn.Request, usern } type ldapService interface { - Login(query *models.LoginUserQuery) (*models.ExternalUserInfo, error) - User(username string) (*models.ExternalUserInfo, error) + Login(query *login.LoginUserQuery) (*login.ExternalUserInfo, error) + User(username string) (*login.ExternalUserInfo, error) } // FIXME: remove the implementation if we convert ldap to an actual service @@ -70,7 +70,7 @@ type ldapServiceImpl struct { cfg *setting.Cfg } -func (s *ldapServiceImpl) Login(query *models.LoginUserQuery) (*models.ExternalUserInfo, error) { +func (s *ldapServiceImpl) Login(query *login.LoginUserQuery) (*login.ExternalUserInfo, error) { cfg, err := multildap.GetConfig(s.cfg) if err != nil { return nil, err @@ -79,7 +79,7 @@ func (s *ldapServiceImpl) Login(query *models.LoginUserQuery) (*models.ExternalU return multildap.New(cfg.Servers).Login(query) } -func (s *ldapServiceImpl) User(username string) (*models.ExternalUserInfo, error) { +func (s *ldapServiceImpl) User(username string) (*login.ExternalUserInfo, error) { cfg, err := multildap.GetConfig(s.cfg) if err != nil { return nil, err @@ -89,7 +89,7 @@ func (s *ldapServiceImpl) User(username string) (*models.ExternalUserInfo, error return user, err } -func identityFromLDAPInfo(orgID int64, info *models.ExternalUserInfo, allowSignup bool) *authn.Identity { +func identityFromLDAPInfo(orgID int64, info *login.ExternalUserInfo, allowSignup bool) *authn.Identity { return &authn.Identity{ OrgID: orgID, OrgRoles: info.OrgRoles, @@ -105,7 +105,7 @@ func identityFromLDAPInfo(orgID int64, info *models.ExternalUserInfo, allowSignu SyncTeamMembers: true, AllowSignUp: allowSignup, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ Login: &info.Login, Email: &info.Email, }, diff --git a/pkg/services/authn/clients/ldap_test.go b/pkg/services/authn/clients/ldap_test.go index e59516f2cf1..e5c59207320 100644 --- a/pkg/services/authn/clients/ldap_test.go +++ b/pkg/services/authn/clients/ldap_test.go @@ -4,14 +4,14 @@ import ( "context" "testing" - "github.com/grafana/grafana/pkg/models" + "github.com/stretchr/testify/assert" + "github.com/grafana/grafana/pkg/services/authn" "github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/setting" - "github.com/stretchr/testify/assert" ) func TestLDAP_AuthenticateProxy(t *testing.T) { @@ -19,7 +19,7 @@ func TestLDAP_AuthenticateProxy(t *testing.T) { desc string username string expectedLDAPErr error - expectedLDAPInfo *models.ExternalUserInfo + expectedLDAPInfo *login.ExternalUserInfo expectedErr error expectedIdentity *authn.Identity } @@ -28,7 +28,7 @@ func TestLDAP_AuthenticateProxy(t *testing.T) { { desc: "should return valid identity when found by ldap service", username: "test", - expectedLDAPInfo: &models.ExternalUserInfo{ + expectedLDAPInfo: &login.ExternalUserInfo{ AuthModule: login.LDAPAuthModule, AuthId: "123", Email: "test@test.com", @@ -51,7 +51,7 @@ func TestLDAP_AuthenticateProxy(t *testing.T) { SyncTeamMembers: true, AllowSignUp: false, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ Email: strPtr("test@test.com"), Login: strPtr("test"), }, @@ -83,7 +83,7 @@ func TestLDAP_AuthenticatePassword(t *testing.T) { password string expectedErr error expectedLDAPErr error - expectedLDAPInfo *models.ExternalUserInfo + expectedLDAPInfo *login.ExternalUserInfo expectedIdentity *authn.Identity } @@ -92,7 +92,7 @@ func TestLDAP_AuthenticatePassword(t *testing.T) { desc: "should successfully authenticate with correct username and password", username: "test", password: "test123", - expectedLDAPInfo: &models.ExternalUserInfo{ + expectedLDAPInfo: &login.ExternalUserInfo{ AuthModule: login.LDAPAuthModule, AuthId: "123", Email: "test@test.com", @@ -115,7 +115,7 @@ func TestLDAP_AuthenticatePassword(t *testing.T) { SyncTeamMembers: true, AllowSignUp: false, EnableDisabledUsers: true, - LookUpParams: models.UserLookupParams{ + LookUpParams: login.UserLookupParams{ Email: strPtr("test@test.com"), Login: strPtr("test"), }, @@ -157,13 +157,13 @@ var _ ldapService = new(fakeLDAPService) type fakeLDAPService struct { ExpectedErr error - ExpectedInfo *models.ExternalUserInfo + ExpectedInfo *login.ExternalUserInfo } -func (f fakeLDAPService) Login(query *models.LoginUserQuery) (*models.ExternalUserInfo, error) { +func (f fakeLDAPService) Login(query *login.LoginUserQuery) (*login.ExternalUserInfo, error) { return f.ExpectedInfo, f.ExpectedErr } -func (f fakeLDAPService) User(username string) (*models.ExternalUserInfo, error) { +func (f fakeLDAPService) User(username string) (*login.ExternalUserInfo, error) { return f.ExpectedInfo, f.ExpectedErr } diff --git a/pkg/services/contexthandler/auth_jwt.go b/pkg/services/contexthandler/auth_jwt.go index 24f7a2c0a22..a0a5b9750a9 100644 --- a/pkg/services/contexthandler/auth_jwt.go +++ b/pkg/services/contexthandler/auth_jwt.go @@ -9,10 +9,10 @@ import ( "github.com/jmespath/go-jmespath" "github.com/grafana/grafana/pkg/login" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models/roletype" authJWT "github.com/grafana/grafana/pkg/services/auth/jwt" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + loginsvc "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/user" ) @@ -61,8 +61,7 @@ func (h *ContextHandler) initContextWithJWT(ctx *contextmodel.ReqContext, orgId ctx.JsonApiErr(http.StatusUnauthorized, InvalidJWT, err) return true } - - extUser := &models.ExternalUserInfo{ + extUser := &loginsvc.ExternalUserInfo{ AuthModule: "jwt", AuthId: sub, OrgRoles: map[int64]org.RoleType{}, @@ -118,11 +117,11 @@ func (h *ContextHandler) initContextWithJWT(ctx *contextmodel.ReqContext, orgId } if h.Cfg.JWTAuthAutoSignUp { - upsert := &models.UpsertUserCommand{ + upsert := &loginsvc.UpsertUserCommand{ ReqContext: ctx, SignupAllowed: h.Cfg.JWTAuthAutoSignUp, ExternalUser: extUser, - UserLookupParams: models.UserLookupParams{ + UserLookupParams: loginsvc.UserLookupParams{ UserID: nil, Login: &query.Login, Email: &query.Email, diff --git a/pkg/services/contexthandler/auth_proxy_test.go b/pkg/services/contexthandler/auth_proxy_test.go index 55cf1ada314..773e6b36ee0 100644 --- a/pkg/services/contexthandler/auth_proxy_test.go +++ b/pkg/services/contexthandler/auth_proxy_test.go @@ -12,13 +12,13 @@ import ( "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/infra/tracing" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/jwt" "github.com/grafana/grafana/pkg/services/authn/authntest" "github.com/grafana/grafana/pkg/services/contexthandler/authproxy" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/rendering" @@ -114,6 +114,6 @@ func getContextHandler(t *testing.T) *ContextHandler { type fakeAuthenticator struct{} -func (fa *fakeAuthenticator) AuthenticateUser(c context.Context, query *models.LoginUserQuery) error { +func (fa *fakeAuthenticator) AuthenticateUser(c context.Context, query *login.LoginUserQuery) error { return nil } diff --git a/pkg/services/contexthandler/authproxy/authproxy.go b/pkg/services/contexthandler/authproxy/authproxy.go index 1cf0a7993d1..6a6fbda21b7 100644 --- a/pkg/services/contexthandler/authproxy/authproxy.go +++ b/pkg/services/contexthandler/authproxy/authproxy.go @@ -16,7 +16,6 @@ import ( "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/remotecache" - "github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/login" @@ -242,11 +241,11 @@ func (auth *AuthProxy) LoginViaLDAP(reqCtx *contextmodel.ReqContext) (int64, err } // Have to sync grafana and LDAP user during log in - upsert := &models.UpsertUserCommand{ + upsert := &login.UpsertUserCommand{ ReqContext: reqCtx, SignupAllowed: auth.cfg.LDAPAllowSignup, ExternalUser: extUser, - UserLookupParams: models.UserLookupParams{ + UserLookupParams: login.UserLookupParams{ Login: &extUser.Login, Email: &extUser.Email, UserID: nil, @@ -262,7 +261,7 @@ func (auth *AuthProxy) LoginViaLDAP(reqCtx *contextmodel.ReqContext) (int64, err // loginViaHeader logs in user from the header only func (auth *AuthProxy) loginViaHeader(reqCtx *contextmodel.ReqContext) (int64, error) { header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName) - extUser := &models.ExternalUserInfo{ + extUser := &login.ExternalUserInfo{ AuthModule: login.AuthProxyAuthModule, AuthId: header, } @@ -304,11 +303,11 @@ func (auth *AuthProxy) loginViaHeader(reqCtx *contextmodel.ReqContext) (int64, e } }) - upsert := &models.UpsertUserCommand{ + upsert := &login.UpsertUserCommand{ ReqContext: reqCtx, SignupAllowed: auth.cfg.AuthProxyAutoSignUp, ExternalUser: extUser, - UserLookupParams: models.UserLookupParams{ + UserLookupParams: login.UserLookupParams{ UserID: nil, Login: &extUser.Login, Email: &extUser.Email, diff --git a/pkg/services/contexthandler/contexthandler.go b/pkg/services/contexthandler/contexthandler.go index 034cc80bcc0..14f3398ec85 100644 --- a/pkg/services/contexthandler/contexthandler.go +++ b/pkg/services/contexthandler/contexthandler.go @@ -20,7 +20,6 @@ import ( "github.com/grafana/grafana/pkg/infra/tracing" loginpkg "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/middleware/cookies" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/apikey" "github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth/jwt" @@ -419,7 +418,7 @@ func (h *ContextHandler) initContextWithBasicAuth(reqContext *contextmodel.ReqCo ctx := WithAuthHTTPHeader(reqContext.Req.Context(), "Authorization") *reqContext.Req = *reqContext.Req.WithContext(ctx) - authQuery := models.LoginUserQuery{ + authQuery := login.LoginUserQuery{ Username: username, Password: password, Cfg: h.Cfg, @@ -774,7 +773,7 @@ func AuthHTTPHeaderListFromContext(c context.Context) *AuthHTTPHeaderList { return nil } -func (h *ContextHandler) hasAccessTokenExpired(token *models.UserAuth) bool { +func (h *ContextHandler) hasAccessTokenExpired(token *login.UserAuth) bool { if token.OAuthExpiry.IsZero() { return false } diff --git a/pkg/services/hooks/hooks.go b/pkg/services/hooks/hooks.go index 1729067e676..af36933ee20 100644 --- a/pkg/services/hooks/hooks.go +++ b/pkg/services/hooks/hooks.go @@ -2,13 +2,13 @@ package hooks import ( "github.com/grafana/grafana/pkg/api/dtos" - "github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + "github.com/grafana/grafana/pkg/services/login" ) type IndexDataHook func(indexData *dtos.IndexViewData, req *contextmodel.ReqContext) -type LoginHook func(loginInfo *models.LoginInfo, req *contextmodel.ReqContext) +type LoginHook func(loginInfo *login.LoginInfo, req *contextmodel.ReqContext) type HooksService struct { indexDataHooks []IndexDataHook @@ -33,7 +33,7 @@ func (srv *HooksService) AddLoginHook(hook LoginHook) { srv.loginHooks = append(srv.loginHooks, hook) } -func (srv *HooksService) RunLoginHook(loginInfo *models.LoginInfo, req *contextmodel.ReqContext) { +func (srv *HooksService) RunLoginHook(loginInfo *login.LoginInfo, req *contextmodel.ReqContext) { for _, hook := range srv.loginHooks { hook(loginInfo, req) } diff --git a/pkg/services/ldap/ldap.go b/pkg/services/ldap/ldap.go index 934a3c0c8e0..8a65c939fcd 100644 --- a/pkg/services/ldap/ldap.go +++ b/pkg/services/ldap/ldap.go @@ -15,7 +15,6 @@ import ( "gopkg.in/ldap.v3" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" ) @@ -33,8 +32,8 @@ type IConnection interface { // IServer is interface for LDAP authorization type IServer interface { - Login(*models.LoginUserQuery) (*models.ExternalUserInfo, error) - Users([]string) ([]*models.ExternalUserInfo, error) + Login(*login.LoginUserQuery) (*login.ExternalUserInfo, error) + Users([]string) ([]*login.ExternalUserInfo, error) Bind() error UserBind(string, string) error Dial() error @@ -202,8 +201,8 @@ func (server *Server) Close() { // // Dial() sets the connection with the server for this Struct. Therefore, we require a // call to Dial() before being able to execute this function. -func (server *Server) Login(query *models.LoginUserQuery) ( - *models.ExternalUserInfo, error, +func (server *Server) Login(query *login.LoginUserQuery) ( + *login.ExternalUserInfo, error, ) { var err error var authAndBind bool @@ -279,7 +278,7 @@ func (server *Server) shouldSingleBind() bool { // Dial() sets the connection with the server for this Struct. Therefore, we require a // call to Dial() before being able to execute this function. func (server *Server) Users(logins []string) ( - []*models.ExternalUserInfo, + []*login.ExternalUserInfo, error, ) { var users [][]*ldap.Entry @@ -293,7 +292,7 @@ func (server *Server) Users(logins []string) ( } if len(users) == 0 { - return []*models.ExternalUserInfo{}, nil + return []*login.ExternalUserInfo{}, nil } serializedUsers, err := server.serializeUsers(users) @@ -361,7 +360,7 @@ func (server *Server) users(logins []string) ( // validateGrafanaUser validates user access. // If there are no ldap group mappings access is true // otherwise a single group must match -func (server *Server) validateGrafanaUser(user *models.ExternalUserInfo) error { +func (server *Server) validateGrafanaUser(user *login.ExternalUserInfo) error { if !SkipOrgRoleSync() && len(server.Config.Groups) > 0 && (len(user.OrgRoles) == 0 && (user.IsGrafanaAdmin == nil || !*user.IsGrafanaAdmin)) { server.log.Error( @@ -423,14 +422,14 @@ func (server *Server) getSearchRequest( } // buildGrafanaUser extracts info from UserInfo model to ExternalUserInfo -func (server *Server) buildGrafanaUser(user *ldap.Entry) (*models.ExternalUserInfo, error) { +func (server *Server) buildGrafanaUser(user *ldap.Entry) (*login.ExternalUserInfo, error) { memberOf, err := server.getMemberOf(user) if err != nil { return nil, err } attrs := server.Config.Attr - extUser := &models.ExternalUserInfo{ + extUser := &login.ExternalUserInfo{ AuthModule: login.LDAPAuthModule, AuthId: user.DN, Name: strings.TrimSpace( @@ -595,8 +594,8 @@ func (server *Server) requestMemberOf(entry *ldap.Entry) ([]string, error) { // from LDAP result to ExternalInfo struct func (server *Server) serializeUsers( entries [][]*ldap.Entry, -) ([]*models.ExternalUserInfo, error) { - var serialized []*models.ExternalUserInfo +) ([]*login.ExternalUserInfo, error) { + var serialized []*login.ExternalUserInfo var users = map[string]struct{}{} for _, dn := range entries { diff --git a/pkg/services/ldap/ldap_groups.go b/pkg/services/ldap/ldap_groups.go index a3e6053e575..be23712313d 100644 --- a/pkg/services/ldap/ldap_groups.go +++ b/pkg/services/ldap/ldap_groups.go @@ -1,9 +1,7 @@ package ldap -import "github.com/grafana/grafana/pkg/models" - type Groups interface { - GetTeams(groups []string, orgIDs []int64) ([]models.TeamOrgGroupDTO, error) + GetTeams(groups []string, orgIDs []int64) ([]TeamOrgGroupDTO, error) } type OSSGroups struct{} @@ -12,6 +10,6 @@ func ProvideGroupsService() *OSSGroups { return &OSSGroups{} } -func (*OSSGroups) GetTeams(_ []string, _ []int64) ([]models.TeamOrgGroupDTO, error) { +func (*OSSGroups) GetTeams(_ []string, _ []int64) ([]TeamOrgGroupDTO, error) { return nil, nil } diff --git a/pkg/services/ldap/ldap_login_test.go b/pkg/services/ldap/ldap_login_test.go index 7b552a8edfa..c31b2cb4dbd 100644 --- a/pkg/services/ldap/ldap_login_test.go +++ b/pkg/services/ldap/ldap_login_test.go @@ -10,10 +10,10 @@ import ( "gopkg.in/ldap.v3" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/login" ) -var defaultLogin = &models.LoginUserQuery{ +var defaultLogin = &login.LoginUserQuery{ Username: "user", Password: "pwd", IpAddress: "192.168.1.1:56433", diff --git a/pkg/services/ldap/ldap_private_test.go b/pkg/services/ldap/ldap_private_test.go index b7846f58f6c..e9d534051eb 100644 --- a/pkg/services/ldap/ldap_private_test.go +++ b/pkg/services/ldap/ldap_private_test.go @@ -10,7 +10,7 @@ import ( "gopkg.in/ldap.v3" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" ) @@ -159,7 +159,7 @@ func TestServer_validateGrafanaUser(t *testing.T) { log: logger.New("test"), } - user := &models.ExternalUserInfo{ + user := &login.ExternalUserInfo{ Login: "markelog", } @@ -179,7 +179,7 @@ func TestServer_validateGrafanaUser(t *testing.T) { log: logger.New("test"), } - user := &models.ExternalUserInfo{ + user := &login.ExternalUserInfo{ Login: "markelog", OrgRoles: map[int64]org.RoleType{ 1: "test", @@ -202,7 +202,7 @@ func TestServer_validateGrafanaUser(t *testing.T) { log: logger.New("test"), } - user := &models.ExternalUserInfo{ + user := &login.ExternalUserInfo{ Login: "markelog", } diff --git a/pkg/services/ldap/model.go b/pkg/services/ldap/model.go new file mode 100644 index 00000000000..302f5bffabe --- /dev/null +++ b/pkg/services/ldap/model.go @@ -0,0 +1,7 @@ +package ldap + +type TeamOrgGroupDTO struct { + TeamName string `json:"teamName"` + OrgName string `json:"orgName"` + GroupDN string `json:"groupDN"` +} diff --git a/pkg/services/login/authinfo.go b/pkg/services/login/authinfo.go index 01476e31ef2..9f7e8908533 100644 --- a/pkg/services/login/authinfo.go +++ b/pkg/services/login/authinfo.go @@ -3,17 +3,16 @@ package login import ( "context" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/user" ) type AuthInfoService interface { - LookupAndUpdate(ctx context.Context, query *models.GetUserByAuthInfoQuery) (*user.User, error) - GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error - GetUserLabels(ctx context.Context, query models.GetUserLabelsQuery) (map[int64]string, error) - GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error - SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error - UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error + LookupAndUpdate(ctx context.Context, query *GetUserByAuthInfoQuery) (*user.User, error) + GetAuthInfo(ctx context.Context, query *GetAuthInfoQuery) error + GetUserLabels(ctx context.Context, query GetUserLabelsQuery) (map[int64]string, error) + GetExternalUserInfoByLogin(ctx context.Context, query *GetExternalUserInfoByLoginQuery) error + SetAuthInfo(ctx context.Context, cmd *SetAuthInfoCommand) error + UpdateAuthInfo(ctx context.Context, cmd *UpdateAuthInfoCommand) error DeleteUserAuthInfo(ctx context.Context, userID int64) error } diff --git a/pkg/services/login/authinfoservice/database/database.go b/pkg/services/login/authinfoservice/database/database.go index 1aa23b77d17..1d4abbfe85b 100644 --- a/pkg/services/login/authinfoservice/database/database.go +++ b/pkg/services/login/authinfoservice/database/database.go @@ -7,7 +7,6 @@ import ( "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/secrets" "github.com/grafana/grafana/pkg/services/user" @@ -35,19 +34,19 @@ func ProvideAuthInfoStore(sqlStore db.DB, secretsService secrets.Service, userSe return store } -func (s *AuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error { +func (s *AuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *login.GetExternalUserInfoByLoginQuery) error { userQuery := user.GetUserByLoginQuery{LoginOrEmail: query.LoginOrEmail} usr, err := s.userService.GetByLogin(ctx, &userQuery) if err != nil { return err } - authInfoQuery := &models.GetAuthInfoQuery{UserId: usr.ID} + authInfoQuery := &login.GetAuthInfoQuery{UserId: usr.ID} if err := s.GetAuthInfo(ctx, authInfoQuery); err != nil { return err } - query.Result = &models.ExternalUserInfo{ + query.Result = &login.ExternalUserInfo{ UserId: usr.ID, Login: usr.Login, Email: usr.Email, @@ -59,12 +58,12 @@ func (s *AuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *m return nil } -func (s *AuthInfoStore) GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error { +func (s *AuthInfoStore) GetAuthInfo(ctx context.Context, query *login.GetAuthInfoQuery) error { if query.UserId == 0 && query.AuthId == "" { return user.ErrUserNotFound } - userAuth := &models.UserAuth{ + userAuth := &login.UserAuth{ UserId: query.UserId, AuthModule: query.AuthModule, AuthId: query.AuthId, @@ -110,8 +109,8 @@ func (s *AuthInfoStore) GetAuthInfo(ctx context.Context, query *models.GetAuthIn return nil } -func (s *AuthInfoStore) GetUserLabels(ctx context.Context, query models.GetUserLabelsQuery) (map[int64]string, error) { - userAuths := []models.UserAuth{} +func (s *AuthInfoStore) GetUserLabels(ctx context.Context, query login.GetUserLabelsQuery) (map[int64]string, error) { + userAuths := []login.UserAuth{} params := make([]interface{}, 0, len(query.UserIDs)) for _, id := range query.UserIDs { params = append(params, id) @@ -134,8 +133,8 @@ func (s *AuthInfoStore) GetUserLabels(ctx context.Context, query models.GetUserL return labelMap, nil } -func (s *AuthInfoStore) SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error { - authUser := &models.UserAuth{ +func (s *AuthInfoStore) SetAuthInfo(ctx context.Context, cmd *login.SetAuthInfoCommand) error { + authUser := &login.UserAuth{ UserId: cmd.UserId, AuthModule: cmd.AuthModule, AuthId: cmd.AuthId, @@ -179,10 +178,10 @@ func (s *AuthInfoStore) SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfo // UpdateAuthInfoDate updates the auth info for the user with the latest date. // Avoids overlapping entries hiding the last used one (ex: LDAP->SAML->LDAP). -func (s *AuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *models.UserAuth) error { +func (s *AuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *login.UserAuth) error { authInfo.Created = GetTime() - cond := &models.UserAuth{ + cond := &login.UserAuth{ Id: authInfo.Id, UserId: authInfo.UserId, AuthModule: authInfo.AuthModule, @@ -193,8 +192,8 @@ func (s *AuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *models }) } -func (s *AuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error { - authUser := &models.UserAuth{ +func (s *AuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error { + authUser := &login.UserAuth{ UserId: cmd.UserId, AuthModule: cmd.AuthModule, AuthId: cmd.AuthId, @@ -237,7 +236,7 @@ func (s *AuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAu }) } -func (s *AuthInfoStore) DeleteAuthInfo(ctx context.Context, cmd *models.DeleteAuthInfoCommand) error { +func (s *AuthInfoStore) DeleteAuthInfo(ctx context.Context, cmd *login.DeleteAuthInfoCommand) error { return s.sqlStore.WithTransactionalDbSession(ctx, func(sess *db.Session) error { _, err := sess.Delete(cmd.UserAuth) return err diff --git a/pkg/services/login/authinfoservice/service.go b/pkg/services/login/authinfoservice/service.go index 1f248453eb5..e0d6f440994 100644 --- a/pkg/services/login/authinfoservice/service.go +++ b/pkg/services/login/authinfoservice/service.go @@ -6,7 +6,6 @@ import ( "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/usagestats" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" ) @@ -31,8 +30,8 @@ func ProvideAuthInfoService(userProtectionService login.UserProtectionService, a return s } -func (s *Implementation) LookupAndFix(ctx context.Context, query *models.GetUserByAuthInfoQuery) (bool, *user.User, *models.UserAuth, error) { - authQuery := &models.GetAuthInfoQuery{} +func (s *Implementation) LookupAndFix(ctx context.Context, query *login.GetUserByAuthInfoQuery) (bool, *user.User, *login.UserAuth, error) { + authQuery := &login.GetAuthInfoQuery{} // Try to find the user by auth module and id first if query.AuthModule != "" && query.AuthId != "" { @@ -49,7 +48,7 @@ func (s *Implementation) LookupAndFix(ctx context.Context, query *models.GetUser if query.UserLookupParams.UserID != nil && *query.UserLookupParams.UserID != 0 && *query.UserLookupParams.UserID != authQuery.Result.UserId { - if err := s.authInfoStore.DeleteAuthInfo(ctx, &models.DeleteAuthInfoCommand{ + if err := s.authInfoStore.DeleteAuthInfo(ctx, &login.DeleteAuthInfoCommand{ UserAuth: authQuery.Result, }); err != nil { s.logger.Error("Error removing user_auth entry", "error", err) @@ -61,7 +60,7 @@ func (s *Implementation) LookupAndFix(ctx context.Context, query *models.GetUser if err != nil { if errors.Is(err, user.ErrUserNotFound) { // if the user has been deleted then remove the entry - if errDel := s.authInfoStore.DeleteAuthInfo(ctx, &models.DeleteAuthInfoCommand{ + if errDel := s.authInfoStore.DeleteAuthInfo(ctx, &login.DeleteAuthInfoCommand{ UserAuth: authQuery.Result, }); errDel != nil { s.logger.Error("Error removing user_auth entry", "error", errDel) @@ -81,7 +80,7 @@ func (s *Implementation) LookupAndFix(ctx context.Context, query *models.GetUser return false, nil, nil, user.ErrUserNotFound } -func (s *Implementation) LookupByOneOf(ctx context.Context, params *models.UserLookupParams) (*user.User, error) { +func (s *Implementation) LookupByOneOf(ctx context.Context, params *login.UserLookupParams) (*user.User, error) { var usr *user.User var err error @@ -116,9 +115,9 @@ func (s *Implementation) LookupByOneOf(ctx context.Context, params *models.UserL return usr, nil } -func (s *Implementation) GenericOAuthLookup(ctx context.Context, authModule string, authId string, userID int64) (*models.UserAuth, error) { +func (s *Implementation) GenericOAuthLookup(ctx context.Context, authModule string, authId string, userID int64) (*login.UserAuth, error) { if authModule == genericOAuthModule && userID != 0 { - authQuery := &models.GetAuthInfoQuery{} + authQuery := &login.GetAuthInfoQuery{} authQuery.AuthModule = authModule authQuery.AuthId = authId authQuery.UserId = userID @@ -132,7 +131,7 @@ func (s *Implementation) GenericOAuthLookup(ctx context.Context, authModule stri return nil, nil } -func (s *Implementation) LookupAndUpdate(ctx context.Context, query *models.GetUserByAuthInfoQuery) (*user.User, error) { +func (s *Implementation) LookupAndUpdate(ctx context.Context, query *login.GetUserByAuthInfoQuery) (*user.User, error) { // 1. LookupAndFix = auth info, user, error // TODO: Not a big fan of the fact that we are deleting auth info here, might want to move that foundUser, usr, authInfo, err := s.LookupAndFix(ctx, query) @@ -165,7 +164,7 @@ func (s *Implementation) LookupAndUpdate(ctx context.Context, query *models.GetU if query.AuthModule != "" { if authInfo == nil { - cmd := &models.SetAuthInfoCommand{ + cmd := &login.SetAuthInfoCommand{ UserId: usr.ID, AuthModule: query.AuthModule, AuthId: query.AuthId, @@ -183,26 +182,26 @@ func (s *Implementation) LookupAndUpdate(ctx context.Context, query *models.GetU return usr, nil } -func (s *Implementation) GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error { +func (s *Implementation) GetAuthInfo(ctx context.Context, query *login.GetAuthInfoQuery) error { return s.authInfoStore.GetAuthInfo(ctx, query) } -func (s *Implementation) GetUserLabels(ctx context.Context, query models.GetUserLabelsQuery) (map[int64]string, error) { +func (s *Implementation) GetUserLabels(ctx context.Context, query login.GetUserLabelsQuery) (map[int64]string, error) { if len(query.UserIDs) == 0 { return map[int64]string{}, nil } return s.authInfoStore.GetUserLabels(ctx, query) } -func (s *Implementation) UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error { +func (s *Implementation) UpdateAuthInfo(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error { return s.authInfoStore.UpdateAuthInfo(ctx, cmd) } -func (s *Implementation) SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error { +func (s *Implementation) SetAuthInfo(ctx context.Context, cmd *login.SetAuthInfoCommand) error { return s.authInfoStore.SetAuthInfo(ctx, cmd) } -func (s *Implementation) GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error { +func (s *Implementation) GetExternalUserInfoByLogin(ctx context.Context, query *login.GetExternalUserInfoByLoginQuery) error { return s.authInfoStore.GetExternalUserInfoByLogin(ctx, query) } diff --git a/pkg/services/login/authinfoservice/user_auth_test.go b/pkg/services/login/authinfoservice/user_auth_test.go index f22814020a5..d61e8191482 100644 --- a/pkg/services/login/authinfoservice/user_auth_test.go +++ b/pkg/services/login/authinfoservice/user_auth_test.go @@ -12,7 +12,6 @@ import ( "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/usagestats" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/authinfoservice/database" "github.com/grafana/grafana/pkg/services/org/orgimpl" @@ -50,22 +49,22 @@ func TestUserAuth(t *testing.T) { t.Run("Can find existing user", func(t *testing.T) { // By Login - login := "loginuser0" + userlogin := "loginuser0" authInfoStore.ExpectedUser = &user.User{ Login: "loginuser0", ID: 1, Email: "user1@test.com", } - query := &models.GetUserByAuthInfoQuery{UserLookupParams: models.UserLookupParams{Login: &login}} + query := &login.GetUserByAuthInfoQuery{UserLookupParams: login.UserLookupParams{Login: &userlogin}} usr, err := srv.LookupAndUpdate(context.Background(), query) require.Nil(t, err) - require.Equal(t, usr.Login, login) + require.Equal(t, usr.Login, userlogin) // By ID id := usr.ID - usr, err = srv.LookupByOneOf(context.Background(), &models.UserLookupParams{ + usr, err = srv.LookupByOneOf(context.Background(), &login.UserLookupParams{ UserID: &id, }) @@ -75,7 +74,7 @@ func TestUserAuth(t *testing.T) { // By Email email := "user1@test.com" - usr, err = srv.LookupByOneOf(context.Background(), &models.UserLookupParams{ + usr, err = srv.LookupByOneOf(context.Background(), &login.UserLookupParams{ Email: &email, }) @@ -86,7 +85,7 @@ func TestUserAuth(t *testing.T) { // Don't find nonexistent user email = "nonexistent@test.com" - usr, err = srv.LookupByOneOf(context.Background(), &models.UserLookupParams{ + usr, err = srv.LookupByOneOf(context.Background(), &login.UserLookupParams{ Email: &email, }) @@ -98,29 +97,29 @@ func TestUserAuth(t *testing.T) { // get nonexistent user_auth entry authInfoStore.ExpectedUser = &user.User{} authInfoStore.ExpectedError = user.ErrUserNotFound - query := &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} + query := &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} usr, err := srv.LookupAndUpdate(context.Background(), query) require.Equal(t, user.ErrUserNotFound, err) require.Nil(t, usr) // create user_auth entry - login := "loginuser0" + userlogin := "loginuser0" authInfoStore.ExpectedUser = &user.User{Login: "loginuser0", ID: 1, Email: ""} authInfoStore.ExpectedError = nil - authInfoStore.ExpectedOAuth = &models.UserAuth{Id: 1} - query.UserLookupParams.Login = &login + authInfoStore.ExpectedOAuth = &login.UserAuth{Id: 1} + query.UserLookupParams.Login = &userlogin usr, err = srv.LookupAndUpdate(context.Background(), query) require.Nil(t, err) - require.Equal(t, usr.Login, login) + require.Equal(t, usr.Login, userlogin) // get via user_auth - query = &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} + query = &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} usr, err = srv.LookupAndUpdate(context.Background(), query) require.Nil(t, err) - require.Equal(t, usr.Login, login) + require.Equal(t, usr.Login, userlogin) // get with non-matching id idPlusOne := usr.ID + 1 @@ -133,7 +132,7 @@ func TestUserAuth(t *testing.T) { require.Equal(t, usr.Login, "loginuser1") // get via user_auth - query = &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} + query = &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} usr, err = srv.LookupAndUpdate(context.Background(), query) require.Nil(t, err) @@ -149,7 +148,7 @@ func TestUserAuth(t *testing.T) { authInfoStore.ExpectedUser = nil authInfoStore.ExpectedError = user.ErrUserNotFound // get via user_auth for deleted user - query = &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} + query = &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test"} usr, err = srv.LookupAndUpdate(context.Background(), query) require.Equal(t, err, user.ErrUserNotFound) @@ -167,10 +166,10 @@ func TestUserAuth(t *testing.T) { token = token.WithExtra(map[string]interface{}{"id_token": idToken}) // Find a user to set tokens on - login := "loginuser0" + userlogin := "loginuser0" authInfoStore.ExpectedUser = &user.User{Login: "loginuser0", ID: 1, Email: ""} authInfoStore.ExpectedError = nil - authInfoStore.ExpectedOAuth = &models.UserAuth{ + authInfoStore.ExpectedOAuth = &login.UserAuth{ Id: 1, OAuthAccessToken: token.AccessToken, OAuthRefreshToken: token.RefreshToken, @@ -179,15 +178,15 @@ func TestUserAuth(t *testing.T) { OAuthExpiry: token.Expiry, } // Calling GetUserByAuthInfoQuery on an existing user will populate an entry in the user_auth table - query := &models.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test", UserLookupParams: models.UserLookupParams{ - Login: &login, + query := &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test", UserLookupParams: login.UserLookupParams{ + Login: &userlogin, }} user, err := srv.LookupAndUpdate(context.Background(), query) require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) - cmd := &models.UpdateAuthInfoCommand{ + cmd := &login.UpdateAuthInfoCommand{ UserId: user.ID, AuthId: query.AuthId, AuthModule: query.AuthModule, @@ -197,7 +196,7 @@ func TestUserAuth(t *testing.T) { require.Nil(t, err) - getAuthQuery := &models.GetAuthInfoQuery{ + getAuthQuery := &login.GetAuthInfoQuery{ UserId: user.ID, } @@ -230,34 +229,34 @@ func TestUserAuth(t *testing.T) { } // Find a user to set tokens on - login := "loginuser0" + userlogin := "loginuser0" // Calling srv.LookupAndUpdateQuery on an existing user will populate an entry in the user_auth table // Make the first log-in during the past database.GetTime = func() time.Time { return time.Now().AddDate(0, 0, -2) } - query := &models.GetUserByAuthInfoQuery{AuthModule: "test1", AuthId: "test1", UserLookupParams: models.UserLookupParams{ - Login: &login, + query := &login.GetUserByAuthInfoQuery{AuthModule: "test1", AuthId: "test1", UserLookupParams: login.UserLookupParams{ + Login: &userlogin, }} user, err := srv.LookupAndUpdate(context.Background(), query) database.GetTime = time.Now require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) // Add a second auth module for this user // Have this module's last log-in be more recent database.GetTime = func() time.Time { return time.Now().AddDate(0, 0, -1) } - query = &models.GetUserByAuthInfoQuery{AuthModule: "test2", AuthId: "test2", UserLookupParams: models.UserLookupParams{ - Login: &login, + query = &login.GetUserByAuthInfoQuery{AuthModule: "test2", AuthId: "test2", UserLookupParams: login.UserLookupParams{ + Login: &userlogin, }} user, err = srv.LookupAndUpdate(context.Background(), query) database.GetTime = time.Now require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) authInfoStore.ExpectedOAuth.AuthModule = "test2" // Get the latest entry by not supply an authmodule or authid - getAuthQuery := &models.GetAuthInfoQuery{ + getAuthQuery := &login.GetAuthInfoQuery{ UserId: user.ID, } @@ -267,13 +266,13 @@ func TestUserAuth(t *testing.T) { require.Equal(t, getAuthQuery.Result.AuthModule, "test2") // "log in" again with the first auth module - updateAuthCmd := &models.UpdateAuthInfoCommand{UserId: user.ID, AuthModule: "test1", AuthId: "test1"} + updateAuthCmd := &login.UpdateAuthInfoCommand{UserId: user.ID, AuthModule: "test1", AuthId: "test1"} err = authInfoStore.UpdateAuthInfo(context.Background(), updateAuthCmd) require.Nil(t, err) authInfoStore.ExpectedOAuth.AuthModule = "test1" // Get the latest entry by not supply an authmodule or authid - getAuthQuery = &models.GetAuthInfoQuery{ + getAuthQuery = &login.GetAuthInfoQuery{ UserId: user.ID, } @@ -303,33 +302,33 @@ func TestUserAuth(t *testing.T) { } // Find a user to set tokens on - login := "loginuser0" + userlogin := "loginuser0" fixedTime := time.Now() // Calling srv.LookupAndUpdateQuery on an existing user will populate an entry in the user_auth table // Make the first log-in during the past database.GetTime = func() time.Time { return fixedTime.AddDate(0, 0, -2) } - queryOne := &models.GetUserByAuthInfoQuery{AuthModule: "test1", AuthId: "test1", UserLookupParams: models.UserLookupParams{ - Login: &login, + queryOne := &login.GetUserByAuthInfoQuery{AuthModule: "test1", AuthId: "test1", UserLookupParams: login.UserLookupParams{ + Login: &userlogin, }} user, err := srv.LookupAndUpdate(context.Background(), queryOne) database.GetTime = time.Now require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) // Add a second auth module for this user // Have this module's last log-in be more recent database.GetTime = func() time.Time { return fixedTime.AddDate(0, 0, -1) } - queryTwo := &models.GetUserByAuthInfoQuery{AuthModule: "test2", AuthId: "test2", UserLookupParams: models.UserLookupParams{ - Login: &login, + queryTwo := &login.GetUserByAuthInfoQuery{AuthModule: "test2", AuthId: "test2", UserLookupParams: login.UserLookupParams{ + Login: &userlogin, }} user, err = srv.LookupAndUpdate(context.Background(), queryTwo) require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) // Get the latest entry by not supply an authmodule or authid - getAuthQuery := &models.GetAuthInfoQuery{ + getAuthQuery := &login.GetAuthInfoQuery{ UserId: user.ID, } authInfoStore.ExpectedOAuth.AuthModule = "test2" @@ -343,7 +342,7 @@ func TestUserAuth(t *testing.T) { database.GetTime = func() time.Time { return fixedTime } // add oauth info to auth_info to make sure update date does not overwrite it - updateAuthCmd := &models.UpdateAuthInfoCommand{UserId: user.ID, AuthModule: "test1", AuthId: "test1", OAuthToken: &oauth2.Token{ + updateAuthCmd := &login.UpdateAuthInfoCommand{UserId: user.ID, AuthModule: "test1", AuthId: "test1", OAuthToken: &oauth2.Token{ AccessToken: "access_token", TokenType: "token_type", RefreshToken: "refresh_token", @@ -354,7 +353,7 @@ func TestUserAuth(t *testing.T) { user, err = srv.LookupAndUpdate(context.Background(), queryOne) require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) authInfoStore.ExpectedOAuth.AuthModule = "test1" authInfoStore.ExpectedOAuth.OAuthAccessToken = "access_token" err = authInfoStore.GetAuthInfo(context.Background(), getAuthQuery) @@ -368,7 +367,7 @@ func TestUserAuth(t *testing.T) { database.GetTime = func() time.Time { return fixedTime.AddDate(0, 0, 1) } user, err = srv.LookupAndUpdate(context.Background(), queryTwo) require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) authInfoStore.ExpectedOAuth.AuthModule = "test2" err = authInfoStore.GetAuthInfo(context.Background(), getAuthQuery) @@ -376,7 +375,7 @@ func TestUserAuth(t *testing.T) { require.Equal(t, "test2", getAuthQuery.Result.AuthModule) // Ensure test 1 did not have its entry modified - getAuthQueryUnchanged := &models.GetAuthInfoQuery{ + getAuthQueryUnchanged := &login.GetAuthInfoQuery{ UserId: user.ID, AuthModule: "test1", } @@ -389,23 +388,23 @@ func TestUserAuth(t *testing.T) { t.Run("Can set & locate by generic oauth auth module and user id", func(t *testing.T) { // Find a user to set tokens on - login := "loginuser0" + userlogin := "loginuser0" // Expect to pass since there's a matching login user database.GetTime = func() time.Time { return time.Now().AddDate(0, 0, -2) } - query := &models.GetUserByAuthInfoQuery{AuthModule: genericOAuthModule, AuthId: "", UserLookupParams: models.UserLookupParams{ - Login: &login, + query := &login.GetUserByAuthInfoQuery{AuthModule: genericOAuthModule, AuthId: "", UserLookupParams: login.UserLookupParams{ + Login: &userlogin, }} user, err := srv.LookupAndUpdate(context.Background(), query) database.GetTime = time.Now require.Nil(t, err) - require.Equal(t, user.Login, login) + require.Equal(t, user.Login, userlogin) otherLoginUser := "aloginuser" // Should throw a "user not found" error since there's no matching login user database.GetTime = func() time.Time { return time.Now().AddDate(0, 0, -2) } - query = &models.GetUserByAuthInfoQuery{AuthModule: genericOAuthModule, AuthId: "", UserLookupParams: models.UserLookupParams{ + query = &login.GetUserByAuthInfoQuery{AuthModule: genericOAuthModule, AuthId: "", UserLookupParams: login.UserLookupParams{ Login: &otherLoginUser, }} authInfoStore.ExpectedError = errors.New("some error") @@ -510,7 +509,7 @@ type FakeAuthInfoStore struct { login.AuthInfoService ExpectedError error ExpectedUser *user.User - ExpectedOAuth *models.UserAuth + ExpectedOAuth *login.UserAuth ExpectedDuplicateUserEntries int ExpectedHasDuplicateUserEntries int ExpectedLoginStats login.LoginStats @@ -520,23 +519,23 @@ func newFakeAuthInfoStore() *FakeAuthInfoStore { return &FakeAuthInfoStore{} } -func (f *FakeAuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error { +func (f *FakeAuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *login.GetExternalUserInfoByLoginQuery) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error { +func (f *FakeAuthInfoStore) GetAuthInfo(ctx context.Context, query *login.GetAuthInfoQuery) error { query.Result = f.ExpectedOAuth return f.ExpectedError } -func (f *FakeAuthInfoStore) SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error { +func (f *FakeAuthInfoStore) SetAuthInfo(ctx context.Context, cmd *login.SetAuthInfoCommand) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *models.UserAuth) error { +func (f *FakeAuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *login.UserAuth) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error { +func (f *FakeAuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) DeleteAuthInfo(ctx context.Context, cmd *models.DeleteAuthInfoCommand) error { +func (f *FakeAuthInfoStore) DeleteAuthInfo(ctx context.Context, cmd *login.DeleteAuthInfoCommand) error { return f.ExpectedError } func (f *FakeAuthInfoStore) GetUserById(ctx context.Context, id int64) (*user.User, error) { diff --git a/pkg/services/login/login.go b/pkg/services/login/login.go index bb1ff508e4a..908d1c43038 100644 --- a/pkg/services/login/login.go +++ b/pkg/services/login/login.go @@ -4,7 +4,6 @@ import ( "context" "errors" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/user" ) @@ -15,10 +14,10 @@ var ( ErrSignupNotAllowed = errors.New("system administrator has disabled signup") ) -type TeamSyncFunc func(user *user.User, externalUser *models.ExternalUserInfo) error +type TeamSyncFunc func(user *user.User, externalUser *ExternalUserInfo) error type Service interface { - UpsertUser(ctx context.Context, cmd *models.UpsertUserCommand) error + UpsertUser(ctx context.Context, cmd *UpsertUserCommand) error DisableExternalUser(ctx context.Context, username string) error SetTeamSyncFunc(TeamSyncFunc) } diff --git a/pkg/services/login/loginservice/loginservice.go b/pkg/services/login/loginservice/loginservice.go index 89cc5351dae..0b18e713136 100644 --- a/pkg/services/login/loginservice/loginservice.go +++ b/pkg/services/login/loginservice/loginservice.go @@ -5,7 +5,6 @@ import ( "errors" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/org" @@ -44,10 +43,10 @@ type Implementation struct { } // UpsertUser updates an existing user, or if it doesn't exist, inserts a new one. -func (ls *Implementation) UpsertUser(ctx context.Context, cmd *models.UpsertUserCommand) error { +func (ls *Implementation) UpsertUser(ctx context.Context, cmd *login.UpsertUserCommand) error { extUser := cmd.ExternalUser - usr, errAuthLookup := ls.AuthInfoService.LookupAndUpdate(ctx, &models.GetUserByAuthInfoQuery{ + usr, errAuthLookup := ls.AuthInfoService.LookupAndUpdate(ctx, &login.GetUserByAuthInfoQuery{ AuthModule: extUser.AuthModule, AuthId: extUser.AuthId, UserLookupParams: cmd.UserLookupParams, @@ -109,7 +108,7 @@ func (ls *Implementation) UpsertUser(ctx context.Context, cmd *models.UpsertUser } if extUser.AuthModule != "" { - cmd2 := &models.SetAuthInfoCommand{ + cmd2 := &login.SetAuthInfoCommand{ UserId: cmd.Result.ID, AuthModule: extUser.AuthModule, AuthId: extUser.AuthId, @@ -166,7 +165,7 @@ func (ls *Implementation) UpsertUser(ctx context.Context, cmd *models.UpsertUser func (ls *Implementation) DisableExternalUser(ctx context.Context, username string) error { // Check if external user exist in Grafana - userQuery := &models.GetExternalUserInfoByLoginQuery{ + userQuery := &login.GetExternalUserInfoByLoginQuery{ LoginOrEmail: username, } @@ -209,7 +208,7 @@ func (ls *Implementation) SetTeamSyncFunc(teamSyncFunc login.TeamSyncFunc) { ls.TeamSync = teamSyncFunc } -func (ls *Implementation) updateUser(ctx context.Context, usr *user.User, extUser *models.ExternalUserInfo) error { +func (ls *Implementation) updateUser(ctx context.Context, usr *user.User, extUser *login.ExternalUserInfo) error { // sync user info updateCmd := &user.UpdateUserCommand{ UserID: usr.ID, @@ -242,8 +241,8 @@ func (ls *Implementation) updateUser(ctx context.Context, usr *user.User, extUse return ls.userService.Update(ctx, updateCmd) } -func (ls *Implementation) updateUserAuth(ctx context.Context, user *user.User, extUser *models.ExternalUserInfo) error { - updateCmd := &models.UpdateAuthInfoCommand{ +func (ls *Implementation) updateUserAuth(ctx context.Context, user *user.User, extUser *login.ExternalUserInfo) error { + updateCmd := &login.UpdateAuthInfoCommand{ AuthModule: extUser.AuthModule, AuthId: extUser.AuthId, UserId: user.ID, @@ -254,7 +253,7 @@ func (ls *Implementation) updateUserAuth(ctx context.Context, user *user.User, e return ls.AuthInfoService.UpdateAuthInfo(ctx, updateCmd) } -func (ls *Implementation) syncOrgRoles(ctx context.Context, usr *user.User, extUser *models.ExternalUserInfo) error { +func (ls *Implementation) syncOrgRoles(ctx context.Context, usr *user.User, extUser *login.ExternalUserInfo) error { logger.Debug("Syncing organization roles", "id", usr.ID, "extOrgRoles", extUser.OrgRoles) // don't sync org roles if none is specified diff --git a/pkg/services/login/loginservice/loginservice_mock.go b/pkg/services/login/loginservice/loginservice_mock.go index b77ac1b4caa..dbb39e0fcf6 100644 --- a/pkg/services/login/loginservice/loginservice_mock.go +++ b/pkg/services/login/loginservice/loginservice_mock.go @@ -3,7 +3,6 @@ package loginservice import ( "context" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" ) @@ -11,11 +10,11 @@ import ( type LoginServiceMock struct { login.Service ExpectedUser *user.User - ExpectedUserFunc func(cmd *models.UpsertUserCommand) *user.User + ExpectedUserFunc func(cmd *login.UpsertUserCommand) *user.User ExpectedError error } -func (s LoginServiceMock) UpsertUser(ctx context.Context, cmd *models.UpsertUserCommand) error { +func (s LoginServiceMock) UpsertUser(ctx context.Context, cmd *login.UpsertUserCommand) error { if s.ExpectedUserFunc != nil { cmd.Result = s.ExpectedUserFunc(cmd) return s.ExpectedError diff --git a/pkg/services/login/loginservice/loginservice_test.go b/pkg/services/login/loginservice/loginservice_test.go index c7d5a4762bc..626c3f519b6 100644 --- a/pkg/services/login/loginservice/loginservice_test.go +++ b/pkg/services/login/loginservice/loginservice_test.go @@ -8,7 +8,9 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" - "github.com/grafana/grafana/pkg/models" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/services/accesscontrol/actest" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/logintest" @@ -17,8 +19,6 @@ import ( "github.com/grafana/grafana/pkg/services/quota/quotatest" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user/usertest" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func Test_syncOrgRoles_doesNotBreakWhenTryingToRemoveLastOrgAdmin(t *testing.T) { @@ -65,14 +65,14 @@ func Test_syncOrgRoles_whenTryingToRemoveLastOrgLogsError(t *testing.T) { func Test_teamSync(t *testing.T) { authInfoMock := &logintest.AuthInfoServiceFake{} - login := Implementation{ + loginsvc := Implementation{ QuotaService: quotatest.New(false, nil), AuthInfoService: authInfoMock, } email := "test_user@example.org" - upsertCmd := &models.UpsertUserCommand{ExternalUser: &models.ExternalUserInfo{Email: email}, - UserLookupParams: models.UserLookupParams{Email: &email}} + upsertCmd := &login.UpsertUserCommand{ExternalUser: &login.ExternalUserInfo{Email: email}, + UserLookupParams: login.UserLookupParams{Email: &email}} expectedUser := &user.User{ ID: 1, Email: email, @@ -82,22 +82,22 @@ func Test_teamSync(t *testing.T) { authInfoMock.ExpectedUser = expectedUser var actualUser *user.User - var actualExternalUser *models.ExternalUserInfo + var actualExternalUser *login.ExternalUserInfo t.Run("login.TeamSync should not be called when nil", func(t *testing.T) { - err := login.UpsertUser(context.Background(), upsertCmd) + err := loginsvc.UpsertUser(context.Background(), upsertCmd) require.Nil(t, err) assert.Nil(t, actualUser) assert.Nil(t, actualExternalUser) t.Run("login.TeamSync should be called when not nil", func(t *testing.T) { - teamSyncFunc := func(user *user.User, externalUser *models.ExternalUserInfo) error { + teamSyncFunc := func(user *user.User, externalUser *login.ExternalUserInfo) error { actualUser = user actualExternalUser = externalUser return nil } - login.TeamSync = teamSyncFunc - err := login.UpsertUser(context.Background(), upsertCmd) + loginsvc.TeamSync = teamSyncFunc + err := loginsvc.UpsertUser(context.Background(), upsertCmd) require.Nil(t, err) assert.Equal(t, actualUser, expectedUser) assert.Equal(t, actualExternalUser, upsertCmd.ExternalUser) @@ -105,33 +105,33 @@ func Test_teamSync(t *testing.T) { t.Run("login.TeamSync should not be called when not nil and skipTeamSync is set for externalUserInfo", func(t *testing.T) { var actualUser *user.User - var actualExternalUser *models.ExternalUserInfo - upsertCmdSkipTeamSync := &models.UpsertUserCommand{ - ExternalUser: &models.ExternalUserInfo{ + var actualExternalUser *login.ExternalUserInfo + upsertCmdSkipTeamSync := &login.UpsertUserCommand{ + ExternalUser: &login.ExternalUserInfo{ Email: email, // sending in ExternalUserInfo with SkipTeamSync yields no team sync SkipTeamSync: true, }, - UserLookupParams: models.UserLookupParams{Email: &email}, + UserLookupParams: login.UserLookupParams{Email: &email}, } - teamSyncFunc := func(user *user.User, externalUser *models.ExternalUserInfo) error { + teamSyncFunc := func(user *user.User, externalUser *login.ExternalUserInfo) error { actualUser = user actualExternalUser = externalUser return nil } - login.TeamSync = teamSyncFunc - err := login.UpsertUser(context.Background(), upsertCmdSkipTeamSync) + loginsvc.TeamSync = teamSyncFunc + err := loginsvc.UpsertUser(context.Background(), upsertCmdSkipTeamSync) require.Nil(t, err) assert.Nil(t, actualUser) assert.Nil(t, actualExternalUser) }) t.Run("login.TeamSync should propagate its errors to the caller", func(t *testing.T) { - teamSyncFunc := func(user *user.User, externalUser *models.ExternalUserInfo) error { + teamSyncFunc := func(user *user.User, externalUser *login.ExternalUserInfo) error { return errors.New("teamsync test error") } - login.TeamSync = teamSyncFunc - err := login.UpsertUser(context.Background(), upsertCmd) + loginsvc.TeamSync = teamSyncFunc + err := loginsvc.UpsertUser(context.Background(), upsertCmd) require.Error(t, err) }) }) @@ -166,8 +166,8 @@ func createUserOrgDTO() []*org.UserOrgDTO { return users } -func createSimpleExternalUser() models.ExternalUserInfo { - externalUser := models.ExternalUserInfo{ +func createSimpleExternalUser() login.ExternalUserInfo { + externalUser := login.ExternalUserInfo{ AuthModule: login.LDAPAuthModule, OrgRoles: map[int64]org.RoleType{ 1: org.RoleViewer, diff --git a/pkg/services/login/logintest/logintest.go b/pkg/services/login/logintest/logintest.go index 1ca3d532ca9..0c9c2b82944 100644 --- a/pkg/services/login/logintest/logintest.go +++ b/pkg/services/login/logintest/logintest.go @@ -3,14 +3,13 @@ package logintest import ( "context" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" ) type LoginServiceFake struct{} -func (l *LoginServiceFake) UpsertUser(ctx context.Context, cmd *models.UpsertUserCommand) error { +func (l *LoginServiceFake) UpsertUser(ctx context.Context, cmd *login.UpsertUserCommand) error { return nil } func (l *LoginServiceFake) DisableExternalUser(ctx context.Context, username string) error { @@ -21,17 +20,17 @@ func (l *LoginServiceFake) SetTeamSyncFunc(login.TeamSyncFunc) {} type AuthInfoServiceFake struct { login.AuthInfoService LatestUserID int64 - ExpectedUserAuth *models.UserAuth + ExpectedUserAuth *login.UserAuth ExpectedUser *user.User - ExpectedExternalUser *models.ExternalUserInfo + ExpectedExternalUser *login.ExternalUserInfo ExpectedError error ExpectedLabels map[int64]string - SetAuthInfoFn func(ctx context.Context, cmd *models.SetAuthInfoCommand) error - UpdateAuthInfoFn func(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error + SetAuthInfoFn func(ctx context.Context, cmd *login.SetAuthInfoCommand) error + UpdateAuthInfoFn func(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error } -func (a *AuthInfoServiceFake) LookupAndUpdate(ctx context.Context, query *models.GetUserByAuthInfoQuery) (*user.User, error) { +func (a *AuthInfoServiceFake) LookupAndUpdate(ctx context.Context, query *login.GetUserByAuthInfoQuery) (*user.User, error) { if query.UserLookupParams.UserID != nil { a.LatestUserID = *query.UserLookupParams.UserID } else { @@ -40,17 +39,17 @@ func (a *AuthInfoServiceFake) LookupAndUpdate(ctx context.Context, query *models return a.ExpectedUser, a.ExpectedError } -func (a *AuthInfoServiceFake) GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error { +func (a *AuthInfoServiceFake) GetAuthInfo(ctx context.Context, query *login.GetAuthInfoQuery) error { a.LatestUserID = query.UserId query.Result = a.ExpectedUserAuth return a.ExpectedError } -func (a *AuthInfoServiceFake) GetUserLabels(ctx context.Context, query models.GetUserLabelsQuery) (map[int64]string, error) { +func (a *AuthInfoServiceFake) GetUserLabels(ctx context.Context, query login.GetUserLabelsQuery) (map[int64]string, error) { return a.ExpectedLabels, a.ExpectedError } -func (a *AuthInfoServiceFake) SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error { +func (a *AuthInfoServiceFake) SetAuthInfo(ctx context.Context, cmd *login.SetAuthInfoCommand) error { if a.SetAuthInfoFn != nil { return a.SetAuthInfoFn(ctx, cmd) } @@ -58,7 +57,7 @@ func (a *AuthInfoServiceFake) SetAuthInfo(ctx context.Context, cmd *models.SetAu return a.ExpectedError } -func (a *AuthInfoServiceFake) UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error { +func (a *AuthInfoServiceFake) UpdateAuthInfo(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error { if a.UpdateAuthInfoFn != nil { return a.UpdateAuthInfoFn(ctx, cmd) } @@ -66,7 +65,7 @@ func (a *AuthInfoServiceFake) UpdateAuthInfo(ctx context.Context, cmd *models.Up return a.ExpectedError } -func (a *AuthInfoServiceFake) GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error { +func (a *AuthInfoServiceFake) GetExternalUserInfoByLogin(ctx context.Context, query *login.GetExternalUserInfoByLoginQuery) error { query.Result = a.ExpectedExternalUser return a.ExpectedError } @@ -80,7 +79,7 @@ type AuthenticatorFake struct { ExpectedError error } -func (a *AuthenticatorFake) AuthenticateUser(c context.Context, query *models.LoginUserQuery) error { +func (a *AuthenticatorFake) AuthenticateUser(c context.Context, query *login.LoginUserQuery) error { query.User = a.ExpectedUser return a.ExpectedError } diff --git a/pkg/services/login/model.go b/pkg/services/login/model.go index a69b7d9fcba..60a3526872b 100644 --- a/pkg/services/login/model.go +++ b/pkg/services/login/model.go @@ -1,10 +1,17 @@ package login import ( + "fmt" "sync" "time" "github.com/prometheus/client_golang/prometheus" + "golang.org/x/oauth2" + + contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + "github.com/grafana/grafana/pkg/services/org" + "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/setting" ) type LoginStats struct { @@ -30,3 +37,122 @@ var ( Once sync.Once Initialised bool = false ) + +type UserAuth struct { + Id int64 + UserId int64 + AuthModule string + AuthId string + Created time.Time + OAuthAccessToken string + OAuthRefreshToken string + OAuthIdToken string + OAuthTokenType string + OAuthExpiry time.Time +} + +type ExternalUserInfo struct { + OAuthToken *oauth2.Token + AuthModule string + AuthId string + UserId int64 + Email string + Login string + Name string + Groups []string + OrgRoles map[int64]org.RoleType + IsGrafanaAdmin *bool // This is a pointer to know if we should sync this or not (nil = ignore sync) + IsDisabled bool + SkipTeamSync bool +} + +func (e *ExternalUserInfo) String() string { + return fmt.Sprintf("%+v", *e) +} + +type LoginInfo struct { + AuthModule string + User *user.User + ExternalUser ExternalUserInfo + LoginUsername string + HTTPStatus int + Error error +} + +// RequestURIKey is used as key to save request URI in contexts +// (used for the Enterprise auditing feature) +type RequestURIKey struct{} + +// --------------------- +// COMMANDS + +type UpsertUserCommand struct { + ReqContext *contextmodel.ReqContext + ExternalUser *ExternalUserInfo + UserLookupParams + SignupAllowed bool + + Result *user.User +} + +type SetAuthInfoCommand struct { + AuthModule string + AuthId string + UserId int64 + OAuthToken *oauth2.Token +} + +type UpdateAuthInfoCommand struct { + AuthModule string + AuthId string + UserId int64 + OAuthToken *oauth2.Token +} + +type DeleteAuthInfoCommand struct { + UserAuth *UserAuth +} + +// ---------------------- +// QUERIES + +type LoginUserQuery struct { + ReqContext *contextmodel.ReqContext + Username string + Password string + User *user.User + IpAddress string + AuthModule string + Cfg *setting.Cfg +} + +type GetUserByAuthInfoQuery struct { + AuthModule string + AuthId string + UserLookupParams +} + +type UserLookupParams struct { + // Describes lookup order as well + UserID *int64 // if set, will try to find the user by id + Email *string // if set, will try to find the user by email + Login *string // if set, will try to find the user by login +} + +type GetExternalUserInfoByLoginQuery struct { + LoginOrEmail string + + Result *ExternalUserInfo +} + +type GetAuthInfoQuery struct { + UserId int64 + AuthModule string + AuthId string + + Result *UserAuth +} + +type GetUserLabelsQuery struct { + UserIDs []int64 +} diff --git a/pkg/services/login/userprotection.go b/pkg/services/login/userprotection.go index f77b6401244..4f94d6a030b 100644 --- a/pkg/services/login/userprotection.go +++ b/pkg/services/login/userprotection.go @@ -3,7 +3,6 @@ package login import ( "context" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/user" ) @@ -12,13 +11,13 @@ type UserProtectionService interface { } type Store interface { - GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error - GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error - GetUserLabels(ctx context.Context, query models.GetUserLabelsQuery) (map[int64]string, error) - SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error - UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error - UpdateAuthInfoDate(ctx context.Context, authInfo *models.UserAuth) error - DeleteAuthInfo(ctx context.Context, cmd *models.DeleteAuthInfoCommand) error + GetExternalUserInfoByLogin(ctx context.Context, query *GetExternalUserInfoByLoginQuery) error + GetAuthInfo(ctx context.Context, query *GetAuthInfoQuery) error + GetUserLabels(ctx context.Context, query GetUserLabelsQuery) (map[int64]string, error) + SetAuthInfo(ctx context.Context, cmd *SetAuthInfoCommand) error + UpdateAuthInfo(ctx context.Context, cmd *UpdateAuthInfoCommand) error + UpdateAuthInfoDate(ctx context.Context, authInfo *UserAuth) error + DeleteAuthInfo(ctx context.Context, cmd *DeleteAuthInfoCommand) error GetUserById(ctx context.Context, id int64) (*user.User, error) GetUserByLogin(ctx context.Context, login string) (*user.User, error) GetUserByEmail(ctx context.Context, email string) (*user.User, error) diff --git a/pkg/services/multildap/multidap_mock.go b/pkg/services/multildap/multidap_mock.go index d59ca876f00..31b2557d0a3 100644 --- a/pkg/services/multildap/multidap_mock.go +++ b/pkg/services/multildap/multidap_mock.go @@ -1,8 +1,8 @@ package multildap import ( - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/ldap" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" ) @@ -16,25 +16,25 @@ type MultiLDAPmock struct { ExpectedErr error } -func (m *MultiLDAPmock) Login(query *models.LoginUserQuery) ( - *models.ExternalUserInfo, error, +func (m *MultiLDAPmock) Login(query *login.LoginUserQuery) ( + *login.ExternalUserInfo, error, ) { m.LoginCalled = true query.User = m.UserInfo query.AuthModule = m.AuthModule - result := &models.ExternalUserInfo{ + result := &login.ExternalUserInfo{ UserId: m.ID, } return result, m.ExpectedErr } -func (m *MultiLDAPmock) User(login string) ( - *models.ExternalUserInfo, +func (m *MultiLDAPmock) User(loginstr string) ( + *login.ExternalUserInfo, ldap.ServerConfig, error, ) { m.UserCalled = true - result := &models.ExternalUserInfo{ + result := &login.ExternalUserInfo{ UserId: m.ID, } return result, ldap.ServerConfig{}, nil diff --git a/pkg/services/multildap/multildap.go b/pkg/services/multildap/multildap.go index b9ea8bd9ef3..25ec86fde72 100644 --- a/pkg/services/multildap/multildap.go +++ b/pkg/services/multildap/multildap.go @@ -4,8 +4,8 @@ import ( "errors" "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/ldap" + "github.com/grafana/grafana/pkg/services/login" ) // logger to log @@ -43,16 +43,16 @@ type ServerStatus struct { // IMultiLDAP is interface for MultiLDAP type IMultiLDAP interface { Ping() ([]*ServerStatus, error) - Login(query *models.LoginUserQuery) ( - *models.ExternalUserInfo, error, + Login(query *login.LoginUserQuery) ( + *login.ExternalUserInfo, error, ) Users(logins []string) ( - []*models.ExternalUserInfo, error, + []*login.ExternalUserInfo, error, ) User(login string) ( - *models.ExternalUserInfo, ldap.ServerConfig, error, + *login.ExternalUserInfo, ldap.ServerConfig, error, ) } @@ -99,8 +99,8 @@ func (multiples *MultiLDAP) Ping() ([]*ServerStatus, error) { } // Login tries to log in the user in multiples LDAP -func (multiples *MultiLDAP) Login(query *models.LoginUserQuery) ( - *models.ExternalUserInfo, error, +func (multiples *MultiLDAP) Login(query *login.LoginUserQuery) ( + *login.ExternalUserInfo, error, ) { if len(multiples.configs) == 0 { return nil, ErrNoLDAPServers @@ -157,7 +157,7 @@ func (multiples *MultiLDAP) Login(query *models.LoginUserQuery) ( // User attempts to find an user by login/username by searching into all of the configured LDAP servers. Then, if the user is found it returns the user alongisde the server it was found. func (multiples *MultiLDAP) User(login string) ( - *models.ExternalUserInfo, + *login.ExternalUserInfo, ldap.ServerConfig, error, ) { @@ -200,10 +200,10 @@ func (multiples *MultiLDAP) User(login string) ( // Users gets users from multiple LDAP servers func (multiples *MultiLDAP) Users(logins []string) ( - []*models.ExternalUserInfo, + []*login.ExternalUserInfo, error, ) { - var result []*models.ExternalUserInfo + var result []*login.ExternalUserInfo if len(multiples.configs) == 0 { return nil, ErrNoLDAPServers diff --git a/pkg/services/multildap/multildap_test.go b/pkg/services/multildap/multildap_test.go index cbf33532b2d..8d61448cdde 100644 --- a/pkg/services/multildap/multildap_test.go +++ b/pkg/services/multildap/multildap_test.go @@ -4,8 +4,8 @@ import ( "errors" "testing" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/ldap" + "github.com/grafana/grafana/pkg/services/login" "github.com/stretchr/testify/require" @@ -71,7 +71,7 @@ func TestMultiLDAP(t *testing.T) { setup() multi := New([]*ldap.ServerConfig{}) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Error(t, err) require.Equal(t, ErrNoLDAPServers, err) @@ -89,7 +89,7 @@ func TestMultiLDAP(t *testing.T) { {}, {}, }) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Error(t, err) require.Equal(t, expected, err) @@ -104,7 +104,7 @@ func TestMultiLDAP(t *testing.T) { multi := New([]*ldap.ServerConfig{ {}, {}, }) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Equal(t, 2, mock.dialCalledTimes) require.Equal(t, 2, mock.loginCalledTimes) @@ -118,14 +118,14 @@ func TestMultiLDAP(t *testing.T) { t.Run("Should get login result", func(t *testing.T) { mock := setup() - mock.loginReturn = &models.ExternalUserInfo{ + mock.loginReturn = &login.ExternalUserInfo{ Login: "killa", } multi := New([]*ldap.ServerConfig{ {}, {}, }) - result, err := multi.Login(&models.LoginUserQuery{}) + result, err := multi.Login(&login.LoginUserQuery{}) require.Equal(t, 1, mock.dialCalledTimes) require.Equal(t, 1, mock.loginCalledTimes) @@ -145,7 +145,7 @@ func TestMultiLDAP(t *testing.T) { multi := New([]*ldap.ServerConfig{ {}, {}, }) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Equal(t, 2, mock.dialCalledTimes) require.Equal(t, 2, mock.loginCalledTimes) @@ -164,7 +164,7 @@ func TestMultiLDAP(t *testing.T) { multi := New([]*ldap.ServerConfig{ {}, {}, }) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Equal(t, 2, mock.dialCalledTimes) require.Equal(t, 2, mock.loginCalledTimes) @@ -184,7 +184,7 @@ func TestMultiLDAP(t *testing.T) { multi := New([]*ldap.ServerConfig{ {}, {}, }) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Equal(t, 2, mock.dialCalledTimes) @@ -202,7 +202,7 @@ func TestMultiLDAP(t *testing.T) { multi := New([]*ldap.ServerConfig{ {}, {}, }) - _, err := multi.Login(&models.LoginUserQuery{}) + _, err := multi.Login(&login.LoginUserQuery{}) require.Equal(t, 1, mock.dialCalledTimes) require.Equal(t, 1, mock.loginCalledTimes) @@ -285,7 +285,7 @@ func TestMultiLDAP(t *testing.T) { t.Run("Should get only one user", func(t *testing.T) { mock := setup() - mock.usersFirstReturn = []*models.ExternalUserInfo{ + mock.usersFirstReturn = []*login.ExternalUserInfo{ { Login: "one", }, @@ -415,7 +415,7 @@ func TestMultiLDAP(t *testing.T) { t.Run("Should get users", func(t *testing.T) { mock := setup() - mock.usersFirstReturn = []*models.ExternalUserInfo{ + mock.usersFirstReturn = []*login.ExternalUserInfo{ { Login: "one", }, @@ -425,7 +425,7 @@ func TestMultiLDAP(t *testing.T) { }, } - mock.usersRestReturn = []*models.ExternalUserInfo{ + mock.usersRestReturn = []*login.ExternalUserInfo{ { Login: "three", }, @@ -461,23 +461,23 @@ type mockLDAP struct { dialErrReturn error loginErrReturn error - loginReturn *models.ExternalUserInfo + loginReturn *login.ExternalUserInfo bindErrReturn error usersErrReturn error - usersFirstReturn []*models.ExternalUserInfo - usersRestReturn []*models.ExternalUserInfo + usersFirstReturn []*login.ExternalUserInfo + usersRestReturn []*login.ExternalUserInfo } // Login test fn -func (mock *mockLDAP) Login(*models.LoginUserQuery) (*models.ExternalUserInfo, error) { +func (mock *mockLDAP) Login(*login.LoginUserQuery) (*login.ExternalUserInfo, error) { mock.loginCalledTimes++ return mock.loginReturn, mock.loginErrReturn } // Users test fn -func (mock *mockLDAP) Users([]string) ([]*models.ExternalUserInfo, error) { +func (mock *mockLDAP) Users([]string) ([]*login.ExternalUserInfo, error) { mock.usersCalledTimes++ if mock.usersCalledTimes == 1 { diff --git a/pkg/services/oauthtoken/oauth_token.go b/pkg/services/oauthtoken/oauth_token.go index f2fc1118ac5..c773abdab2c 100644 --- a/pkg/services/oauthtoken/oauth_token.go +++ b/pkg/services/oauthtoken/oauth_token.go @@ -12,7 +12,6 @@ import ( "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/login/social" - "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/user" @@ -38,9 +37,9 @@ type Service struct { type OAuthTokenService interface { GetCurrentOAuthToken(context.Context, *user.SignedInUser) *oauth2.Token IsOAuthPassThruEnabled(*datasources.DataSource) bool - HasOAuthEntry(context.Context, *user.SignedInUser) (*models.UserAuth, bool, error) - TryTokenRefresh(context.Context, *models.UserAuth) error - InvalidateOAuthTokens(context.Context, *models.UserAuth) error + HasOAuthEntry(context.Context, *user.SignedInUser) (*login.UserAuth, bool, error) + TryTokenRefresh(context.Context, *login.UserAuth) error + InvalidateOAuthTokens(context.Context, *login.UserAuth) error } func ProvideService(socialService social.Service, authInfoService login.AuthInfoService, cfg *setting.Cfg) *Service { @@ -59,7 +58,7 @@ func (o *Service) GetCurrentOAuthToken(ctx context.Context, usr *user.SignedInUs return nil } - authInfoQuery := &models.GetAuthInfoQuery{UserId: usr.UserID} + authInfoQuery := &login.GetAuthInfoQuery{UserId: usr.UserID} if err := o.AuthInfoService.GetAuthInfo(ctx, authInfoQuery); err != nil { if errors.Is(err, user.ErrUserNotFound) { // Not necessarily an error. User may be logged in another way. @@ -88,13 +87,13 @@ func (o *Service) IsOAuthPassThruEnabled(ds *datasources.DataSource) bool { } // HasOAuthEntry returns true and the UserAuth object when OAuth info exists for the specified User -func (o *Service) HasOAuthEntry(ctx context.Context, usr *user.SignedInUser) (*models.UserAuth, bool, error) { +func (o *Service) HasOAuthEntry(ctx context.Context, usr *user.SignedInUser) (*login.UserAuth, bool, error) { if usr == nil { // No user, therefore no token return nil, false, nil } - authInfoQuery := &models.GetAuthInfoQuery{UserId: usr.UserID} + authInfoQuery := &login.GetAuthInfoQuery{UserId: usr.UserID} err := o.AuthInfoService.GetAuthInfo(ctx, authInfoQuery) if err != nil { if errors.Is(err, user.ErrUserNotFound) { @@ -112,7 +111,7 @@ func (o *Service) HasOAuthEntry(ctx context.Context, usr *user.SignedInUser) (*m // TryTokenRefresh returns an error in case the OAuth token refresh was unsuccessful // It uses a singleflight.Group to prevent getting the Refresh Token multiple times for a given User -func (o *Service) TryTokenRefresh(ctx context.Context, usr *models.UserAuth) error { +func (o *Service) TryTokenRefresh(ctx context.Context, usr *login.UserAuth) error { lockKey := fmt.Sprintf("oauth-refresh-token-%d", usr.UserId) _, err, _ := o.singleFlightGroup.Do(lockKey, func() (interface{}, error) { logger.Debug("singleflight request for getting a new access token", "key", lockKey) @@ -122,7 +121,7 @@ func (o *Service) TryTokenRefresh(ctx context.Context, usr *models.UserAuth) err return err } -func buildOAuthTokenFromAuthInfo(authInfo *models.UserAuth) *oauth2.Token { +func buildOAuthTokenFromAuthInfo(authInfo *login.UserAuth) *oauth2.Token { token := &oauth2.Token{ AccessToken: authInfo.OAuthAccessToken, Expiry: authInfo.OAuthExpiry, @@ -137,7 +136,7 @@ func buildOAuthTokenFromAuthInfo(authInfo *models.UserAuth) *oauth2.Token { return token } -func checkOAuthRefreshToken(authInfo *models.UserAuth) error { +func checkOAuthRefreshToken(authInfo *login.UserAuth) error { if !strings.Contains(authInfo.AuthModule, "oauth") { logger.Warn("the specified user's auth provider is not oauth", "authmodule", authInfo.AuthModule, "userid", authInfo.UserId) @@ -154,8 +153,8 @@ func checkOAuthRefreshToken(authInfo *models.UserAuth) error { } // InvalidateOAuthTokens invalidates the OAuth tokens (access_token, refresh_token) and sets the Expiry to default/zero -func (o *Service) InvalidateOAuthTokens(ctx context.Context, usr *models.UserAuth) error { - return o.AuthInfoService.UpdateAuthInfo(ctx, &models.UpdateAuthInfoCommand{ +func (o *Service) InvalidateOAuthTokens(ctx context.Context, usr *login.UserAuth) error { + return o.AuthInfoService.UpdateAuthInfo(ctx, &login.UpdateAuthInfoCommand{ UserId: usr.UserId, AuthModule: usr.AuthModule, AuthId: usr.AuthId, @@ -167,7 +166,7 @@ func (o *Service) InvalidateOAuthTokens(ctx context.Context, usr *models.UserAut }) } -func (o *Service) tryGetOrRefreshAccessToken(ctx context.Context, usr *models.UserAuth) (*oauth2.Token, error) { +func (o *Service) tryGetOrRefreshAccessToken(ctx context.Context, usr *login.UserAuth) (*oauth2.Token, error) { if err := checkOAuthRefreshToken(usr); err != nil { return nil, err } @@ -198,7 +197,7 @@ func (o *Service) tryGetOrRefreshAccessToken(ctx context.Context, usr *models.Us // If the tokens are not the same, update the entry in the DB if !tokensEq(persistedToken, token) { - updateAuthCommand := &models.UpdateAuthInfoCommand{ + updateAuthCommand := &login.UpdateAuthInfoCommand{ UserId: usr.UserId, AuthModule: usr.AuthModule, AuthId: usr.AuthId, diff --git a/pkg/services/oauthtoken/oauth_token_test.go b/pkg/services/oauthtoken/oauth_token_test.go index 063de3ce3f2..1392d1e229e 100644 --- a/pkg/services/oauthtoken/oauth_token_test.go +++ b/pkg/services/oauthtoken/oauth_token_test.go @@ -8,29 +8,29 @@ import ( "testing" "time" - "github.com/grafana/grafana/pkg/infra/usagestats" - "github.com/grafana/grafana/pkg/login/social" - "github.com/grafana/grafana/pkg/models" - "github.com/grafana/grafana/pkg/services/login" - "github.com/grafana/grafana/pkg/services/login/authinfoservice" - "github.com/grafana/grafana/pkg/services/user" - "github.com/grafana/grafana/pkg/setting" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "golang.org/x/oauth2" "golang.org/x/sync/singleflight" + + "github.com/grafana/grafana/pkg/infra/usagestats" + "github.com/grafana/grafana/pkg/login/social" + "github.com/grafana/grafana/pkg/services/login" + "github.com/grafana/grafana/pkg/services/login/authinfoservice" + "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/setting" ) func TestService_HasOAuthEntry(t *testing.T) { testCases := []struct { name string user *user.SignedInUser - want *models.UserAuth + want *login.UserAuth wantExist bool wantErr bool err error getAuthInfoErr error - getAuthInfoUser models.UserAuth + getAuthInfoUser login.UserAuth }{ { name: "returns false without an error in case user is nil", @@ -61,15 +61,15 @@ func TestService_HasOAuthEntry(t *testing.T) { want: nil, wantExist: false, wantErr: false, - getAuthInfoUser: models.UserAuth{AuthModule: "auth_saml"}, + getAuthInfoUser: login.UserAuth{AuthModule: "auth_saml"}, }, { name: "returns true when the auth entry is found", user: &user.SignedInUser{}, - want: &models.UserAuth{AuthModule: "oauth_generic_oauth"}, + want: &login.UserAuth{AuthModule: "oauth_generic_oauth"}, wantExist: true, wantErr: false, - getAuthInfoUser: models.UserAuth{AuthModule: "oauth_generic_oauth"}, + getAuthInfoUser: login.UserAuth{AuthModule: "oauth_generic_oauth"}, }, } for _, tc := range testCases { @@ -101,7 +101,7 @@ func TestService_TryTokenRefresh_ValidToken(t *testing.T) { Expiry: time.Now(), TokenType: "Bearer", } - usr := &models.UserAuth{ + usr := &login.UserAuth{ AuthModule: "oauth_generic_oauth", OAuthAccessToken: token.AccessToken, OAuthRefreshToken: token.RefreshToken, @@ -117,7 +117,7 @@ func TestService_TryTokenRefresh_ValidToken(t *testing.T) { assert.Nil(t, err) socialConnector.AssertNumberOfCalls(t, "TokenSource", 1) - authInfoQuery := &models.GetAuthInfoQuery{} + authInfoQuery := &login.GetAuthInfoQuery{} err = srv.AuthInfoService.GetAuthInfo(ctx, authInfoQuery) assert.Nil(t, err) @@ -139,7 +139,7 @@ func TestService_TryTokenRefresh_NoRefreshToken(t *testing.T) { Expiry: time.Now().Add(-time.Hour), TokenType: "Bearer", } - usr := &models.UserAuth{ + usr := &login.UserAuth{ AuthModule: "oauth_generic_oauth", OAuthAccessToken: token.AccessToken, OAuthRefreshToken: token.RefreshToken, @@ -174,7 +174,7 @@ func TestService_TryTokenRefresh_ExpiredToken(t *testing.T) { TokenType: "Bearer", } - usr := &models.UserAuth{ + usr := &login.UserAuth{ AuthModule: "oauth_generic_oauth", OAuthAccessToken: token.AccessToken, OAuthRefreshToken: token.RefreshToken, @@ -191,7 +191,7 @@ func TestService_TryTokenRefresh_ExpiredToken(t *testing.T) { assert.Nil(t, err) socialConnector.AssertNumberOfCalls(t, "TokenSource", 1) - authInfoQuery := &models.GetAuthInfoQuery{} + authInfoQuery := &login.GetAuthInfoQuery{} err = srv.AuthInfoService.GetAuthInfo(ctx, authInfoQuery) assert.Nil(t, err) @@ -207,7 +207,7 @@ func TestService_TryTokenRefresh_DifferentAuthModuleForUser(t *testing.T) { srv, _, socialConnector := setupOAuthTokenService(t) ctx := context.Background() token := &oauth2.Token{} - usr := &models.UserAuth{ + usr := &login.UserAuth{ AuthModule: "auth.saml", } @@ -307,30 +307,30 @@ type FakeAuthInfoStore struct { login.Store ExpectedError error ExpectedUser *user.User - ExpectedOAuth *models.UserAuth + ExpectedOAuth *login.UserAuth ExpectedDuplicateUserEntries int ExpectedHasDuplicateUserEntries int ExpectedLoginStats login.LoginStats } -func (f *FakeAuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *models.GetExternalUserInfoByLoginQuery) error { +func (f *FakeAuthInfoStore) GetExternalUserInfoByLogin(ctx context.Context, query *login.GetExternalUserInfoByLoginQuery) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) GetAuthInfo(ctx context.Context, query *models.GetAuthInfoQuery) error { +func (f *FakeAuthInfoStore) GetAuthInfo(ctx context.Context, query *login.GetAuthInfoQuery) error { query.Result = f.ExpectedOAuth return f.ExpectedError } -func (f *FakeAuthInfoStore) SetAuthInfo(ctx context.Context, cmd *models.SetAuthInfoCommand) error { +func (f *FakeAuthInfoStore) SetAuthInfo(ctx context.Context, cmd *login.SetAuthInfoCommand) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *models.UserAuth) error { +func (f *FakeAuthInfoStore) UpdateAuthInfoDate(ctx context.Context, authInfo *login.UserAuth) error { return f.ExpectedError } -func (f *FakeAuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error { +func (f *FakeAuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *login.UpdateAuthInfoCommand) error { f.ExpectedOAuth.OAuthAccessToken = cmd.OAuthToken.AccessToken f.ExpectedOAuth.OAuthExpiry = cmd.OAuthToken.Expiry f.ExpectedOAuth.OAuthTokenType = cmd.OAuthToken.TokenType @@ -338,7 +338,7 @@ func (f *FakeAuthInfoStore) UpdateAuthInfo(ctx context.Context, cmd *models.Upda return f.ExpectedError } -func (f *FakeAuthInfoStore) DeleteAuthInfo(ctx context.Context, cmd *models.DeleteAuthInfoCommand) error { +func (f *FakeAuthInfoStore) DeleteAuthInfo(ctx context.Context, cmd *login.DeleteAuthInfoCommand) error { return f.ExpectedError } diff --git a/pkg/services/oauthtoken/oauthtokentest/mock.go b/pkg/services/oauthtoken/oauthtokentest/mock.go index 95bc1ccd204..e1af309faa3 100644 --- a/pkg/services/oauthtoken/oauthtokentest/mock.go +++ b/pkg/services/oauthtoken/oauthtokentest/mock.go @@ -3,18 +3,19 @@ package oauthtokentest import ( "context" - "github.com/grafana/grafana/pkg/models" - "github.com/grafana/grafana/pkg/services/datasources" - "github.com/grafana/grafana/pkg/services/user" "golang.org/x/oauth2" + + "github.com/grafana/grafana/pkg/services/datasources" + "github.com/grafana/grafana/pkg/services/login" + "github.com/grafana/grafana/pkg/services/user" ) type MockOauthTokenService struct { GetCurrentOauthTokenFunc func(ctx context.Context, usr *user.SignedInUser) *oauth2.Token IsOAuthPassThruEnabledFunc func(ds *datasources.DataSource) bool - HasOAuthEntryFunc func(ctx context.Context, usr *user.SignedInUser) (*models.UserAuth, bool, error) - InvalidateOAuthTokensFunc func(ctx context.Context, usr *models.UserAuth) error - TryTokenRefreshFunc func(ctx context.Context, usr *models.UserAuth) error + HasOAuthEntryFunc func(ctx context.Context, usr *user.SignedInUser) (*login.UserAuth, bool, error) + InvalidateOAuthTokensFunc func(ctx context.Context, usr *login.UserAuth) error + TryTokenRefreshFunc func(ctx context.Context, usr *login.UserAuth) error } func (m *MockOauthTokenService) GetCurrentOAuthToken(ctx context.Context, usr *user.SignedInUser) *oauth2.Token { @@ -31,21 +32,21 @@ func (m *MockOauthTokenService) IsOAuthPassThruEnabled(ds *datasources.DataSourc return false } -func (m *MockOauthTokenService) HasOAuthEntry(ctx context.Context, usr *user.SignedInUser) (*models.UserAuth, bool, error) { +func (m *MockOauthTokenService) HasOAuthEntry(ctx context.Context, usr *user.SignedInUser) (*login.UserAuth, bool, error) { if m.HasOAuthEntryFunc != nil { return m.HasOAuthEntryFunc(ctx, usr) } return nil, false, nil } -func (m *MockOauthTokenService) InvalidateOAuthTokens(ctx context.Context, usr *models.UserAuth) error { +func (m *MockOauthTokenService) InvalidateOAuthTokens(ctx context.Context, usr *login.UserAuth) error { if m.InvalidateOAuthTokensFunc != nil { return m.InvalidateOAuthTokensFunc(ctx, usr) } return nil } -func (m *MockOauthTokenService) TryTokenRefresh(ctx context.Context, usr *models.UserAuth) error { +func (m *MockOauthTokenService) TryTokenRefresh(ctx context.Context, usr *login.UserAuth) error { if m.TryTokenRefreshFunc != nil { return m.TryTokenRefreshFunc(ctx, usr) } diff --git a/pkg/services/oauthtoken/oauthtokentest/oauthtokentest.go b/pkg/services/oauthtoken/oauthtokentest/oauthtokentest.go index 230b2d7e290..2bb990c8446 100644 --- a/pkg/services/oauthtoken/oauthtokentest/oauthtokentest.go +++ b/pkg/services/oauthtoken/oauthtokentest/oauthtokentest.go @@ -3,11 +3,12 @@ package oauthtokentest import ( "context" - "github.com/grafana/grafana/pkg/models" + "golang.org/x/oauth2" + "github.com/grafana/grafana/pkg/services/datasources" + "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/oauthtoken" "github.com/grafana/grafana/pkg/services/user" - "golang.org/x/oauth2" ) // Service an OAuth token service suitable for tests. @@ -28,14 +29,14 @@ func (s *Service) IsOAuthPassThruEnabled(ds *datasources.DataSource) bool { return oauthtoken.IsOAuthPassThruEnabled(ds) } -func (s *Service) HasOAuthEntry(context.Context, *user.SignedInUser) (*models.UserAuth, bool, error) { +func (s *Service) HasOAuthEntry(context.Context, *user.SignedInUser) (*login.UserAuth, bool, error) { return nil, false, nil } -func (s *Service) TryTokenRefresh(context.Context, *models.UserAuth) error { +func (s *Service) TryTokenRefresh(context.Context, *login.UserAuth) error { return nil } -func (s *Service) InvalidateOAuthTokens(context.Context, *models.UserAuth) error { +func (s *Service) InvalidateOAuthTokens(context.Context, *login.UserAuth) error { return nil }