Chore: Move ReqContext to contexthandler service (#62102)

* Chore: Move ReqContext to contexthandler service

* Rename package to contextmodel

* Generate ngalert files

* Remove unused imports
This commit is contained in:
idafurjes
2023-01-27 08:50:36 +01:00
committed by GitHub
parent 8379a29b53
commit 6c5a573772
180 changed files with 1208 additions and 1182 deletions

View File

@@ -3,9 +3,9 @@ package api
import ( import (
"fmt" "fmt"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
@@ -435,7 +435,7 @@ func (hs *HTTPServer) declareFixedRoles() error {
// Metadata helpers // Metadata helpers
// getAccessControlMetadata returns the accesscontrol metadata associated with a given resource // getAccessControlMetadata returns the accesscontrol metadata associated with a given resource
func (hs *HTTPServer) getAccessControlMetadata(c *models.ReqContext, func (hs *HTTPServer) getAccessControlMetadata(c *contextmodel.ReqContext,
orgID int64, prefix string, resourceID string) ac.Metadata { orgID int64, prefix string, resourceID string) ac.Metadata {
ids := map[string]bool{resourceID: true} ids := map[string]bool{resourceID: true}
return hs.getMultiAccessControlMetadata(c, orgID, prefix, ids)[resourceID] return hs.getMultiAccessControlMetadata(c, orgID, prefix, ids)[resourceID]
@@ -443,7 +443,7 @@ func (hs *HTTPServer) getAccessControlMetadata(c *models.ReqContext,
// getMultiAccessControlMetadata returns the accesscontrol metadata associated with a given set of resources // getMultiAccessControlMetadata returns the accesscontrol metadata associated with a given set of resources
// Context must contain permissions in the given org (see LoadPermissionsMiddleware or AuthorizeInOrgMiddleware) // Context must contain permissions in the given org (see LoadPermissionsMiddleware or AuthorizeInOrgMiddleware)
func (hs *HTTPServer) getMultiAccessControlMetadata(c *models.ReqContext, func (hs *HTTPServer) getMultiAccessControlMetadata(c *contextmodel.ReqContext,
orgID int64, prefix string, resourceIDs map[string]bool) map[string]ac.Metadata { orgID int64, prefix string, resourceIDs map[string]bool) map[string]ac.Metadata {
if hs.AccessControl.IsDisabled() || !c.QueryBool("accesscontrol") { if hs.AccessControl.IsDisabled() || !c.QueryBool("accesscontrol") {
return map[string]ac.Metadata{} return map[string]ac.Metadata{}

View File

@@ -5,8 +5,8 @@ import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/stats" "github.com/grafana/grafana/pkg/services/stats"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -25,7 +25,7 @@ import (
// 200: adminGetSettingsResponse // 200: adminGetSettingsResponse
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
func (hs *HTTPServer) AdminGetSettings(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminGetSettings(c *contextmodel.ReqContext) response.Response {
settings, err := hs.getAuthorizedSettings(c.Req.Context(), c.SignedInUser, hs.SettingsProvider.Current()) settings, err := hs.getAuthorizedSettings(c.Req.Context(), c.SignedInUser, hs.SettingsProvider.Current())
if err != nil { if err != nil {
return response.Error(http.StatusForbidden, "Failed to authorize settings", err) return response.Error(http.StatusForbidden, "Failed to authorize settings", err)
@@ -45,7 +45,7 @@ func (hs *HTTPServer) AdminGetSettings(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminGetStats(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminGetStats(c *contextmodel.ReqContext) response.Response {
statsQuery := stats.GetAdminStatsQuery{} statsQuery := stats.GetAdminStatsQuery{}
if err := hs.statsService.GetAdminStats(c.Req.Context(), &statsQuery); err != nil { if err := hs.statsService.GetAdminStats(c.Req.Context(), &statsQuery); err != nil {

View File

@@ -5,11 +5,11 @@ import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
skv "github.com/grafana/grafana/pkg/services/secrets/kvstore" skv "github.com/grafana/grafana/pkg/services/secrets/kvstore"
) )
func (hs *HTTPServer) AdminRotateDataEncryptionKeys(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminRotateDataEncryptionKeys(c *contextmodel.ReqContext) response.Response {
if err := hs.SecretsService.RotateDataKeys(c.Req.Context()); err != nil { if err := hs.SecretsService.RotateDataKeys(c.Req.Context()); err != nil {
return response.Error(http.StatusInternalServerError, "Failed to rotate data keys", err) return response.Error(http.StatusInternalServerError, "Failed to rotate data keys", err)
} }
@@ -17,7 +17,7 @@ func (hs *HTTPServer) AdminRotateDataEncryptionKeys(c *models.ReqContext) respon
return response.Respond(http.StatusNoContent, "") return response.Respond(http.StatusNoContent, "")
} }
func (hs *HTTPServer) AdminReEncryptEncryptionKeys(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminReEncryptEncryptionKeys(c *contextmodel.ReqContext) response.Response {
if err := hs.SecretsService.ReEncryptDataKeys(c.Req.Context()); err != nil { if err := hs.SecretsService.ReEncryptDataKeys(c.Req.Context()); err != nil {
return response.Error(http.StatusInternalServerError, "Failed to re-encrypt data keys", err) return response.Error(http.StatusInternalServerError, "Failed to re-encrypt data keys", err)
} }
@@ -25,7 +25,7 @@ func (hs *HTTPServer) AdminReEncryptEncryptionKeys(c *models.ReqContext) respons
return response.Respond(http.StatusOK, "Data encryption keys re-encrypted successfully") return response.Respond(http.StatusOK, "Data encryption keys re-encrypted successfully")
} }
func (hs *HTTPServer) AdminReEncryptSecrets(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminReEncryptSecrets(c *contextmodel.ReqContext) response.Response {
success, err := hs.secretsMigrator.ReEncryptSecrets(c.Req.Context()) success, err := hs.secretsMigrator.ReEncryptSecrets(c.Req.Context())
if err != nil { if err != nil {
return response.Error(http.StatusInternalServerError, "Failed to re-encrypt secrets", err) return response.Error(http.StatusInternalServerError, "Failed to re-encrypt secrets", err)
@@ -38,7 +38,7 @@ func (hs *HTTPServer) AdminReEncryptSecrets(c *models.ReqContext) response.Respo
return response.Respond(http.StatusOK, "Secrets re-encrypted successfully") return response.Respond(http.StatusOK, "Secrets re-encrypted successfully")
} }
func (hs *HTTPServer) AdminRollbackSecrets(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminRollbackSecrets(c *contextmodel.ReqContext) response.Response {
success, err := hs.secretsMigrator.RollBackSecrets(c.Req.Context()) success, err := hs.secretsMigrator.RollBackSecrets(c.Req.Context())
if err != nil { if err != nil {
return response.Error(http.StatusInternalServerError, "Failed to rollback secrets", err) return response.Error(http.StatusInternalServerError, "Failed to rollback secrets", err)
@@ -53,7 +53,7 @@ func (hs *HTTPServer) AdminRollbackSecrets(c *models.ReqContext) response.Respon
// To migrate to the plugin, it must be installed and configured // To migrate to the plugin, it must be installed and configured
// so as not to lose access to migrated secrets // so as not to lose access to migrated secrets
func (hs *HTTPServer) AdminMigrateSecretsToPlugin(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminMigrateSecretsToPlugin(c *contextmodel.ReqContext) response.Response {
if skv.EvaluateRemoteSecretsPlugin(c.Req.Context(), hs.secretsPluginManager, hs.Cfg) != nil { if skv.EvaluateRemoteSecretsPlugin(c.Req.Context(), hs.secretsPluginManager, hs.Cfg) != nil {
hs.log.Warn("Received secrets plugin migration request while plugin is not available") hs.log.Warn("Received secrets plugin migration request while plugin is not available")
return response.Respond(http.StatusBadRequest, "Secrets plugin is not available") return response.Respond(http.StatusBadRequest, "Secrets plugin is not available")
@@ -68,7 +68,7 @@ func (hs *HTTPServer) AdminMigrateSecretsToPlugin(c *models.ReqContext) response
// To migrate from the plugin, it must be installed only // To migrate from the plugin, it must be installed only
// as it is possible the user disabled it and then wants to migrate // as it is possible the user disabled it and then wants to migrate
func (hs *HTTPServer) AdminMigrateSecretsFromPlugin(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminMigrateSecretsFromPlugin(c *contextmodel.ReqContext) response.Response {
if hs.secretsPluginManager.SecretsManager(c.Req.Context()) == nil { if hs.secretsPluginManager.SecretsManager(c.Req.Context()) == nil {
hs.log.Warn("Received secrets plugin migration request while plugin is not installed") hs.log.Warn("Received secrets plugin migration request while plugin is not installed")
return response.Respond(http.StatusBadRequest, "Secrets plugin is not installed") return response.Respond(http.StatusBadRequest, "Secrets plugin is not installed")
@@ -81,7 +81,7 @@ func (hs *HTTPServer) AdminMigrateSecretsFromPlugin(c *models.ReqContext) respon
return response.Respond(http.StatusOK, "Secret migration from plugin triggered successfully") return response.Respond(http.StatusOK, "Secret migration from plugin triggered successfully")
} }
func (hs *HTTPServer) AdminDeleteAllSecretsManagerPluginSecrets(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminDeleteAllSecretsManagerPluginSecrets(c *contextmodel.ReqContext) response.Response {
if hs.secretsPluginManager.SecretsManager(c.Req.Context()) == nil { if hs.secretsPluginManager.SecretsManager(c.Req.Context()) == nil {
hs.log.Warn("Received secrets plugin deletion request while plugin is not installed") hs.log.Warn("Received secrets plugin deletion request while plugin is not installed")
return response.Respond(http.StatusBadRequest, "Secrets plugin is not installed") return response.Respond(http.StatusBadRequest, "Secrets plugin is not installed")

View File

@@ -5,7 +5,7 @@ import (
"errors" "errors"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
) )
// swagger:route POST /admin/provisioning/dashboards/reload admin_provisioning adminProvisioningReloadDashboards // swagger:route POST /admin/provisioning/dashboards/reload admin_provisioning adminProvisioningReloadDashboards
@@ -23,7 +23,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminProvisioningReloadDashboards(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminProvisioningReloadDashboards(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionDashboards(c.Req.Context()) err := hs.ProvisioningService.ProvisionDashboards(c.Req.Context())
if err != nil && !errors.Is(err, context.Canceled) { if err != nil && !errors.Is(err, context.Canceled) {
return response.Error(500, "", err) return response.Error(500, "", err)
@@ -46,7 +46,7 @@ func (hs *HTTPServer) AdminProvisioningReloadDashboards(c *models.ReqContext) re
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminProvisioningReloadDatasources(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminProvisioningReloadDatasources(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionDatasources(c.Req.Context()) err := hs.ProvisioningService.ProvisionDatasources(c.Req.Context())
if err != nil { if err != nil {
return response.Error(500, "", err) return response.Error(500, "", err)
@@ -69,7 +69,7 @@ func (hs *HTTPServer) AdminProvisioningReloadDatasources(c *models.ReqContext) r
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionPlugins(c.Req.Context()) err := hs.ProvisioningService.ProvisionPlugins(c.Req.Context())
if err != nil { if err != nil {
return response.Error(500, "Failed to reload plugins config", err) return response.Error(500, "Failed to reload plugins config", err)
@@ -92,7 +92,7 @@ func (hs *HTTPServer) AdminProvisioningReloadPlugins(c *models.ReqContext) respo
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminProvisioningReloadNotifications(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminProvisioningReloadNotifications(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionNotifications(c.Req.Context()) err := hs.ProvisioningService.ProvisionNotifications(c.Req.Context())
if err != nil { if err != nil {
return response.Error(500, "", err) return response.Error(500, "", err)
@@ -100,7 +100,7 @@ func (hs *HTTPServer) AdminProvisioningReloadNotifications(c *models.ReqContext)
return response.Success("Notifications config reloaded") return response.Success("Notifications config reloaded")
} }
func (hs *HTTPServer) AdminProvisioningReloadAlerting(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminProvisioningReloadAlerting(c *contextmodel.ReqContext) response.Response {
err := hs.ProvisioningService.ProvisionAlerting(c.Req.Context()) err := hs.ProvisioningService.ProvisionAlerting(c.Req.Context())
if err != nil { if err != nil {
return response.Error(500, "", err) return response.Error(500, "", err)

View File

@@ -15,6 +15,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -38,7 +39,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 412: preconditionFailedError // 412: preconditionFailedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminCreateUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminCreateUser(c *contextmodel.ReqContext) response.Response {
form := dtos.AdminCreateUserForm{} form := dtos.AdminCreateUserForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -104,7 +105,7 @@ func (hs *HTTPServer) AdminCreateUser(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminUpdateUserPassword(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminUpdateUserPassword(c *contextmodel.ReqContext) response.Response {
form := dtos.AdminUpdateUserPasswordForm{} form := dtos.AdminUpdateUserPasswordForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -156,7 +157,7 @@ func (hs *HTTPServer) AdminUpdateUserPassword(c *models.ReqContext) response.Res
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminUpdateUserPermissions(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminUpdateUserPermissions(c *contextmodel.ReqContext) response.Response {
form := dtos.AdminUpdateUserPermissionsForm{} form := dtos.AdminUpdateUserPermissionsForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -193,7 +194,7 @@ func (hs *HTTPServer) AdminUpdateUserPermissions(c *models.ReqContext) response.
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminDeleteUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminDeleteUser(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -285,7 +286,7 @@ func (hs *HTTPServer) AdminDeleteUser(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminDisableUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminDisableUser(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -328,7 +329,7 @@ func (hs *HTTPServer) AdminDisableUser(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminEnableUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminEnableUser(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -366,7 +367,7 @@ func (hs *HTTPServer) AdminEnableUser(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminLogoutUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminLogoutUser(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -392,7 +393,7 @@ func (hs *HTTPServer) AdminLogoutUser(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminGetUserAuthTokens(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminGetUserAuthTokens(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -417,7 +418,7 @@ func (hs *HTTPServer) AdminGetUserAuthTokens(c *models.ReqContext) response.Resp
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AdminRevokeUserAuthToken(c *models.ReqContext) response.Response { func (hs *HTTPServer) AdminRevokeUserAuthToken(c *contextmodel.ReqContext) response.Response {
cmd := auth.RevokeAuthTokenCmd{} cmd := auth.RevokeAuthTokenCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -13,9 +13,9 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/authtest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/login/logintest"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
@@ -242,7 +242,7 @@ func putAdminScenario(t *testing.T, desc string, url string, routePattern string
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -267,7 +267,7 @@ func adminLogoutUserScenario(t *testing.T, desc string, url string, routePattern
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
t.Log("Route handler invoked", "url", c.Req.URL) t.Log("Route handler invoked", "url", c.Req.URL)
sc.context = c sc.context = c
@@ -295,7 +295,7 @@ func adminRevokeUserAuthTokenScenario(t *testing.T, desc string, url string, rou
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -323,7 +323,7 @@ func adminGetUserAuthTokensScenario(t *testing.T, desc string, url string, route
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
sc.context.OrgID = testOrgID sc.context.OrgID = testOrgID
@@ -355,7 +355,7 @@ func adminDisableUserScenario(t *testing.T, desc string, action string, url stri
sc.sqlStore = hs.SQLStore sc.sqlStore = hs.SQLStore
sc.authInfoService = authInfoService sc.authInfoService = authInfoService
sc.userService = hs.userService sc.userService = hs.userService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
@@ -381,7 +381,7 @@ func adminDeleteUserScenario(t *testing.T, desc string, url string, routePattern
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.sqlStore = hs.SQLStore sc.sqlStore = hs.SQLStore
sc.authInfoService = &logintest.AuthInfoServiceFake{} sc.authInfoService = &logintest.AuthInfoServiceFake{}
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
@@ -402,7 +402,7 @@ func adminCreateUserScenario(t *testing.T, desc string, url string, routePattern
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -12,6 +12,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
alertmodels "github.com/grafana/grafana/pkg/services/alerting/models" alertmodels "github.com/grafana/grafana/pkg/services/alerting/models"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@@ -23,7 +24,7 @@ import (
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) ValidateOrgAlert(c *models.ReqContext) { func (hs *HTTPServer) ValidateOrgAlert(c *contextmodel.ReqContext) {
id, err := strconv.ParseInt(web.Params(c.Req)[":alertId"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":alertId"], 10, 64)
if err != nil { if err != nil {
c.JsonApiErr(http.StatusBadRequest, "alertId is invalid", nil) c.JsonApiErr(http.StatusBadRequest, "alertId is invalid", nil)
@@ -51,7 +52,7 @@ func (hs *HTTPServer) ValidateOrgAlert(c *models.ReqContext) {
// 200: getDashboardStatesResponse // 200: getDashboardStatesResponse
// 400: badRequestError // 400: badRequestError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlertStatesForDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlertStatesForDashboard(c *contextmodel.ReqContext) response.Response {
dashboardID := c.QueryInt64("dashboardId") dashboardID := c.QueryInt64("dashboardId")
if dashboardID == 0 { if dashboardID == 0 {
@@ -78,7 +79,7 @@ func (hs *HTTPServer) GetAlertStatesForDashboard(c *models.ReqContext) response.
// 200: getAlertsResponse // 200: getAlertsResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlerts(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlerts(c *contextmodel.ReqContext) response.Response {
dashboardQuery := c.Query("dashboardQuery") dashboardQuery := c.Query("dashboardQuery")
dashboardTags := c.QueryStrings("dashboardTag") dashboardTags := c.QueryStrings("dashboardTag")
stringDashboardIDs := c.QueryStrings("dashboardId") stringDashboardIDs := c.QueryStrings("dashboardId")
@@ -165,7 +166,7 @@ func (hs *HTTPServer) GetAlerts(c *models.ReqContext) response.Response {
// 422: unprocessableEntityError // 422: unprocessableEntityError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AlertTest(c *models.ReqContext) response.Response { func (hs *HTTPServer) AlertTest(c *contextmodel.ReqContext) response.Response {
dto := dtos.AlertTestCommand{} dto := dtos.AlertTestCommand{}
if err := web.Bind(c.Req, &dto); err != nil { if err := web.Bind(c.Req, &dto); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -219,7 +220,7 @@ func (hs *HTTPServer) AlertTest(c *models.ReqContext) response.Response {
// 200: getAlertResponse // 200: getAlertResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlert(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlert(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":alertId"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":alertId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "alertId is invalid", err) return response.Error(http.StatusBadRequest, "alertId is invalid", err)
@@ -233,8 +234,8 @@ func (hs *HTTPServer) GetAlert(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, &query.Result) return response.JSON(http.StatusOK, &query.Result)
} }
func (hs *HTTPServer) GetAlertNotifiers(ngalertEnabled bool) func(*models.ReqContext) response.Response { func (hs *HTTPServer) GetAlertNotifiers(ngalertEnabled bool) func(*contextmodel.ReqContext) response.Response {
return func(_ *models.ReqContext) response.Response { return func(_ *contextmodel.ReqContext) response.Response {
if ngalertEnabled { if ngalertEnabled {
return response.JSON(http.StatusOK, channels_config.GetAvailableNotifiers()) return response.JSON(http.StatusOK, channels_config.GetAvailableNotifiers())
} }
@@ -255,7 +256,7 @@ func (hs *HTTPServer) GetAlertNotifiers(ngalertEnabled bool) func(*models.ReqCon
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlertNotificationLookup(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlertNotificationLookup(c *contextmodel.ReqContext) response.Response {
alertNotifications, err := hs.getAlertNotificationsInternal(c) alertNotifications, err := hs.getAlertNotificationsInternal(c)
if err != nil { if err != nil {
return response.Error(500, "Failed to get alert notifications", err) return response.Error(500, "Failed to get alert notifications", err)
@@ -281,7 +282,7 @@ func (hs *HTTPServer) GetAlertNotificationLookup(c *models.ReqContext) response.
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlertNotifications(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlertNotifications(c *contextmodel.ReqContext) response.Response {
alertNotifications, err := hs.getAlertNotificationsInternal(c) alertNotifications, err := hs.getAlertNotificationsInternal(c)
if err != nil { if err != nil {
return response.Error(500, "Failed to get alert notifications", err) return response.Error(500, "Failed to get alert notifications", err)
@@ -296,7 +297,7 @@ func (hs *HTTPServer) GetAlertNotifications(c *models.ReqContext) response.Respo
return response.JSON(http.StatusOK, result) return response.JSON(http.StatusOK, result)
} }
func (hs *HTTPServer) getAlertNotificationsInternal(c *models.ReqContext) ([]*alertmodels.AlertNotification, error) { func (hs *HTTPServer) getAlertNotificationsInternal(c *contextmodel.ReqContext) ([]*alertmodels.AlertNotification, error) {
query := &alertmodels.GetAllAlertNotificationsQuery{OrgId: c.OrgID} query := &alertmodels.GetAllAlertNotificationsQuery{OrgId: c.OrgID}
if err := hs.AlertNotificationService.GetAllAlertNotifications(c.Req.Context(), query); err != nil { if err := hs.AlertNotificationService.GetAllAlertNotifications(c.Req.Context(), query); err != nil {
@@ -318,7 +319,7 @@ func (hs *HTTPServer) getAlertNotificationsInternal(c *models.ReqContext) ([]*al
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlertNotificationByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlertNotificationByID(c *contextmodel.ReqContext) response.Response {
notificationId, err := strconv.ParseInt(web.Params(c.Req)[":notificationId"], 10, 64) notificationId, err := strconv.ParseInt(web.Params(c.Req)[":notificationId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "notificationId is invalid", err) return response.Error(http.StatusBadRequest, "notificationId is invalid", err)
@@ -355,7 +356,7 @@ func (hs *HTTPServer) GetAlertNotificationByID(c *models.ReqContext) response.Re
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAlertNotificationByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAlertNotificationByUID(c *contextmodel.ReqContext) response.Response {
query := &alertmodels.GetAlertNotificationsWithUidQuery{ query := &alertmodels.GetAlertNotificationsWithUidQuery{
OrgId: c.OrgID, OrgId: c.OrgID,
Uid: web.Params(c.Req)[":uid"], Uid: web.Params(c.Req)[":uid"],
@@ -388,7 +389,7 @@ func (hs *HTTPServer) GetAlertNotificationByUID(c *models.ReqContext) response.R
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CreateAlertNotification(c *models.ReqContext) response.Response { func (hs *HTTPServer) CreateAlertNotification(c *contextmodel.ReqContext) response.Response {
cmd := alertmodels.CreateAlertNotificationCommand{} cmd := alertmodels.CreateAlertNotificationCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -421,7 +422,7 @@ func (hs *HTTPServer) CreateAlertNotification(c *models.ReqContext) response.Res
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateAlertNotification(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateAlertNotification(c *contextmodel.ReqContext) response.Response {
cmd := alertmodels.UpdateAlertNotificationCommand{} cmd := alertmodels.UpdateAlertNotificationCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -468,7 +469,7 @@ func (hs *HTTPServer) UpdateAlertNotification(c *models.ReqContext) response.Res
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateAlertNotificationByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateAlertNotificationByUID(c *contextmodel.ReqContext) response.Response {
cmd := alertmodels.UpdateAlertNotificationWithUidCommand{} cmd := alertmodels.UpdateAlertNotificationWithUidCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -568,7 +569,7 @@ func (hs *HTTPServer) fillWithSecureSettingsDataByUID(ctx context.Context, cmd *
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteAlertNotification(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteAlertNotification(c *contextmodel.ReqContext) response.Response {
notificationId, err := strconv.ParseInt(web.Params(c.Req)[":notificationId"], 10, 64) notificationId, err := strconv.ParseInt(web.Params(c.Req)[":notificationId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "notificationId is invalid", err) return response.Error(http.StatusBadRequest, "notificationId is invalid", err)
@@ -601,7 +602,7 @@ func (hs *HTTPServer) DeleteAlertNotification(c *models.ReqContext) response.Res
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteAlertNotificationByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteAlertNotificationByUID(c *contextmodel.ReqContext) response.Response {
cmd := alertmodels.DeleteAlertNotificationWithUidCommand{ cmd := alertmodels.DeleteAlertNotificationWithUidCommand{
OrgId: c.OrgID, OrgId: c.OrgID,
Uid: web.Params(c.Req)[":uid"], Uid: web.Params(c.Req)[":uid"],
@@ -633,7 +634,7 @@ func (hs *HTTPServer) DeleteAlertNotificationByUID(c *models.ReqContext) respons
// 403: forbiddenError // 403: forbiddenError
// 412: SMTPNotEnabledError // 412: SMTPNotEnabledError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) NotificationTest(c *models.ReqContext) response.Response { func (hs *HTTPServer) NotificationTest(c *contextmodel.ReqContext) response.Response {
dto := dtos.NotificationTestCommand{} dto := dtos.NotificationTestCommand{}
if err := web.Bind(c.Req, &dto); err != nil { if err := web.Bind(c.Req, &dto); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -672,14 +673,14 @@ func (hs *HTTPServer) NotificationTest(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *models.ReqContext) response.Response { func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmodel.ReqContext) response.Response {
if legacyAlertingEnabled == nil || !*legacyAlertingEnabled { if legacyAlertingEnabled == nil || !*legacyAlertingEnabled {
return func(_ *models.ReqContext) response.Response { return func(_ *contextmodel.ReqContext) response.Response {
return response.Error(http.StatusBadRequest, "legacy alerting is disabled, so this call has no effect.", nil) return response.Error(http.StatusBadRequest, "legacy alerting is disabled, so this call has no effect.", nil)
} }
} }
return func(c *models.ReqContext) response.Response { return func(c *contextmodel.ReqContext) response.Response {
dto := dtos.PauseAlertCommand{} dto := dtos.PauseAlertCommand{}
if err := web.Bind(c.Req, &dto); err != nil { if err := web.Bind(c.Req, &dto); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -754,14 +755,14 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *models.Req
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PauseAllAlerts(legacyAlertingEnabled *bool) func(c *models.ReqContext) response.Response { func (hs *HTTPServer) PauseAllAlerts(legacyAlertingEnabled *bool) func(c *contextmodel.ReqContext) response.Response {
if legacyAlertingEnabled == nil || !*legacyAlertingEnabled { if legacyAlertingEnabled == nil || !*legacyAlertingEnabled {
return func(_ *models.ReqContext) response.Response { return func(_ *contextmodel.ReqContext) response.Response {
return response.Error(http.StatusBadRequest, "legacy alerting is disabled, so this call has no effect.", nil) return response.Error(http.StatusBadRequest, "legacy alerting is disabled, so this call has no effect.", nil)
} }
} }
return func(c *models.ReqContext) response.Response { return func(c *contextmodel.ReqContext) response.Response {
dto := dtos.PauseAllAlertsCommand{} dto := dtos.PauseAllAlertsCommand{}
if err := web.Bind(c.Req, &dto); err != nil { if err := web.Bind(c.Req, &dto); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -9,9 +9,9 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/annotations"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@@ -31,7 +31,7 @@ import (
// 200: getAnnotationsResponse // 200: getAnnotationsResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAnnotations(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAnnotations(c *contextmodel.ReqContext) response.Response {
query := &annotations.ItemQuery{ query := &annotations.ItemQuery{
From: c.QueryInt64("from"), From: c.QueryInt64("from"),
To: c.QueryInt64("to"), To: c.QueryInt64("to"),
@@ -114,7 +114,7 @@ func (e *AnnotationError) Error() string {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PostAnnotation(c *models.ReqContext) response.Response { func (hs *HTTPServer) PostAnnotation(c *contextmodel.ReqContext) response.Response {
cmd := dtos.PostAnnotationsCmd{} cmd := dtos.PostAnnotationsCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -185,7 +185,7 @@ func formatGraphiteAnnotation(what string, data string) string {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PostGraphiteAnnotation(c *models.ReqContext) response.Response { func (hs *HTTPServer) PostGraphiteAnnotation(c *contextmodel.ReqContext) response.Response {
cmd := dtos.PostGraphiteAnnotationsCmd{} cmd := dtos.PostGraphiteAnnotationsCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -250,7 +250,7 @@ func (hs *HTTPServer) PostGraphiteAnnotation(c *models.ReqContext) response.Resp
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateAnnotation(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateAnnotation(c *contextmodel.ReqContext) response.Response {
cmd := dtos.UpdateAnnotationsCmd{} cmd := dtos.UpdateAnnotationsCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -306,7 +306,7 @@ func (hs *HTTPServer) UpdateAnnotation(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PatchAnnotation(c *models.ReqContext) response.Response { func (hs *HTTPServer) PatchAnnotation(c *contextmodel.ReqContext) response.Response {
cmd := dtos.PatchAnnotationsCmd{} cmd := dtos.PatchAnnotationsCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -371,7 +371,7 @@ func (hs *HTTPServer) PatchAnnotation(c *models.ReqContext) response.Response {
// 200: okResponse // 200: okResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) MassDeleteAnnotations(c *models.ReqContext) response.Response { func (hs *HTTPServer) MassDeleteAnnotations(c *contextmodel.ReqContext) response.Response {
cmd := dtos.MassDeleteAnnotationsCmd{} cmd := dtos.MassDeleteAnnotationsCmd{}
err := web.Bind(c.Req, &cmd) err := web.Bind(c.Req, &cmd)
if err != nil { if err != nil {
@@ -447,7 +447,7 @@ func (hs *HTTPServer) MassDeleteAnnotations(c *models.ReqContext) response.Respo
// 200: getAnnotationByIDResponse // 200: getAnnotationByIDResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAnnotationByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAnnotationByID(c *contextmodel.ReqContext) response.Response {
annotationID, err := strconv.ParseInt(web.Params(c.Req)[":annotationId"], 10, 64) annotationID, err := strconv.ParseInt(web.Params(c.Req)[":annotationId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "annotationId is invalid", err) return response.Error(http.StatusBadRequest, "annotationId is invalid", err)
@@ -476,7 +476,7 @@ func (hs *HTTPServer) GetAnnotationByID(c *models.ReqContext) response.Response
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteAnnotationByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteAnnotationByID(c *contextmodel.ReqContext) response.Response {
annotationID, err := strconv.ParseInt(web.Params(c.Req)[":annotationId"], 10, 64) annotationID, err := strconv.ParseInt(web.Params(c.Req)[":annotationId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "annotationId is invalid", err) return response.Error(http.StatusBadRequest, "annotationId is invalid", err)
@@ -502,7 +502,7 @@ func (hs *HTTPServer) DeleteAnnotationByID(c *models.ReqContext) response.Respon
return response.Success("Annotation deleted") return response.Success("Annotation deleted")
} }
func (hs *HTTPServer) canSaveAnnotation(c *models.ReqContext, annotation *annotations.ItemDTO) (bool, error) { func (hs *HTTPServer) canSaveAnnotation(c *contextmodel.ReqContext, annotation *annotations.ItemDTO) (bool, error) {
if annotation.GetType() == annotations.Dashboard { if annotation.GetType() == annotations.Dashboard {
return canEditDashboard(c, annotation.DashboardId) return canEditDashboard(c, annotation.DashboardId)
} else { } else {
@@ -513,7 +513,7 @@ func (hs *HTTPServer) canSaveAnnotation(c *models.ReqContext, annotation *annota
} }
} }
func canEditDashboard(c *models.ReqContext, dashboardID int64) (bool, error) { func canEditDashboard(c *contextmodel.ReqContext, dashboardID int64) (bool, error) {
guard, err := guardian.New(c.Req.Context(), dashboardID, c.OrgID, c.SignedInUser) guard, err := guardian.New(c.Req.Context(), dashboardID, c.OrgID, c.SignedInUser)
if err != nil { if err != nil {
return false, err return false, err
@@ -555,7 +555,7 @@ func findAnnotationByID(ctx context.Context, repo annotations.Repository, annota
// 200: getAnnotationTagsResponse // 200: getAnnotationTagsResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAnnotationTags(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAnnotationTags(c *contextmodel.ReqContext) response.Response {
query := &annotations.TagsQuery{ query := &annotations.TagsQuery{
OrgID: c.OrgID, OrgID: c.OrgID,
Tag: c.Query("tag"), Tag: c.Query("tag"),
@@ -612,7 +612,7 @@ func AnnotationTypeScopeResolver(annotationsRepo annotations.Repository) (string
}) })
} }
func (hs *HTTPServer) canCreateAnnotation(c *models.ReqContext, dashboardId int64) (bool, error) { func (hs *HTTPServer) canCreateAnnotation(c *contextmodel.ReqContext, dashboardId int64) (bool, error) {
if dashboardId != 0 { if dashboardId != 0 {
if !hs.AccessControl.IsDisabled() { if !hs.AccessControl.IsDisabled() {
evaluator := accesscontrol.EvalPermission(accesscontrol.ActionAnnotationsCreate, accesscontrol.ScopeAnnotationsTypeDashboard) evaluator := accesscontrol.EvalPermission(accesscontrol.ActionAnnotationsCreate, accesscontrol.ScopeAnnotationsTypeDashboard)
@@ -632,7 +632,7 @@ func (hs *HTTPServer) canCreateAnnotation(c *models.ReqContext, dashboardId int6
} }
} }
func (hs *HTTPServer) canMassDeleteAnnotations(c *models.ReqContext, dashboardID int64) (bool, error) { func (hs *HTTPServer) canMassDeleteAnnotations(c *contextmodel.ReqContext, dashboardID int64) (bool, error) {
if dashboardID == 0 { if dashboardID == 0 {
evaluator := accesscontrol.EvalPermission(accesscontrol.ActionAnnotationsDelete, accesscontrol.ScopeAnnotationsTypeOrganization) evaluator := accesscontrol.EvalPermission(accesscontrol.ActionAnnotationsDelete, accesscontrol.ScopeAnnotationsTypeOrganization)
return hs.AccessControl.Evaluate(c.Req.Context(), c.SignedInUser, evaluator) return hs.AccessControl.Evaluate(c.Req.Context(), c.SignedInUser, evaluator)

View File

@@ -17,11 +17,11 @@ import (
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "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/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl"
"github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/annotations/annotationstest" "github.com/grafana/grafana/pkg/services/annotations/annotationstest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
@@ -296,7 +296,7 @@ func postAnnotationScenario(t *testing.T, desc string, url string, routePattern
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.dashboardService = dashSvc sc.dashboardService = dashSvc
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -320,7 +320,7 @@ func putAnnotationScenario(t *testing.T, desc string, url string, routePattern s
hs.SQLStore = store hs.SQLStore = store
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -345,7 +345,7 @@ func patchAnnotationScenario(t *testing.T, desc string, url string, routePattern
hs.SQLStore = store hs.SQLStore = store
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -370,7 +370,7 @@ func deleteAnnotationsScenario(t *testing.T, desc string, url string, routePatte
hs.DashboardService = dashSvc hs.DashboardService = dashSvc
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -33,11 +33,11 @@ import (
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/middleware" "github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/apikey" "github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/correlations" "github.com/grafana/grafana/pkg/services/correlations"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
@@ -173,8 +173,8 @@ func (hs *HTTPServer) registerRoutes() {
) )
} }
r.Get("/explore", authorize(func(c *models.ReqContext) { r.Get("/explore", authorize(func(c *contextmodel.ReqContext) {
if f, ok := reqSignedIn.(func(c *models.ReqContext)); ok { if f, ok := reqSignedIn.(func(c *contextmodel.ReqContext)); ok {
f(c) f(c)
} }
middleware.EnsureEditorOrViewerCanEdit(c) middleware.EnsureEditorOrViewerCanEdit(c)

View File

@@ -9,8 +9,8 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/components/apikeygen" "github.com/grafana/grafana/pkg/components/apikeygen"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/apikey" "github.com/grafana/grafana/pkg/services/apikey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -26,7 +26,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetAPIKeys(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetAPIKeys(c *contextmodel.ReqContext) response.Response {
query := apikey.GetApiKeysQuery{OrgId: c.OrgID, User: c.SignedInUser, IncludeExpired: c.QueryBool("includeExpired")} query := apikey.GetApiKeysQuery{OrgId: c.OrgID, User: c.SignedInUser, IncludeExpired: c.QueryBool("includeExpired")}
if err := hs.apiKeyService.GetAPIKeys(c.Req.Context(), &query); err != nil { if err := hs.apiKeyService.GetAPIKeys(c.Req.Context(), &query); err != nil {
@@ -70,7 +70,7 @@ func (hs *HTTPServer) GetAPIKeys(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteAPIKey(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteAPIKey(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -104,7 +104,7 @@ func (hs *HTTPServer) DeleteAPIKey(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AddAPIKey(c *models.ReqContext) response.Response { func (hs *HTTPServer) AddAPIKey(c *contextmodel.ReqContext) response.Response {
cmd := apikey.AddCommand{} cmd := apikey.AddCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -21,7 +21,7 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/infra/log" "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/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
gocache "github.com/patrickmn/go-cache" gocache "github.com/patrickmn/go-cache"
@@ -98,7 +98,7 @@ type AvatarCacheServer struct {
var validMD5 = regexp.MustCompile("^[a-fA-F0-9]{32}$") var validMD5 = regexp.MustCompile("^[a-fA-F0-9]{32}$")
func (a *AvatarCacheServer) Handler(ctx *models.ReqContext) { func (a *AvatarCacheServer) Handler(ctx *contextmodel.ReqContext) {
hash := web.Params(ctx.Req)[":hash"] hash := web.Params(ctx.Req)[":hash"]
if len(hash) != 32 || !validMD5.MatchString(hash) { if len(hash) != 32 || !validMD5.MatchString(hash) {

View File

@@ -5,14 +5,14 @@ import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/comments" "github.com/grafana/grafana/pkg/services/comments"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) commentsGet(c *models.ReqContext) response.Response { func (hs *HTTPServer) commentsGet(c *contextmodel.ReqContext) response.Response {
cmd := comments.GetCmd{} cmd := comments.GetCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -29,7 +29,7 @@ func (hs *HTTPServer) commentsGet(c *models.ReqContext) response.Response {
}) })
} }
func (hs *HTTPServer) commentsCreate(c *models.ReqContext) response.Response { func (hs *HTTPServer) commentsCreate(c *contextmodel.ReqContext) response.Response {
cmd := comments.CreateCmd{} cmd := comments.CreateCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -35,6 +35,7 @@ import (
"github.com/grafana/grafana/pkg/services/contexthandler" "github.com/grafana/grafana/pkg/services/contexthandler"
"github.com/grafana/grafana/pkg/services/contexthandler/authproxy" "github.com/grafana/grafana/pkg/services/contexthandler/authproxy"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
dashboardsstore "github.com/grafana/grafana/pkg/services/dashboards/database" dashboardsstore "github.com/grafana/grafana/pkg/services/dashboards/database"
dashboardservice "github.com/grafana/grafana/pkg/services/dashboards/service" dashboardservice "github.com/grafana/grafana/pkg/services/dashboards/service"
@@ -76,7 +77,7 @@ func loggedInUserScenarioWithRole(t *testing.T, desc string, method string, url
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.sqlStore = sqlStore sc.sqlStore = sqlStore
sc.userService = usertest.NewUserServiceFake() sc.userService = usertest.NewUserServiceFake()
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
sc.context.OrgID = testOrgID sc.context.OrgID = testOrgID
@@ -102,7 +103,7 @@ func loggedInUserScenarioWithRole(t *testing.T, desc string, method string, url
func anonymousUserScenario(t *testing.T, desc string, method string, url string, routePattern string, fn scenarioFunc) { func anonymousUserScenario(t *testing.T, desc string, method string, url string, routePattern string, fn scenarioFunc) {
t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) {
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
if sc.handlerFunc != nil { if sc.handlerFunc != nil {
return sc.handlerFunc(sc.context) return sc.handlerFunc(sc.context)
@@ -178,7 +179,7 @@ type scenarioContext struct {
t *testing.T t *testing.T
cfg *setting.Cfg cfg *setting.Cfg
m *web.Mux m *web.Mux
context *models.ReqContext context *contextmodel.ReqContext
resp *httptest.ResponseRecorder resp *httptest.ResponseRecorder
handlerFunc handlerFunc handlerFunc handlerFunc
defaultHandler web.Handler defaultHandler web.Handler
@@ -197,7 +198,7 @@ func (sc *scenarioContext) exec() {
} }
type scenarioFunc func(c *scenarioContext) type scenarioFunc func(c *scenarioContext)
type handlerFunc func(c *models.ReqContext) response.Response type handlerFunc func(c *contextmodel.ReqContext) response.Response
func getContextHandler(t *testing.T, cfg *setting.Cfg) *contexthandler.ContextHandler { func getContextHandler(t *testing.T, cfg *setting.Cfg) *contexthandler.ContextHandler {
t.Helper() t.Helper()
@@ -266,7 +267,7 @@ type accessControlScenarioContext struct {
// initCtx is used in a middleware to set the initial context // initCtx is used in a middleware to set the initial context
// of the request server side. Can be used to pretend sign in. // of the request server side. Can be used to pretend sign in.
initCtx *models.ReqContext initCtx *contextmodel.ReqContext
// hs is a minimal HTTPServer for the accesscontrol tests to pass. // hs is a minimal HTTPServer for the accesscontrol tests to pass.
hs *HTTPServer hs *HTTPServer
@@ -302,17 +303,17 @@ func userWithPermissions(orgID int64, permissions []accesscontrol.Permission) *u
} }
// setInitCtxSignedInUser sets a copy of the user in initCtx // setInitCtxSignedInUser sets a copy of the user in initCtx
func setInitCtxSignedInUser(initCtx *models.ReqContext, user user.SignedInUser) { func setInitCtxSignedInUser(initCtx *contextmodel.ReqContext, user user.SignedInUser) {
initCtx.IsSignedIn = true initCtx.IsSignedIn = true
initCtx.SignedInUser = &user initCtx.SignedInUser = &user
} }
func setInitCtxSignedInViewer(initCtx *models.ReqContext) { func setInitCtxSignedInViewer(initCtx *contextmodel.ReqContext) {
initCtx.IsSignedIn = true initCtx.IsSignedIn = true
initCtx.SignedInUser = &user.SignedInUser{UserID: testUserID, OrgID: 1, OrgRole: org.RoleViewer, Login: testUserLogin} initCtx.SignedInUser = &user.SignedInUser{UserID: testUserID, OrgID: 1, OrgRole: org.RoleViewer, Login: testUserLogin}
} }
func setInitCtxSignedInOrgAdmin(initCtx *models.ReqContext) { func setInitCtxSignedInOrgAdmin(initCtx *contextmodel.ReqContext) {
initCtx.IsSignedIn = true initCtx.IsSignedIn = true
initCtx.SignedInUser = &user.SignedInUser{UserID: testUserID, OrgID: 1, OrgRole: org.RoleAdmin, Login: testUserLogin} initCtx.SignedInUser = &user.SignedInUser{UserID: testUserID, OrgID: 1, OrgRole: org.RoleAdmin, Login: testUserLogin}
} }
@@ -434,7 +435,7 @@ func setupHTTPServerWithCfgDb(
m := web.New() m := web.New()
// middleware to set the test initial context // middleware to set the test initial context
initCtx := &models.ReqContext{} initCtx := &contextmodel.ReqContext{}
m.Use(func(c *web.Context) { m.Use(func(c *web.Context) {
initCtx.Context = c initCtx.Context = c
initCtx.Logger = log.New("api-test") initCtx.Logger = log.New("api-test")

View File

@@ -18,9 +18,9 @@ import (
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/kinds/dashboard" "github.com/grafana/grafana/pkg/kinds/dashboard"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
dashver "github.com/grafana/grafana/pkg/services/dashboardversion" dashver "github.com/grafana/grafana/pkg/services/dashboardversion"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
@@ -39,7 +39,7 @@ const (
anonString = "Anonymous" anonString = "Anonymous"
) )
func (hs *HTTPServer) isDashboardStarredByUser(c *models.ReqContext, dashID int64) (bool, error) { func (hs *HTTPServer) isDashboardStarredByUser(c *contextmodel.ReqContext, dashID int64) (bool, error) {
if !c.IsSignedIn { if !c.IsSignedIn {
return false, nil return false, nil
} }
@@ -63,7 +63,7 @@ func dashboardGuardianResponse(err error) response.Response {
// 200: trimDashboardResponse // 200: trimDashboardResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) TrimDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) TrimDashboard(c *contextmodel.ReqContext) response.Response {
cmd := dashboards.TrimDashboardCommand{} cmd := dashboards.TrimDashboardCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -93,7 +93,7 @@ func (hs *HTTPServer) TrimDashboard(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDashboard(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
dash, rsp := hs.getDashboardHelper(c.Req.Context(), c.OrgID, 0, uid) dash, rsp := hs.getDashboardHelper(c.Req.Context(), c.OrgID, 0, uid)
if rsp != nil { if rsp != nil {
@@ -242,7 +242,7 @@ func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, dto) return response.JSON(http.StatusOK, dto)
} }
func (hs *HTTPServer) getAnnotationPermissionsByScope(c *models.ReqContext, actions *dtos.AnnotationActions, scope string) { func (hs *HTTPServer) getAnnotationPermissionsByScope(c *contextmodel.ReqContext, actions *dtos.AnnotationActions, scope string) {
var err error var err error
evaluate := accesscontrol.EvalPermission(accesscontrol.ActionAnnotationsCreate, scope) evaluate := accesscontrol.EvalPermission(accesscontrol.ActionAnnotationsCreate, scope)
@@ -302,11 +302,11 @@ func (hs *HTTPServer) getDashboardHelper(ctx context.Context, orgID int64, id in
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteDashboardByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDashboardByUID(c *contextmodel.ReqContext) response.Response {
return hs.deleteDashboard(c) return hs.deleteDashboard(c)
} }
func (hs *HTTPServer) deleteDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) deleteDashboard(c *contextmodel.ReqContext) response.Response {
dash, rsp := hs.getDashboardHelper(c.Req.Context(), c.OrgID, 0, web.Params(c.Req)[":uid"]) dash, rsp := hs.getDashboardHelper(c.Req.Context(), c.OrgID, 0, web.Params(c.Req)[":uid"])
if rsp != nil { if rsp != nil {
return rsp return rsp
@@ -365,7 +365,7 @@ func (hs *HTTPServer) deleteDashboard(c *models.ReqContext) response.Response {
// 412: preconditionFailedError // 412: preconditionFailedError
// 422: unprocessableEntityError // 422: unprocessableEntityError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PostDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) PostDashboard(c *contextmodel.ReqContext) response.Response {
cmd := dashboards.SaveDashboardCommand{} cmd := dashboards.SaveDashboardCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -396,7 +396,7 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext) response.Response {
return hs.postDashboard(c, cmd) return hs.postDashboard(c, cmd)
} }
func (hs *HTTPServer) postDashboard(c *models.ReqContext, cmd dashboards.SaveDashboardCommand) response.Response { func (hs *HTTPServer) postDashboard(c *contextmodel.ReqContext, cmd dashboards.SaveDashboardCommand) response.Response {
ctx := c.Req.Context() ctx := c.Req.Context()
var err error var err error
cmd.OrgID = c.OrgID cmd.OrgID = c.OrgID
@@ -517,7 +517,7 @@ func (hs *HTTPServer) postDashboard(c *models.ReqContext, cmd dashboards.SaveDas
// 200: getHomeDashboardResponse // 200: getHomeDashboardResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetHomeDashboard(c *contextmodel.ReqContext) response.Response {
prefsQuery := pref.GetPreferenceWithDefaultsQuery{OrgID: c.OrgID, UserID: c.SignedInUser.UserID, Teams: c.Teams} prefsQuery := pref.GetPreferenceWithDefaultsQuery{OrgID: c.OrgID, UserID: c.SignedInUser.UserID, Teams: c.Teams}
homePage := hs.Cfg.HomePage homePage := hs.Cfg.HomePage
@@ -575,7 +575,7 @@ func (hs *HTTPServer) GetHomeDashboard(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, &dash) return response.JSON(http.StatusOK, &dash)
} }
func (hs *HTTPServer) addGettingStartedPanelToHomeDashboard(c *models.ReqContext, dash *simplejson.Json) { func (hs *HTTPServer) addGettingStartedPanelToHomeDashboard(c *contextmodel.ReqContext, dash *simplejson.Json) {
// We only add this getting started panel for Admins who have not dismissed it, // We only add this getting started panel for Admins who have not dismissed it,
// and if a custom default home dashboard hasn't been configured // and if a custom default home dashboard hasn't been configured
if !c.HasUserRole(org.RoleAdmin) || if !c.HasUserRole(org.RoleAdmin) ||
@@ -626,7 +626,7 @@ func (hs *HTTPServer) addGettingStartedPanelToHomeDashboard(c *models.ReqContext
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDashboardVersions(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDashboardVersions(c *contextmodel.ReqContext) response.Response {
var dashID int64 var dashID int64
var err error var err error
@@ -709,7 +709,7 @@ func (hs *HTTPServer) GetDashboardVersions(c *models.ReqContext) response.Respon
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDashboardVersion(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDashboardVersion(c *contextmodel.ReqContext) response.Response {
var dashID int64 var dashID int64
var err error var err error
@@ -784,7 +784,7 @@ func (hs *HTTPServer) GetDashboardVersion(c *models.ReqContext) response.Respons
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) ValidateDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) ValidateDashboard(c *contextmodel.ReqContext) response.Response {
cmd := dashboards.ValidateDashboardCommand{} cmd := dashboards.ValidateDashboardCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
@@ -846,7 +846,7 @@ func (hs *HTTPServer) ValidateDashboard(c *models.ReqContext) response.Response
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CalculateDashboardDiff(c *models.ReqContext) response.Response { func (hs *HTTPServer) CalculateDashboardDiff(c *contextmodel.ReqContext) response.Response {
apiOptions := dtos.CalculateDiffOptions{} apiOptions := dtos.CalculateDiffOptions{}
if err := web.Bind(c.Req, &apiOptions); err != nil { if err := web.Bind(c.Req, &apiOptions); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -958,7 +958,7 @@ func (hs *HTTPServer) CalculateDashboardDiff(c *models.ReqContext) response.Resp
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext) response.Response { func (hs *HTTPServer) RestoreDashboardVersion(c *contextmodel.ReqContext) response.Response {
var dashID int64 var dashID int64
var err error var err error
@@ -1016,7 +1016,7 @@ func (hs *HTTPServer) RestoreDashboardVersion(c *models.ReqContext) response.Res
// 200: getDashboardsTagsResponse // 200: getDashboardsTagsResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDashboardTags(c *models.ReqContext) { func (hs *HTTPServer) GetDashboardTags(c *contextmodel.ReqContext) {
query := dashboards.GetDashboardTagsQuery{OrgID: c.OrgID} query := dashboards.GetDashboardTagsQuery{OrgID: c.OrgID}
queryResult, err := hs.DashboardService.GetDashboardTags(c.Req.Context(), &query) queryResult, err := hs.DashboardService.GetDashboardTags(c.Req.Context(), &query)
if err != nil { if err != nil {
@@ -1028,7 +1028,7 @@ func (hs *HTTPServer) GetDashboardTags(c *models.ReqContext) {
} }
// GetDashboardUIDs converts internal ids to UIDs // GetDashboardUIDs converts internal ids to UIDs
func (hs *HTTPServer) GetDashboardUIDs(c *models.ReqContext) { func (hs *HTTPServer) GetDashboardUIDs(c *contextmodel.ReqContext) {
ids := strings.Split(web.Params(c.Req)[":ids"], ",") ids := strings.Split(web.Params(c.Req)[":ids"], ",")
uids := make([]string, 0, len(ids)) uids := make([]string, 0, len(ids))

View File

@@ -9,8 +9,8 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -41,7 +41,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDashboardPermissionList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDashboardPermissionList(c *contextmodel.ReqContext) response.Response {
var dashID int64 var dashID int64
var err error var err error
dashUID := web.Params(c.Req)[":uid"] dashUID := web.Params(c.Req)[":uid"]
@@ -123,7 +123,7 @@ func (hs *HTTPServer) GetDashboardPermissionList(c *models.ReqContext) response.
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateDashboardPermissions(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateDashboardPermissions(c *contextmodel.ReqContext) response.Response {
var dashID int64 var dashID int64
var err error var err error
apiCmd := dtos.UpdateDashboardACLCommand{} apiCmd := dtos.UpdateDashboardACLCommand{}

View File

@@ -15,8 +15,8 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
dashboardservice "github.com/grafana/grafana/pkg/services/dashboards/service" dashboardservice "github.com/grafana/grafana/pkg/services/dashboards/service"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
@@ -354,7 +354,7 @@ func updateDashboardPermissionScenario(t *testing.T, ctx updatePermissionContext
t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) { t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) {
sc := setupScenarioContext(t, ctx.url) sc := setupScenarioContext(t, ctx.url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(ctx.cmd) c.Req.Body = mockRequestBody(ctx.cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -12,7 +12,7 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/dashboardsnapshots" "github.com/grafana/grafana/pkg/services/dashboardsnapshots"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@@ -33,7 +33,7 @@ var client = &http.Client{
// Responses: // Responses:
// 200: getSharingOptionsResponse // 200: getSharingOptionsResponse
// 401: unauthorisedError // 401: unauthorisedError
func (hs *HTTPServer) GetSharingOptions(c *models.ReqContext) { func (hs *HTTPServer) GetSharingOptions(c *contextmodel.ReqContext) {
c.JSON(http.StatusOK, util.DynMap{ c.JSON(http.StatusOK, util.DynMap{
"snapshotEnabled": hs.Cfg.SnapshotEnabled, "snapshotEnabled": hs.Cfg.SnapshotEnabled,
"externalSnapshotURL": hs.Cfg.ExternalSnapshotUrl, "externalSnapshotURL": hs.Cfg.ExternalSnapshotUrl,
@@ -105,7 +105,7 @@ func createOriginalDashboardURL(cmd *dashboardsnapshots.CreateDashboardSnapshotC
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CreateDashboardSnapshot(c *models.ReqContext) response.Response { func (hs *HTTPServer) CreateDashboardSnapshot(c *contextmodel.ReqContext) response.Response {
if !hs.Cfg.SnapshotEnabled { if !hs.Cfg.SnapshotEnabled {
c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil) c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil)
return nil return nil
@@ -200,7 +200,7 @@ func (hs *HTTPServer) CreateDashboardSnapshot(c *models.ReqContext) response.Res
// 400: badRequestError // 400: badRequestError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDashboardSnapshot(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDashboardSnapshot(c *contextmodel.ReqContext) response.Response {
if !hs.Cfg.SnapshotEnabled { if !hs.Cfg.SnapshotEnabled {
c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil) c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil)
return nil return nil
@@ -284,7 +284,7 @@ func deleteExternalDashboardSnapshot(externalUrl string) error {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDashboardSnapshotByDeleteKey(c *contextmodel.ReqContext) response.Response {
if !hs.Cfg.SnapshotEnabled { if !hs.Cfg.SnapshotEnabled {
c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil) c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil)
return nil return nil
@@ -329,7 +329,7 @@ func (hs *HTTPServer) DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) r
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteDashboardSnapshot(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDashboardSnapshot(c *contextmodel.ReqContext) response.Response {
if !hs.Cfg.SnapshotEnabled { if !hs.Cfg.SnapshotEnabled {
c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil) c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil)
return nil return nil
@@ -399,7 +399,7 @@ func (hs *HTTPServer) DeleteDashboardSnapshot(c *models.ReqContext) response.Res
// Responses: // Responses:
// 200: searchDashboardSnapshotsResponse // 200: searchDashboardSnapshotsResponse
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) SearchDashboardSnapshots(c *models.ReqContext) response.Response { func (hs *HTTPServer) SearchDashboardSnapshots(c *contextmodel.ReqContext) response.Response {
if !hs.Cfg.SnapshotEnabled { if !hs.Cfg.SnapshotEnabled {
c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil) c.JsonApiErr(http.StatusForbidden, "Dashboard Snapshots are disabled", nil)
return nil return nil

View File

@@ -22,7 +22,6 @@ import (
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/registry/corekind" "github.com/grafana/grafana/pkg/registry/corekind"
"github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl"
@@ -30,6 +29,7 @@ import (
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/annotations/annotationstest" "github.com/grafana/grafana/pkg/services/annotations/annotationstest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/dashboards/database" "github.com/grafana/grafana/pkg/services/dashboards/database"
"github.com/grafana/grafana/pkg/services/dashboards/service" "github.com/grafana/grafana/pkg/services/dashboards/service"
@@ -58,7 +58,7 @@ func TestGetHomeDashboard(t *testing.T) {
httpReq, err := http.NewRequest(http.MethodGet, "", nil) httpReq, err := http.NewRequest(http.MethodGet, "", nil)
require.NoError(t, err) require.NoError(t, err)
httpReq.Header.Add("Content-Type", "application/json") httpReq.Header.Add("Content-Type", "application/json")
req := &models.ReqContext{SignedInUser: &user.SignedInUser{}, Context: &web.Context{Req: httpReq}} req := &contextmodel.ReqContext{SignedInUser: &user.SignedInUser{}, Context: &web.Context{Req: httpReq}}
cfg := setting.NewCfg() cfg := setting.NewCfg()
cfg.StaticRootPath = "../../public/" cfg.StaticRootPath = "../../public/"
prefService := preftest.NewPreferenceServiceFake() prefService := preftest.NewPreferenceServiceFake()
@@ -1076,7 +1076,7 @@ func postDashboardScenario(t *testing.T, desc string, url string, routePattern s
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -1108,7 +1108,7 @@ func postValidateScenario(t *testing.T, desc string, url string, routePattern st
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -1148,7 +1148,7 @@ func postDiffScenario(t *testing.T, desc string, url string, routePattern string
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -1190,7 +1190,7 @@ func restoreDashboardVersionScenario(t *testing.T, desc string, url string, rout
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.sqlStore = sqlStore sc.sqlStore = sqlStore
sc.dashboardVersionService = fakeDashboardVersionService sc.dashboardVersionService = fakeDashboardVersionService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -1,6 +1,6 @@
package api package api
import "github.com/grafana/grafana/pkg/models" import contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
// swagger:route GET /datasources/proxy/{id}/{datasource_proxy_route} datasources datasourceProxyGETcalls // swagger:route GET /datasources/proxy/{id}/{datasource_proxy_route} datasources datasourceProxyGETcalls
// //
@@ -56,7 +56,7 @@ import "github.com/grafana/grafana/pkg/models"
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) ProxyDataSourceRequest(c *models.ReqContext) { func (hs *HTTPServer) ProxyDataSourceRequest(c *contextmodel.ReqContext) {
hs.DataProxy.ProxyDataSourceRequest(c) hs.DataProxy.ProxyDataSourceRequest(c)
} }
@@ -102,7 +102,7 @@ func (hs *HTTPServer) ProxyDataSourceRequest(c *models.ReqContext) {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) ProxyDataSourceRequestWithUID(c *models.ReqContext) { func (hs *HTTPServer) ProxyDataSourceRequestWithUID(c *contextmodel.ReqContext) {
hs.DataProxy.ProxyDatasourceRequestWithUID(c, "") hs.DataProxy.ProxyDatasourceRequestWithUID(c, "")
} }

View File

@@ -17,8 +17,8 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins/adapters" "github.com/grafana/grafana/pkg/plugins/adapters"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/datasources/permissions" "github.com/grafana/grafana/pkg/services/datasources/permissions"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
@@ -42,7 +42,7 @@ var secretsPluginError datasources.ErrDatasourceSecretsPluginUserFriendly
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDataSources(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDataSources(c *contextmodel.ReqContext) response.Response {
query := datasources.GetDataSourcesQuery{OrgId: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit} query := datasources.GetDataSourcesQuery{OrgId: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit}
if err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query); err != nil { if err := hs.DataSourcesService.GetDataSources(c.Req.Context(), &query); err != nil {
@@ -106,7 +106,7 @@ func (hs *HTTPServer) GetDataSources(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDataSourceById(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDataSourceById(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", nil) return response.Error(http.StatusBadRequest, "id is invalid", nil)
@@ -151,7 +151,7 @@ func (hs *HTTPServer) GetDataSourceById(c *models.ReqContext) response.Response
// 404: notFoundError // 404: notFoundError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteDataSourceById(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDataSourceById(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -202,7 +202,7 @@ func (hs *HTTPServer) DeleteDataSourceById(c *models.ReqContext) response.Respon
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDataSourceByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDataSourceByUID(c *contextmodel.ReqContext) response.Response {
ds, err := hs.getRawDataSourceByUID(c.Req.Context(), web.Params(c.Req)[":uid"], c.OrgID) ds, err := hs.getRawDataSourceByUID(c.Req.Context(), web.Params(c.Req)[":uid"], c.OrgID)
if err != nil { if err != nil {
@@ -233,7 +233,7 @@ func (hs *HTTPServer) GetDataSourceByUID(c *models.ReqContext) response.Response
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteDataSourceByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDataSourceByUID(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
if uid == "" { if uid == "" {
@@ -283,7 +283,7 @@ func (hs *HTTPServer) DeleteDataSourceByUID(c *models.ReqContext) response.Respo
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteDataSourceByName(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDataSourceByName(c *contextmodel.ReqContext) response.Response {
name := web.Params(c.Req)[":name"] name := web.Params(c.Req)[":name"]
if name == "" { if name == "" {
@@ -365,7 +365,7 @@ func validateJSONData(jsonData *simplejson.Json, cfg *setting.Cfg) error {
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AddDataSource(c *models.ReqContext) response.Response { func (hs *HTTPServer) AddDataSource(c *contextmodel.ReqContext) response.Response {
cmd := datasources.AddDataSourceCommand{} cmd := datasources.AddDataSourceCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -431,7 +431,7 @@ func (hs *HTTPServer) AddDataSource(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateDataSourceByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateDataSourceByID(c *contextmodel.ReqContext) response.Response {
cmd := datasources.UpdateDataSourceCommand{} cmd := datasources.UpdateDataSourceCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -475,7 +475,7 @@ func (hs *HTTPServer) UpdateDataSourceByID(c *models.ReqContext) response.Respon
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateDataSourceByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateDataSourceByUID(c *contextmodel.ReqContext) response.Response {
cmd := datasources.UpdateDataSourceCommand{} cmd := datasources.UpdateDataSourceCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -500,7 +500,7 @@ func (hs *HTTPServer) UpdateDataSourceByUID(c *models.ReqContext) response.Respo
return hs.updateDataSourceByID(c, ds, cmd) return hs.updateDataSourceByID(c, ds, cmd)
} }
func (hs *HTTPServer) updateDataSourceByID(c *models.ReqContext, ds *datasources.DataSource, cmd datasources.UpdateDataSourceCommand) response.Response { func (hs *HTTPServer) updateDataSourceByID(c *contextmodel.ReqContext, ds *datasources.DataSource, cmd datasources.UpdateDataSourceCommand) response.Response {
if ds.ReadOnly { if ds.ReadOnly {
return response.Error(403, "Cannot update read-only data source", nil) return response.Error(403, "Cannot update read-only data source", nil)
} }
@@ -579,7 +579,7 @@ func (hs *HTTPServer) getRawDataSourceByUID(ctx context.Context, uid string, org
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDataSourceByName(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDataSourceByName(c *contextmodel.ReqContext) response.Response {
query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgId: c.OrgID} query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgId: c.OrgID}
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil { if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
@@ -606,7 +606,7 @@ func (hs *HTTPServer) GetDataSourceByName(c *models.ReqContext) response.Respons
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetDataSourceIdByName(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDataSourceIdByName(c *contextmodel.ReqContext) response.Response {
query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgId: c.OrgID} query := datasources.GetDataSourceQuery{Name: web.Params(c.Req)[":name"], OrgId: c.OrgID}
if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil { if err := hs.DataSourcesService.GetDataSource(c.Req.Context(), &query); err != nil {
@@ -639,7 +639,7 @@ func (hs *HTTPServer) GetDataSourceIdByName(c *models.ReqContext) response.Respo
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CallDatasourceResource(c *models.ReqContext) { func (hs *HTTPServer) CallDatasourceResource(c *contextmodel.ReqContext) {
datasourceID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) datasourceID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
c.JsonApiErr(http.StatusBadRequest, "id is invalid", nil) c.JsonApiErr(http.StatusBadRequest, "id is invalid", nil)
@@ -675,7 +675,7 @@ func (hs *HTTPServer) CallDatasourceResource(c *models.ReqContext) {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CallDatasourceResourceWithUID(c *models.ReqContext) { func (hs *HTTPServer) CallDatasourceResourceWithUID(c *contextmodel.ReqContext) {
dsUID := web.Params(c.Req)[":uid"] dsUID := web.Params(c.Req)[":uid"]
if !util.IsValidShortUID(dsUID) { if !util.IsValidShortUID(dsUID) {
c.JsonApiErr(http.StatusBadRequest, "UID is invalid", nil) c.JsonApiErr(http.StatusBadRequest, "UID is invalid", nil)
@@ -746,7 +746,7 @@ func (hs *HTTPServer) convertModelToDtos(ctx context.Context, ds *datasources.Da
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CheckDatasourceHealthWithUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) CheckDatasourceHealthWithUID(c *contextmodel.ReqContext) response.Response {
dsUID := web.Params(c.Req)[":uid"] dsUID := web.Params(c.Req)[":uid"]
if !util.IsValidShortUID(dsUID) { if !util.IsValidShortUID(dsUID) {
return response.Error(http.StatusBadRequest, "UID is invalid", nil) return response.Error(http.StatusBadRequest, "UID is invalid", nil)
@@ -776,7 +776,7 @@ func (hs *HTTPServer) CheckDatasourceHealthWithUID(c *models.ReqContext) respons
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CheckDatasourceHealth(c *models.ReqContext) response.Response { func (hs *HTTPServer) CheckDatasourceHealth(c *contextmodel.ReqContext) response.Response {
datasourceID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) datasourceID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", nil) return response.Error(http.StatusBadRequest, "id is invalid", nil)
@@ -792,7 +792,7 @@ func (hs *HTTPServer) CheckDatasourceHealth(c *models.ReqContext) response.Respo
return hs.checkDatasourceHealth(c, ds) return hs.checkDatasourceHealth(c, ds)
} }
func (hs *HTTPServer) checkDatasourceHealth(c *models.ReqContext, ds *datasources.DataSource) response.Response { func (hs *HTTPServer) checkDatasourceHealth(c *contextmodel.ReqContext, ds *datasources.DataSource) response.Response {
plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), ds.Type) plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), ds.Type)
if !exists { if !exists {
return response.Error(http.StatusInternalServerError, "Unable to find datasource plugin", nil) return response.Error(http.StatusInternalServerError, "Unable to find datasource plugin", nil)

View File

@@ -16,11 +16,11 @@ import (
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl"
"github.com/grafana/grafana/pkg/services/accesscontrol/actest" "github.com/grafana/grafana/pkg/services/accesscontrol/actest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/datasources/permissions" "github.com/grafana/grafana/pkg/services/datasources/permissions"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -88,7 +88,7 @@ func TestAddDataSource_InvalidURL(t *testing.T) {
Cfg: setting.NewCfg(), Cfg: setting.NewCfg(),
} }
sc.m.Post(sc.url, routing.Wrap(func(c *models.ReqContext) response.Response { sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{ c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
Name: "Test", Name: "Test",
Url: "invalid:url", Url: "invalid:url",
@@ -119,7 +119,7 @@ func TestAddDataSource_URLWithoutProtocol(t *testing.T) {
sc := setupScenarioContext(t, "/api/datasources") sc := setupScenarioContext(t, "/api/datasources")
sc.m.Post(sc.url, routing.Wrap(func(c *models.ReqContext) response.Response { sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{ c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
Name: name, Name: name,
Url: url, Url: url,
@@ -149,7 +149,7 @@ func TestAddDataSource_InvalidJSONData(t *testing.T) {
jsonData := simplejson.New() jsonData := simplejson.New()
jsonData.Set("httpHeaderName1", hs.Cfg.AuthProxyHeaderName) jsonData.Set("httpHeaderName1", hs.Cfg.AuthProxyHeaderName)
sc.m.Post(sc.url, routing.Wrap(func(c *models.ReqContext) response.Response { sc.m.Post(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{ c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
Name: "Test", Name: "Test",
Url: "localhost:5432", Url: "localhost:5432",
@@ -173,7 +173,7 @@ func TestUpdateDataSource_InvalidURL(t *testing.T) {
} }
sc := setupScenarioContext(t, "/api/datasources/1234") sc := setupScenarioContext(t, "/api/datasources/1234")
sc.m.Put(sc.url, routing.Wrap(func(c *models.ReqContext) response.Response { sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{ c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
Name: "Test", Name: "Test",
Url: "invalid:url", Url: "invalid:url",
@@ -201,7 +201,7 @@ func TestUpdateDataSource_InvalidJSONData(t *testing.T) {
jsonData := simplejson.New() jsonData := simplejson.New()
jsonData.Set("httpHeaderName1", hs.Cfg.AuthProxyHeaderName) jsonData.Set("httpHeaderName1", hs.Cfg.AuthProxyHeaderName)
sc.m.Put(sc.url, routing.Wrap(func(c *models.ReqContext) response.Response { sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{ c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
Name: "Test", Name: "Test",
Url: "localhost:5432", Url: "localhost:5432",
@@ -233,7 +233,7 @@ func TestUpdateDataSource_URLWithoutProtocol(t *testing.T) {
sc := setupScenarioContext(t, "/api/datasources/1234") sc := setupScenarioContext(t, "/api/datasources/1234")
sc.m.Put(sc.url, routing.Wrap(func(c *models.ReqContext) response.Response { sc.m.Put(sc.url, routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{ c.Req.Body = mockRequestBody(datasources.AddDataSourceCommand{
Name: name, Name: name,
Url: url, Url: url,

View File

@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/api/apierrors" "github.com/grafana/grafana/pkg/api/apierrors"
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder" "github.com/grafana/grafana/pkg/services/folder"
@@ -31,7 +31,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetFolders(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolders(c *contextmodel.ReqContext) response.Response {
var folders []*folder.Folder var folders []*folder.Folder
var err error var err error
if hs.Features.IsEnabled(featuremgmt.FlagNestedFolders) { if hs.Features.IsEnabled(featuremgmt.FlagNestedFolders) {
@@ -82,7 +82,7 @@ func (hs *HTTPServer) GetFolders(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetFolderByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolderByUID(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
folder, err := hs.folderService.Get(c.Req.Context(), &folder.GetFolderQuery{OrgID: c.OrgID, UID: &uid, SignedInUser: c.SignedInUser}) folder, err := hs.folderService.Get(c.Req.Context(), &folder.GetFolderQuery{OrgID: c.OrgID, UID: &uid, SignedInUser: c.SignedInUser})
if err != nil { if err != nil {
@@ -109,7 +109,7 @@ func (hs *HTTPServer) GetFolderByUID(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetFolderByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolderByID(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -139,7 +139,7 @@ func (hs *HTTPServer) GetFolderByID(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CreateFolder(c *models.ReqContext) response.Response { func (hs *HTTPServer) CreateFolder(c *contextmodel.ReqContext) response.Response {
cmd := folder.CreateFolderCommand{} cmd := folder.CreateFolderCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -167,7 +167,7 @@ func (hs *HTTPServer) CreateFolder(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, hs.newToFolderDto(c, g, folder)) return response.JSON(http.StatusOK, hs.newToFolderDto(c, g, folder))
} }
func (hs *HTTPServer) MoveFolder(c *models.ReqContext) response.Response { func (hs *HTTPServer) MoveFolder(c *contextmodel.ReqContext) response.Response {
if hs.Features.IsEnabled(featuremgmt.FlagNestedFolders) { if hs.Features.IsEnabled(featuremgmt.FlagNestedFolders) {
cmd := folder.MoveFolderCommand{} cmd := folder.MoveFolderCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
@@ -205,7 +205,7 @@ func (hs *HTTPServer) MoveFolder(c *models.ReqContext) response.Response {
// 404: notFoundError // 404: notFoundError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateFolder(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateFolder(c *contextmodel.ReqContext) response.Response {
cmd := folder.UpdateFolderCommand{} cmd := folder.UpdateFolderCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -240,7 +240,7 @@ func (hs *HTTPServer) UpdateFolder(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteFolder(c *models.ReqContext) response.Response { // temporarily adding this function to HTTPServer, will be removed from HTTPServer when librarypanels featuretoggle is removed func (hs *HTTPServer) DeleteFolder(c *contextmodel.ReqContext) response.Response { // temporarily adding this function to HTTPServer, will be removed from HTTPServer when librarypanels featuretoggle is removed
err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c.Req.Context(), c.SignedInUser, web.Params(c.Req)[":uid"]) err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c.Req.Context(), c.SignedInUser, web.Params(c.Req)[":uid"])
if err != nil { if err != nil {
if errors.Is(err, libraryelements.ErrFolderHasConnectedLibraryElements) { if errors.Is(err, libraryelements.ErrFolderHasConnectedLibraryElements) {
@@ -258,7 +258,7 @@ func (hs *HTTPServer) DeleteFolder(c *models.ReqContext) response.Response { //
return response.JSON(http.StatusOK, "") return response.JSON(http.StatusOK, "")
} }
func (hs *HTTPServer) newToFolderDto(c *models.ReqContext, g guardian.DashboardGuardian, folder *folder.Folder) dtos.Folder { func (hs *HTTPServer) newToFolderDto(c *contextmodel.ReqContext, g guardian.DashboardGuardian, folder *folder.Folder) dtos.Folder {
canEdit, _ := g.CanEdit() canEdit, _ := g.CanEdit()
canSave, _ := g.CanSave() canSave, _ := g.CanSave()
canAdmin, _ := g.CanAdmin() canAdmin, _ := g.CanAdmin()
@@ -293,7 +293,7 @@ func (hs *HTTPServer) newToFolderDto(c *models.ReqContext, g guardian.DashboardG
} }
} }
func (hs *HTTPServer) searchFolders(c *models.ReqContext) ([]*folder.Folder, error) { func (hs *HTTPServer) searchFolders(c *contextmodel.ReqContext) ([]*folder.Folder, error) {
searchQuery := search.Query{ searchQuery := search.Query{
SignedInUser: c.SignedInUser, SignedInUser: c.SignedInUser,
DashboardIds: make([]int64, 0), DashboardIds: make([]int64, 0),

View File

@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/api/apierrors" "github.com/grafana/grafana/pkg/api/apierrors"
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/folder" "github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@@ -26,7 +26,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetFolderPermissionList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolderPermissionList(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
folder, err := hs.folderService.Get(c.Req.Context(), &folder.GetFolderQuery{OrgID: c.OrgID, UID: &uid, SignedInUser: c.SignedInUser}) folder, err := hs.folderService.Get(c.Req.Context(), &folder.GetFolderQuery{OrgID: c.OrgID, UID: &uid, SignedInUser: c.SignedInUser})
@@ -83,7 +83,7 @@ func (hs *HTTPServer) GetFolderPermissionList(c *models.ReqContext) response.Res
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateFolderPermissions(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateFolderPermissions(c *contextmodel.ReqContext) response.Response {
apiCmd := dtos.UpdateDashboardACLCommand{} apiCmd := dtos.UpdateDashboardACLCommand{}
if err := web.Bind(c.Req, &apiCmd); err != nil { if err := web.Bind(c.Req, &apiCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -13,8 +13,8 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/models"
accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" accesscontrolmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
service "github.com/grafana/grafana/pkg/services/dashboards/service" service "github.com/grafana/grafana/pkg/services/dashboards/service"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
@@ -361,7 +361,7 @@ func updateFolderPermissionScenario(t *testing.T, ctx updatePermissionContext, h
t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) { t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) {
sc := setupScenarioContext(t, ctx.url) sc := setupScenarioContext(t, ctx.url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(ctx.cmd) c.Req.Body = mockRequestBody(ctx.cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -18,6 +18,7 @@ import (
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/actest" "github.com/grafana/grafana/pkg/services/accesscontrol/actest"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder" "github.com/grafana/grafana/pkg/services/folder"
@@ -256,7 +257,7 @@ func createFolderScenario(t *testing.T, desc string, url string, routePattern st
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -286,7 +287,7 @@ func updateFolderScenario(t *testing.T, desc string, url string, routePattern st
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -15,8 +15,8 @@ import (
"github.com/grafana/grafana/pkg/api/frontendlogging" "github.com/grafana/grafana/pkg/api/frontendlogging"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -89,7 +89,7 @@ func logSentryEventScenario(t *testing.T, desc string, event frontendlogging.Fro
loggingHandler := NewFrontendLogMessageHandler(sourceMapStore) loggingHandler := NewFrontendLogMessageHandler(sourceMapStore)
handler := routing.Wrap(func(c *models.ReqContext) response.Response { handler := routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
c.Req.Body = mockRequestBody(event) c.Req.Body = mockRequestBody(event)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
@@ -162,7 +162,7 @@ func logGrafanaJavascriptAgentEventScenario(t *testing.T, desc string, event fro
loggingHandler := GrafanaJavascriptAgentLogMessageHandler(sourceMapStore) loggingHandler := GrafanaJavascriptAgentLogMessageHandler(sourceMapStore)
handler := routing.Wrap(func(c *models.ReqContext) response.Response { handler := routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
c.Req.Body = mockRequestBody(event) c.Req.Body = mockRequestBody(event)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")

View File

@@ -5,11 +5,11 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) PostFrontendMetrics(c *models.ReqContext) response.Response { func (hs *HTTPServer) PostFrontendMetrics(c *contextmodel.ReqContext) response.Response {
cmd := metrics.PostFrontendMetricsCommand{} cmd := metrics.PostFrontendMetricsCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/licensing" "github.com/grafana/grafana/pkg/services/licensing"
@@ -18,7 +18,7 @@ import (
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
func (hs *HTTPServer) GetFrontendSettings(c *models.ReqContext) { func (hs *HTTPServer) GetFrontendSettings(c *contextmodel.ReqContext) {
settings, err := hs.getFrontendSettingsMap(c) settings, err := hs.getFrontendSettingsMap(c)
if err != nil { if err != nil {
c.JsonApiErr(400, "Failed to get frontend settings", err) c.JsonApiErr(400, "Failed to get frontend settings", err)
@@ -29,7 +29,7 @@ func (hs *HTTPServer) GetFrontendSettings(c *models.ReqContext) {
} }
// getFrontendSettingsMap returns a json object with all the settings needed for front end initialisation. // getFrontendSettingsMap returns a json object with all the settings needed for front end initialisation.
func (hs *HTTPServer) getFrontendSettingsMap(c *models.ReqContext) (map[string]interface{}, error) { func (hs *HTTPServer) getFrontendSettingsMap(c *contextmodel.ReqContext) (map[string]interface{}, error) {
enabledPlugins, err := hs.enabledPlugins(c.Req.Context(), c.OrgID) enabledPlugins, err := hs.enabledPlugins(c.Req.Context(), c.OrgID)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -231,7 +231,7 @@ func isSupportBundlesEnabled(hs *HTTPServer) bool {
hs.Features.IsEnabled(featuremgmt.FlagSupportBundles) hs.Features.IsEnabled(featuremgmt.FlagSupportBundles)
} }
func (hs *HTTPServer) getFSDataSources(c *models.ReqContext, enabledPlugins EnabledPlugins) (map[string]plugins.DataSourceDTO, error) { func (hs *HTTPServer) getFSDataSources(c *contextmodel.ReqContext, enabledPlugins EnabledPlugins) (map[string]plugins.DataSourceDTO, error) {
orgDataSources := make([]*datasources.DataSource, 0) orgDataSources := make([]*datasources.DataSource, 0)
if c.OrgID != 0 { if c.OrgID != 0 {
query := datasources.GetDataSourcesQuery{OrgId: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit} query := datasources.GetDataSourcesQuery{OrgId: c.OrgID, DataSourceLimit: hs.Cfg.DataSourceLimit}

View File

@@ -8,7 +8,7 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/infra/log" "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/util" "github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/util/proxyutil" "github.com/grafana/grafana/pkg/util/proxyutil"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -45,7 +45,7 @@ func ReverseProxyGnetReq(logger log.Logger, proxyPath string, version string, gr
return proxyutil.NewReverseProxy(logger, director) return proxyutil.NewReverseProxy(logger, director)
} }
func (hs *HTTPServer) ProxyGnetRequest(c *models.ReqContext) { func (hs *HTTPServer) ProxyGnetRequest(c *contextmodel.ReqContext) {
proxyPath := web.Params(c.Req)["*"] proxyPath := web.Params(c.Req)["*"]
proxy := ReverseProxyGnetReq(c.Logger, proxyPath, hs.Cfg.BuildVersion, hs.Cfg.GrafanaComAPIURL) proxy := ReverseProxyGnetReq(c.Logger, proxyPath, hs.Cfg.BuildVersion, hs.Cfg.GrafanaComAPIURL)
proxy.Transport = grafanaComProxyTransport proxy.Transport = grafanaComProxyTransport

View File

@@ -6,8 +6,8 @@ import (
"strings" "strings"
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder" "github.com/grafana/grafana/pkg/services/folder"
@@ -21,7 +21,7 @@ const (
darkName = "dark" darkName = "dark"
) )
func (hs *HTTPServer) editorInAnyFolder(c *models.ReqContext) bool { func (hs *HTTPServer) editorInAnyFolder(c *contextmodel.ReqContext) bool {
hasEditPermissionInFoldersQuery := folder.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser} hasEditPermissionInFoldersQuery := folder.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser}
hasEditPermissionInFoldersQueryResult, err := hs.DashboardService.HasEditPermissionInFolders(c.Req.Context(), &hasEditPermissionInFoldersQuery) hasEditPermissionInFoldersQueryResult, err := hs.DashboardService.HasEditPermissionInFolders(c.Req.Context(), &hasEditPermissionInFoldersQuery)
if err != nil { if err != nil {
@@ -30,7 +30,7 @@ func (hs *HTTPServer) editorInAnyFolder(c *models.ReqContext) bool {
return hasEditPermissionInFoldersQueryResult return hasEditPermissionInFoldersQueryResult
} }
func (hs *HTTPServer) setIndexViewData(c *models.ReqContext) (*dtos.IndexViewData, error) { func (hs *HTTPServer) setIndexViewData(c *contextmodel.ReqContext) (*dtos.IndexViewData, error) {
hasAccess := ac.HasAccess(hs.AccessControl, c) hasAccess := ac.HasAccess(hs.AccessControl, c)
hasEditPerm := hasAccess(hs.editorInAnyFolder, ac.EvalAny(ac.EvalPermission(dashboards.ActionDashboardsCreate), ac.EvalPermission(dashboards.ActionFoldersCreate))) hasEditPerm := hasAccess(hs.editorInAnyFolder, ac.EvalAny(ac.EvalPermission(dashboards.ActionDashboardsCreate), ac.EvalPermission(dashboards.ActionFoldersCreate)))
@@ -167,7 +167,7 @@ func (hs *HTTPServer) setIndexViewData(c *models.ReqContext) (*dtos.IndexViewDat
return &data, nil return &data, nil
} }
func (hs *HTTPServer) Index(c *models.ReqContext) { func (hs *HTTPServer) Index(c *contextmodel.ReqContext) {
data, err := hs.setIndexViewData(c) data, err := hs.setIndexViewData(c)
if err != nil { if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err) c.Handle(hs.Cfg, 500, "Failed to get settings", err)
@@ -176,7 +176,7 @@ func (hs *HTTPServer) Index(c *models.ReqContext) {
c.HTML(http.StatusOK, "index", data) c.HTML(http.StatusOK, "index", data)
} }
func (hs *HTTPServer) NotFoundHandler(c *models.ReqContext) { func (hs *HTTPServer) NotFoundHandler(c *contextmodel.ReqContext) {
if c.IsApiRequest() { if c.IsApiRequest() {
c.JsonApiErr(404, "Not found", nil) c.JsonApiErr(404, "Not found", nil)
return return

View File

@@ -11,6 +11,7 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "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/ldap"
"github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/services/multildap"
@@ -117,7 +118,7 @@ func (user *LDAPUserDTO) FetchOrgs(ctx context.Context, orga org.Service) error
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) ReloadLDAPCfg(c *models.ReqContext) response.Response { func (hs *HTTPServer) ReloadLDAPCfg(c *contextmodel.ReqContext) response.Response {
if !ldap.IsEnabled() { if !ldap.IsEnabled() {
return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil) return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil)
} }
@@ -143,7 +144,7 @@ func (hs *HTTPServer) ReloadLDAPCfg(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetLDAPStatus(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetLDAPStatus(c *contextmodel.ReqContext) response.Response {
if !ldap.IsEnabled() { if !ldap.IsEnabled() {
return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil) return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil)
} }
@@ -196,7 +197,7 @@ func (hs *HTTPServer) GetLDAPStatus(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PostSyncUserWithLDAP(c *models.ReqContext) response.Response { func (hs *HTTPServer) PostSyncUserWithLDAP(c *contextmodel.ReqContext) response.Response {
if !ldap.IsEnabled() { if !ldap.IsEnabled() {
return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil) return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil)
} }
@@ -292,7 +293,7 @@ func (hs *HTTPServer) PostSyncUserWithLDAP(c *models.ReqContext) response.Respon
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserFromLDAP(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserFromLDAP(c *contextmodel.ReqContext) response.Response {
if !ldap.IsEnabled() { if !ldap.IsEnabled() {
return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil) return response.Error(http.StatusBadRequest, "LDAP is not enabled", nil)
} }

View File

@@ -17,6 +17,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/auth/authtest" "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/ldap"
"github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/login/logintest"
@@ -71,7 +72,7 @@ func getUserFromLDAPContext(t *testing.T, requestURL string, searchOrgRst []*org
hs := &HTTPServer{Cfg: setting.NewCfg(), ldapGroups: ldap.ProvideGroupsService(), orgService: &orgtest.FakeOrgService{ExpectedOrgs: searchOrgRst}} hs := &HTTPServer{Cfg: setting.NewCfg(), ldapGroups: ldap.ProvideGroupsService(), orgService: &orgtest.FakeOrgService{ExpectedOrgs: searchOrgRst}}
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
return hs.GetUserFromLDAP(c) return hs.GetUserFromLDAP(c)
}) })
@@ -318,7 +319,7 @@ func getLDAPStatusContext(t *testing.T) *scenarioContext {
hs := &HTTPServer{Cfg: setting.NewCfg()} hs := &HTTPServer{Cfg: setting.NewCfg()}
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
return hs.GetLDAPStatus(c) return hs.GetLDAPStatus(c)
}) })
@@ -386,7 +387,7 @@ func postSyncUserWithLDAPContext(t *testing.T, requestURL string, preHook func(*
userService: userService, userService: userService,
} }
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
return hs.PostSyncUserWithLDAP(c) return hs.PostSyncUserWithLDAP(c)
}) })

View File

@@ -18,6 +18,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/authn" "github.com/grafana/grafana/pkg/services/authn"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/featuremgmt" "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/secrets"
@@ -80,7 +81,7 @@ func (hs *HTTPServer) CookieOptionsFromCfg() cookies.CookieOptions {
} }
} }
func (hs *HTTPServer) LoginView(c *models.ReqContext) { func (hs *HTTPServer) LoginView(c *contextmodel.ReqContext) {
viewData, err := setIndexViewData(hs, c) viewData, err := setIndexViewData(hs, c)
if err != nil { if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err) c.Handle(hs.Cfg, 500, "Failed to get settings", err)
@@ -139,7 +140,7 @@ func (hs *HTTPServer) LoginView(c *models.ReqContext) {
c.HTML(http.StatusOK, getViewIndex(), viewData) c.HTML(http.StatusOK, getViewIndex(), viewData)
} }
func (hs *HTTPServer) tryAutoLogin(c *models.ReqContext) bool { func (hs *HTTPServer) tryAutoLogin(c *contextmodel.ReqContext) bool {
samlAutoLogin := hs.samlAutoLoginEnabled() samlAutoLogin := hs.samlAutoLoginEnabled()
oauthInfos := hs.SocialService.GetOAuthInfoProviders() oauthInfos := hs.SocialService.GetOAuthInfoProviders()
@@ -185,7 +186,7 @@ func (hs *HTTPServer) tryAutoLogin(c *models.ReqContext) bool {
return false return false
} }
func (hs *HTTPServer) LoginAPIPing(c *models.ReqContext) response.Response { func (hs *HTTPServer) LoginAPIPing(c *contextmodel.ReqContext) response.Response {
if c.IsSignedIn || c.IsAnonymous { if c.IsSignedIn || c.IsAnonymous {
return response.JSON(http.StatusOK, "Logged in") return response.JSON(http.StatusOK, "Logged in")
} }
@@ -193,7 +194,7 @@ func (hs *HTTPServer) LoginAPIPing(c *models.ReqContext) response.Response {
return response.Error(401, "Unauthorized", nil) return response.Error(401, "Unauthorized", nil)
} }
func (hs *HTTPServer) LoginPost(c *models.ReqContext) response.Response { func (hs *HTTPServer) LoginPost(c *contextmodel.ReqContext) response.Response {
if hs.Features.IsEnabled(featuremgmt.FlagAuthnService) { if hs.Features.IsEnabled(featuremgmt.FlagAuthnService) {
identity, err := hs.authnService.Login(c.Req.Context(), authn.ClientForm, &authn.Request{HTTPRequest: c.Req, Resp: c.Resp}) identity, err := hs.authnService.Login(c.Req.Context(), authn.ClientForm, &authn.Request{HTTPRequest: c.Req, Resp: c.Resp})
if err != nil { if err != nil {
@@ -313,7 +314,7 @@ func (hs *HTTPServer) LoginPost(c *models.ReqContext) response.Response {
return resp return resp
} }
func (hs *HTTPServer) loginUserWithUser(user *user.User, c *models.ReqContext) error { func (hs *HTTPServer) loginUserWithUser(user *user.User, c *contextmodel.ReqContext) error {
if user == nil { if user == nil {
return errors.New("could not login user") return errors.New("could not login user")
} }
@@ -338,7 +339,7 @@ func (hs *HTTPServer) loginUserWithUser(user *user.User, c *models.ReqContext) e
return nil return nil
} }
func (hs *HTTPServer) Logout(c *models.ReqContext) { func (hs *HTTPServer) Logout(c *contextmodel.ReqContext) {
// If SAML is enabled and this is a SAML user use saml logout // If SAML is enabled and this is a SAML user use saml logout
if hs.samlSingleLogoutEnabled() { if hs.samlSingleLogoutEnabled() {
getAuthQuery := models.GetAuthInfoQuery{UserId: c.UserID} getAuthQuery := models.GetAuthInfoQuery{UserId: c.UserID}
@@ -372,7 +373,7 @@ func (hs *HTTPServer) Logout(c *models.ReqContext) {
} }
} }
func (hs *HTTPServer) tryGetEncryptedCookie(ctx *models.ReqContext, cookieName string) (string, bool) { func (hs *HTTPServer) tryGetEncryptedCookie(ctx *contextmodel.ReqContext, cookieName string) (string, bool) {
cookie := ctx.GetCookie(cookieName) cookie := ctx.GetCookie(cookieName)
if cookie == "" { if cookie == "" {
return "", false return "", false
@@ -387,7 +388,7 @@ func (hs *HTTPServer) tryGetEncryptedCookie(ctx *models.ReqContext, cookieName s
return string(decryptedError), err == nil return string(decryptedError), err == nil
} }
func (hs *HTTPServer) trySetEncryptedCookie(ctx *models.ReqContext, cookieName string, value string, maxAge int) error { func (hs *HTTPServer) trySetEncryptedCookie(ctx *contextmodel.ReqContext, cookieName string, value string, maxAge int) error {
encryptedError, err := hs.SecretsService.Encrypt(ctx.Req.Context(), []byte(value), secrets.WithoutScope()) encryptedError, err := hs.SecretsService.Encrypt(ctx.Req.Context(), []byte(value), secrets.WithoutScope())
if err != nil { if err != nil {
return err return err
@@ -398,7 +399,7 @@ func (hs *HTTPServer) trySetEncryptedCookie(ctx *models.ReqContext, cookieName s
return nil return nil
} }
func (hs *HTTPServer) redirectWithError(ctx *models.ReqContext, err error, v ...interface{}) { func (hs *HTTPServer) redirectWithError(ctx *contextmodel.ReqContext, err error, v ...interface{}) {
ctx.Logger.Warn(err.Error(), v...) ctx.Logger.Warn(err.Error(), v...)
if err := hs.trySetEncryptedCookie(ctx, loginErrorCookieName, getLoginExternalError(err), 60); err != nil { if err := hs.trySetEncryptedCookie(ctx, loginErrorCookieName, getLoginExternalError(err), 60); err != nil {
hs.log.Error("Failed to set encrypted cookie", "err", err) hs.log.Error("Failed to set encrypted cookie", "err", err)
@@ -407,7 +408,7 @@ func (hs *HTTPServer) redirectWithError(ctx *models.ReqContext, err error, v ...
ctx.Redirect(hs.Cfg.AppSubURL + "/login") ctx.Redirect(hs.Cfg.AppSubURL + "/login")
} }
func (hs *HTTPServer) RedirectResponseWithError(ctx *models.ReqContext, err error, v ...interface{}) *response.RedirectResponse { func (hs *HTTPServer) RedirectResponseWithError(ctx *contextmodel.ReqContext, err error, v ...interface{}) *response.RedirectResponse {
ctx.Logger.Error(err.Error(), v...) ctx.Logger.Error(err.Error(), v...)
if err := hs.trySetEncryptedCookie(ctx, loginErrorCookieName, getLoginExternalError(err), 60); err != nil { if err := hs.trySetEncryptedCookie(ctx, loginErrorCookieName, getLoginExternalError(err), 60); err != nil {
hs.log.Error("Failed to set encrypted cookie", "err", err) hs.log.Error("Failed to set encrypted cookie", "err", err)

View File

@@ -18,6 +18,7 @@ import (
"github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/login/social"
"github.com/grafana/grafana/pkg/middleware/cookies" "github.com/grafana/grafana/pkg/middleware/cookies"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -68,7 +69,7 @@ func genPKCECode() (string, string, error) {
return string(ascii), pkce, nil return string(ascii), pkce, nil
} }
func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) { func (hs *HTTPServer) OAuthLogin(ctx *contextmodel.ReqContext) {
loginInfo := models.LoginInfo{ loginInfo := models.LoginInfo{
AuthModule: "oauth", AuthModule: "oauth",
} }
@@ -308,7 +309,7 @@ func (hs *HTTPServer) buildExternalUserInfo(token *oauth2.Token, userInfo *socia
// SyncUser syncs a Grafana user profile with the corresponding OAuth profile. // SyncUser syncs a Grafana user profile with the corresponding OAuth profile.
func (hs *HTTPServer) SyncUser( func (hs *HTTPServer) SyncUser(
ctx *models.ReqContext, ctx *contextmodel.ReqContext,
extUser *models.ExternalUserInfo, extUser *models.ExternalUserInfo,
connect social.SocialConnector, connect social.SocialConnector,
) (*user.User, error) { ) (*user.User, error) {
@@ -350,7 +351,7 @@ type LoginError struct {
Err error Err error
} }
func (hs *HTTPServer) handleOAuthLoginError(ctx *models.ReqContext, info models.LoginInfo, err LoginError) { func (hs *HTTPServer) handleOAuthLoginError(ctx *contextmodel.ReqContext, info models.LoginInfo, err LoginError) {
ctx.Handle(hs.Cfg, err.HttpStatus, err.PublicMessage, err.Err) ctx.Handle(hs.Cfg, err.HttpStatus, err.PublicMessage, err.Err)
info.Error = err.Err info.Error = err.Err
@@ -362,7 +363,7 @@ func (hs *HTTPServer) handleOAuthLoginError(ctx *models.ReqContext, info models.
hs.HooksService.RunLoginHook(&info, ctx) hs.HooksService.RunLoginHook(&info, ctx)
} }
func (hs *HTTPServer) handleOAuthLoginErrorWithRedirect(ctx *models.ReqContext, info models.LoginInfo, err error, v ...interface{}) { func (hs *HTTPServer) handleOAuthLoginErrorWithRedirect(ctx *contextmodel.ReqContext, info models.LoginInfo, err error, v ...interface{}) {
hs.redirectWithError(ctx, err, v...) hs.redirectWithError(ctx, err, v...)
info.Error = err info.Error = err

View File

@@ -21,6 +21,7 @@ import (
"github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/login/social"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/authtest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/hooks" "github.com/grafana/grafana/pkg/services/hooks"
"github.com/grafana/grafana/pkg/services/licensing" "github.com/grafana/grafana/pkg/services/licensing"
@@ -40,7 +41,7 @@ func fakeSetIndexViewData(t *testing.T) {
t.Cleanup(func() { t.Cleanup(func() {
setIndexViewData = origSetIndexViewData setIndexViewData = origSetIndexViewData
}) })
setIndexViewData = func(*HTTPServer, *models.ReqContext) (*dtos.IndexViewData, error) { setIndexViewData = func(*HTTPServer, *contextmodel.ReqContext) (*dtos.IndexViewData, error) {
data := &dtos.IndexViewData{ data := &dtos.IndexViewData{
User: &dtos.CurrentUser{}, User: &dtos.CurrentUser{},
Settings: map[string]interface{}{}, Settings: map[string]interface{}{},
@@ -104,7 +105,7 @@ func TestLoginErrorCookieAPIEndpoint(t *testing.T) {
SecretsService: secretsService, SecretsService: secretsService,
} }
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
hs.LoginView(c) hs.LoginView(c)
return response.Empty(http.StatusOK) return response.Empty(http.StatusOK)
}) })
@@ -152,7 +153,7 @@ func TestLoginViewRedirect(t *testing.T) {
} }
hs.Cfg.CookieSecure = true hs.Cfg.CookieSecure = true
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.IsSignedIn = true c.IsSignedIn = true
c.SignedInUser = &user.SignedInUser{ c.SignedInUser = &user.SignedInUser{
UserID: 10, UserID: 10,
@@ -328,7 +329,7 @@ func TestLoginPostRedirect(t *testing.T) {
} }
hs.Cfg.CookieSecure = true hs.Cfg.CookieSecure = true
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Header.Set("Content-Type", "application/json") c.Req.Header.Set("Content-Type", "application/json")
c.Req.Body = io.NopCloser(bytes.NewBufferString(`{"user":"admin","password":"admin"}`)) c.Req.Body = io.NopCloser(bytes.NewBufferString(`{"user":"admin","password":"admin"}`))
return hs.LoginPost(c) return hs.LoginPost(c)
@@ -492,7 +493,7 @@ func TestLoginOAuthRedirect(t *testing.T) {
SocialService: mock, SocialService: mock,
} }
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
hs.LoginView(c) hs.LoginView(c)
return response.Empty(http.StatusOK) return response.Empty(http.StatusOK)
}) })
@@ -518,7 +519,7 @@ func TestLoginInternal(t *testing.T) {
log: log.New("test"), log: log.New("test"),
} }
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.URL.RawQuery = "disableAutoLogin=true" c.Req.URL.RawQuery = "disableAutoLogin=true"
hs.LoginView(c) hs.LoginView(c)
return response.Empty(http.StatusOK) return response.Empty(http.StatusOK)
@@ -570,7 +571,7 @@ func setupAuthProxyLoginTest(t *testing.T, enableLoginToken bool) *scenarioConte
SocialService: &mockSocialService{}, SocialService: &mockSocialService{},
} }
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.IsSignedIn = true c.IsSignedIn = true
c.SignedInUser = &user.SignedInUser{ c.SignedInUser = &user.SignedInUser{
UserID: 10, UserID: 10,
@@ -592,7 +593,7 @@ type loginHookTest struct {
info *models.LoginInfo info *models.LoginInfo
} }
func (r *loginHookTest) LoginHook(loginInfo *models.LoginInfo, req *models.ReqContext) { func (r *loginHookTest) LoginHook(loginInfo *models.LoginInfo, req *contextmodel.ReqContext) {
r.info = loginInfo r.info = loginInfo
} }
@@ -608,7 +609,7 @@ func TestLoginPostRunLokingHook(t *testing.T) {
HooksService: hookService, HooksService: hookService,
} }
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Header.Set("Content-Type", "application/json") c.Req.Header.Set("Content-Type", "application/json")
c.Req.Body = io.NopCloser(bytes.NewBufferString(`{"user":"admin","password":"admin"}`)) c.Req.Body = io.NopCloser(bytes.NewBufferString(`{"user":"admin","password":"admin"}`))
x := hs.LoginPost(c) x := hs.LoginPost(c)

View File

@@ -9,7 +9,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -46,7 +46,7 @@ func (hs *HTTPServer) handleQueryMetricsError(err error) *response.NormalRespons
// 400: badRequestError // 400: badRequestError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) QueryMetricsV2(c *models.ReqContext) response.Response { func (hs *HTTPServer) QueryMetricsV2(c *contextmodel.ReqContext) response.Response {
reqDTO := dtos.MetricRequest{} reqDTO := dtos.MetricRequest{}
if err := web.Bind(c.Req, &reqDTO); err != nil { if err := web.Bind(c.Req, &reqDTO); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -3,9 +3,9 @@ package api
import ( import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
) )
func openapi3(c *models.ReqContext) { func openapi3(c *contextmodel.ReqContext) {
c.HTML(http.StatusOK, "openapi3", nil) c.HTML(http.StatusOK, "openapi3", nil)
} }

View File

@@ -9,7 +9,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -25,7 +25,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetCurrentOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetCurrentOrg(c *contextmodel.ReqContext) response.Response {
return hs.getOrgHelper(c.Req.Context(), c.OrgID) return hs.getOrgHelper(c.Req.Context(), c.OrgID)
} }
@@ -41,7 +41,7 @@ func (hs *HTTPServer) GetCurrentOrg(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgByID(c *contextmodel.ReqContext) response.Response {
orgId, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64) orgId, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "orgId is invalid", err) return response.Error(http.StatusBadRequest, "orgId is invalid", err)
@@ -61,7 +61,7 @@ func (hs *HTTPServer) GetOrgByID(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgByName(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgByName(c *contextmodel.ReqContext) response.Response {
orga, err := hs.orgService.GetByName(c.Req.Context(), &org.GetOrgByNameQuery{Name: web.Params(c.Req)[":name"]}) orga, err := hs.orgService.GetByName(c.Req.Context(), &org.GetOrgByNameQuery{Name: web.Params(c.Req)[":name"]})
if err != nil { if err != nil {
if errors.Is(err, org.ErrOrgNotFound) { if errors.Is(err, org.ErrOrgNotFound) {
@@ -126,7 +126,7 @@ func (hs *HTTPServer) getOrgHelper(ctx context.Context, orgID int64) response.Re
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CreateOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) CreateOrg(c *contextmodel.ReqContext) response.Response {
cmd := org.CreateOrgCommand{} cmd := org.CreateOrgCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -163,7 +163,7 @@ func (hs *HTTPServer) CreateOrg(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateCurrentOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateCurrentOrg(c *contextmodel.ReqContext) response.Response {
form := dtos.UpdateOrgForm{} form := dtos.UpdateOrgForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -184,7 +184,7 @@ func (hs *HTTPServer) UpdateCurrentOrg(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateOrg(c *contextmodel.ReqContext) response.Response {
form := dtos.UpdateOrgForm{} form := dtos.UpdateOrgForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -218,7 +218,7 @@ func (hs *HTTPServer) updateOrgHelper(ctx context.Context, form dtos.UpdateOrgFo
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateCurrentOrgAddress(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateCurrentOrgAddress(c *contextmodel.ReqContext) response.Response {
form := dtos.UpdateOrgAddressForm{} form := dtos.UpdateOrgAddressForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -236,7 +236,7 @@ func (hs *HTTPServer) UpdateCurrentOrgAddress(c *models.ReqContext) response.Res
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateOrgAddress(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateOrgAddress(c *contextmodel.ReqContext) response.Response {
form := dtos.UpdateOrgAddressForm{} form := dtos.UpdateOrgAddressForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -282,7 +282,7 @@ func (hs *HTTPServer) updateOrgAddressHelper(ctx context.Context, form dtos.Upda
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteOrgByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteOrgByID(c *contextmodel.ReqContext) response.Response {
orgID, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64) orgID, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "orgId is invalid", err) return response.Error(http.StatusBadRequest, "orgId is invalid", err)
@@ -314,7 +314,7 @@ func (hs *HTTPServer) DeleteOrgByID(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) SearchOrgs(c *models.ReqContext) response.Response { func (hs *HTTPServer) SearchOrgs(c *contextmodel.ReqContext) response.Response {
perPage := c.QueryInt("perpage") perPage := c.QueryInt("perpage")
if perPage <= 0 { if perPage <= 0 {
perPage = 1000 perPage = 1000

View File

@@ -12,8 +12,8 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/notifications" "github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
tempuser "github.com/grafana/grafana/pkg/services/temp_user" tempuser "github.com/grafana/grafana/pkg/services/temp_user"
@@ -32,7 +32,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetPendingOrgInvites(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPendingOrgInvites(c *contextmodel.ReqContext) response.Response {
query := tempuser.GetTempUsersQuery{OrgID: c.OrgID, Status: tempuser.TmpUserInvitePending} query := tempuser.GetTempUsersQuery{OrgID: c.OrgID, Status: tempuser.TmpUserInvitePending}
queryResult, err := hs.tempUserService.GetTempUsersQuery(c.Req.Context(), &query) queryResult, err := hs.tempUserService.GetTempUsersQuery(c.Req.Context(), &query)
@@ -58,7 +58,7 @@ func (hs *HTTPServer) GetPendingOrgInvites(c *models.ReqContext) response.Respon
// 403: forbiddenError // 403: forbiddenError
// 412: SMTPNotEnabledError // 412: SMTPNotEnabledError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AddOrgInvite(c *models.ReqContext) response.Response { func (hs *HTTPServer) AddOrgInvite(c *contextmodel.ReqContext) response.Response {
inviteDto := dtos.AddInviteForm{} inviteDto := dtos.AddInviteForm{}
if err := web.Bind(c.Req, &inviteDto); err != nil { if err := web.Bind(c.Req, &inviteDto); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -145,7 +145,7 @@ func (hs *HTTPServer) AddOrgInvite(c *models.ReqContext) response.Response {
return response.Success(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail)) return response.Success(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail))
} }
func (hs *HTTPServer) inviteExistingUserToOrg(c *models.ReqContext, user *user.User, inviteDto *dtos.AddInviteForm) response.Response { func (hs *HTTPServer) inviteExistingUserToOrg(c *contextmodel.ReqContext, user *user.User, inviteDto *dtos.AddInviteForm) response.Response {
// user exists, add org role // user exists, add org role
createOrgUserCmd := org.AddOrgUserCommand{OrgID: c.OrgID, UserID: user.ID, Role: inviteDto.Role} createOrgUserCmd := org.AddOrgUserCommand{OrgID: c.OrgID, UserID: user.ID, Role: inviteDto.Role}
if err := hs.orgService.AddOrgUser(c.Req.Context(), &createOrgUserCmd); err != nil { if err := hs.orgService.AddOrgUser(c.Req.Context(), &createOrgUserCmd); err != nil {
@@ -187,7 +187,7 @@ func (hs *HTTPServer) inviteExistingUserToOrg(c *models.ReqContext, user *user.U
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) RevokeInvite(c *models.ReqContext) response.Response { func (hs *HTTPServer) RevokeInvite(c *contextmodel.ReqContext) response.Response {
if ok, rsp := hs.updateTempUserStatus(c.Req.Context(), web.Params(c.Req)[":code"], tempuser.TmpUserRevoked); !ok { if ok, rsp := hs.updateTempUserStatus(c.Req.Context(), web.Params(c.Req)[":code"], tempuser.TmpUserRevoked); !ok {
return rsp return rsp
} }
@@ -198,7 +198,7 @@ func (hs *HTTPServer) RevokeInvite(c *models.ReqContext) response.Response {
// GetInviteInfoByCode gets a pending user invite corresponding to a certain code. // GetInviteInfoByCode gets a pending user invite corresponding to a certain code.
// A response containing an InviteInfo object is returned if the invite is found. // A response containing an InviteInfo object is returned if the invite is found.
// If a (pending) invite is not found, 404 is returned. // If a (pending) invite is not found, 404 is returned.
func (hs *HTTPServer) GetInviteInfoByCode(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetInviteInfoByCode(c *contextmodel.ReqContext) response.Response {
query := tempuser.GetTempUserByCodeQuery{Code: web.Params(c.Req)[":code"]} query := tempuser.GetTempUserByCodeQuery{Code: web.Params(c.Req)[":code"]}
queryResult, err := hs.tempUserService.GetTempUserByCode(c.Req.Context(), &query) queryResult, err := hs.tempUserService.GetTempUserByCode(c.Req.Context(), &query)
if err != nil { if err != nil {
@@ -221,7 +221,7 @@ func (hs *HTTPServer) GetInviteInfoByCode(c *models.ReqContext) response.Respons
}) })
} }
func (hs *HTTPServer) CompleteInvite(c *models.ReqContext) response.Response { func (hs *HTTPServer) CompleteInvite(c *contextmodel.ReqContext) response.Response {
completeInvite := dtos.CompleteInviteForm{} completeInvite := dtos.CompleteInviteForm{}
var err error var err error
if err = web.Bind(c.Req, &completeInvite); err != nil { if err = web.Bind(c.Req, &completeInvite); err != nil {

View File

@@ -11,6 +11,7 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
@@ -32,7 +33,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AddOrgUserToCurrentOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) AddOrgUserToCurrentOrg(c *contextmodel.ReqContext) response.Response {
cmd := org.AddOrgUserCommand{} cmd := org.AddOrgUserCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -55,7 +56,7 @@ func (hs *HTTPServer) AddOrgUserToCurrentOrg(c *models.ReqContext) response.Resp
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AddOrgUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) AddOrgUser(c *contextmodel.ReqContext) response.Response {
cmd := org.AddOrgUserCommand{} cmd := org.AddOrgUserCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -69,7 +70,7 @@ func (hs *HTTPServer) AddOrgUser(c *models.ReqContext) response.Response {
return hs.addOrgUserHelper(c, cmd) return hs.addOrgUserHelper(c, cmd)
} }
func (hs *HTTPServer) addOrgUserHelper(c *models.ReqContext, cmd org.AddOrgUserCommand) response.Response { func (hs *HTTPServer) addOrgUserHelper(c *contextmodel.ReqContext, cmd org.AddOrgUserCommand) response.Response {
if !cmd.Role.IsValid() { if !cmd.Role.IsValid() {
return response.Error(400, "Invalid role specified", nil) return response.Error(400, "Invalid role specified", nil)
} }
@@ -114,7 +115,7 @@ func (hs *HTTPServer) addOrgUserHelper(c *models.ReqContext, cmd org.AddOrgUserC
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgUsersForCurrentOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgUsersForCurrentOrg(c *contextmodel.ReqContext) response.Response {
result, err := hs.searchOrgUsersHelper(c, &org.SearchOrgUsersQuery{ result, err := hs.searchOrgUsersHelper(c, &org.SearchOrgUsersQuery{
OrgID: c.OrgID, OrgID: c.OrgID,
Query: c.Query("query"), Query: c.Query("query"),
@@ -143,7 +144,7 @@ func (hs *HTTPServer) GetOrgUsersForCurrentOrg(c *models.ReqContext) response.Re
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgUsersForCurrentOrgLookup(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgUsersForCurrentOrgLookup(c *contextmodel.ReqContext) response.Response {
orgUsersResult, err := hs.searchOrgUsersHelper(c, &org.SearchOrgUsersQuery{ orgUsersResult, err := hs.searchOrgUsersHelper(c, &org.SearchOrgUsersQuery{
OrgID: c.OrgID, OrgID: c.OrgID,
Query: c.Query("query"), Query: c.Query("query"),
@@ -184,7 +185,7 @@ func (hs *HTTPServer) GetOrgUsersForCurrentOrgLookup(c *models.ReqContext) respo
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgUsers(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgUsers(c *contextmodel.ReqContext) response.Response {
orgId, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64) orgId, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "orgId is invalid", err) return response.Error(http.StatusBadRequest, "orgId is invalid", err)
@@ -219,7 +220,7 @@ func (hs *HTTPServer) GetOrgUsers(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) SearchOrgUsers(c *models.ReqContext) response.Response { func (hs *HTTPServer) SearchOrgUsers(c *contextmodel.ReqContext) response.Response {
orgID, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64) orgID, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "orgId is invalid", err) return response.Error(http.StatusBadRequest, "orgId is invalid", err)
@@ -252,7 +253,7 @@ func (hs *HTTPServer) SearchOrgUsers(c *models.ReqContext) response.Response {
// SearchOrgUsersWithPaging is an HTTP handler to search for org users with paging. // SearchOrgUsersWithPaging is an HTTP handler to search for org users with paging.
// GET /api/org/users/search // GET /api/org/users/search
func (hs *HTTPServer) SearchOrgUsersWithPaging(c *models.ReqContext) response.Response { func (hs *HTTPServer) SearchOrgUsersWithPaging(c *contextmodel.ReqContext) response.Response {
perPage := c.QueryInt("perpage") perPage := c.QueryInt("perpage")
if perPage <= 0 { if perPage <= 0 {
perPage = 1000 perPage = 1000
@@ -279,7 +280,7 @@ func (hs *HTTPServer) SearchOrgUsersWithPaging(c *models.ReqContext) response.Re
return response.JSON(http.StatusOK, result) return response.JSON(http.StatusOK, result)
} }
func (hs *HTTPServer) searchOrgUsersHelper(c *models.ReqContext, query *org.SearchOrgUsersQuery) (*org.SearchOrgUsersQueryResult, error) { func (hs *HTTPServer) searchOrgUsersHelper(c *contextmodel.ReqContext, query *org.SearchOrgUsersQuery) (*org.SearchOrgUsersQueryResult, error) {
result, err := hs.orgService.SearchOrgUsers(c.Req.Context(), query) result, err := hs.orgService.SearchOrgUsers(c.Req.Context(), query)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -335,7 +336,7 @@ func (hs *HTTPServer) searchOrgUsersHelper(c *models.ReqContext, query *org.Sear
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateOrgUserForCurrentOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateOrgUserForCurrentOrg(c *contextmodel.ReqContext) response.Response {
cmd := org.UpdateOrgUserCommand{} cmd := org.UpdateOrgUserCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -362,7 +363,7 @@ func (hs *HTTPServer) UpdateOrgUserForCurrentOrg(c *models.ReqContext) response.
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateOrgUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateOrgUser(c *contextmodel.ReqContext) response.Response {
cmd := org.UpdateOrgUserCommand{} cmd := org.UpdateOrgUserCommand{}
var err error var err error
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
@@ -379,7 +380,7 @@ func (hs *HTTPServer) UpdateOrgUser(c *models.ReqContext) response.Response {
return hs.updateOrgUserHelper(c, cmd) return hs.updateOrgUserHelper(c, cmd)
} }
func (hs *HTTPServer) updateOrgUserHelper(c *models.ReqContext, cmd org.UpdateOrgUserCommand) response.Response { func (hs *HTTPServer) updateOrgUserHelper(c *contextmodel.ReqContext, cmd org.UpdateOrgUserCommand) response.Response {
if !cmd.Role.IsValid() { if !cmd.Role.IsValid() {
return response.Error(400, "Invalid role specified", nil) return response.Error(400, "Invalid role specified", nil)
} }
@@ -409,7 +410,7 @@ func (hs *HTTPServer) updateOrgUserHelper(c *models.ReqContext, cmd org.UpdateOr
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) RemoveOrgUserForCurrentOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) RemoveOrgUserForCurrentOrg(c *contextmodel.ReqContext) response.Response {
userId, err := strconv.ParseInt(web.Params(c.Req)[":userId"], 10, 64) userId, err := strconv.ParseInt(web.Params(c.Req)[":userId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "userId is invalid", err) return response.Error(http.StatusBadRequest, "userId is invalid", err)
@@ -435,7 +436,7 @@ func (hs *HTTPServer) RemoveOrgUserForCurrentOrg(c *models.ReqContext) response.
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) RemoveOrgUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) RemoveOrgUser(c *contextmodel.ReqContext) response.Response {
userId, err := strconv.ParseInt(web.Params(c.Req)[":userId"], 10, 64) userId, err := strconv.ParseInt(web.Params(c.Req)[":userId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "userId is invalid", err) return response.Error(http.StatusBadRequest, "userId is invalid", err)

View File

@@ -8,6 +8,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/notifications" "github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
@@ -16,7 +17,7 @@ import (
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) SendResetPasswordEmail(c *models.ReqContext) response.Response { func (hs *HTTPServer) SendResetPasswordEmail(c *contextmodel.ReqContext) response.Response {
form := dtos.SendResetPasswordEmailForm{} form := dtos.SendResetPasswordEmailForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -54,7 +55,7 @@ func (hs *HTTPServer) SendResetPasswordEmail(c *models.ReqContext) response.Resp
return response.Success("Email sent") return response.Success("Email sent")
} }
func (hs *HTTPServer) ResetPassword(c *models.ReqContext) response.Response { func (hs *HTTPServer) ResetPassword(c *contextmodel.ReqContext) response.Response {
form := dtos.ResetUserPasswordForm{} form := dtos.ResetUserPasswordForm{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -5,12 +5,12 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/playlist" "github.com/grafana/grafana/pkg/services/playlist"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) ValidateOrgPlaylist(c *models.ReqContext) { func (hs *HTTPServer) ValidateOrgPlaylist(c *contextmodel.ReqContext) {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
query := playlist.GetPlaylistByUidQuery{UID: uid, OrgId: c.OrgID} query := playlist.GetPlaylistByUidQuery{UID: uid, OrgId: c.OrgID}
p, err := hs.playlistService.GetWithoutItems(c.Req.Context(), &query) p, err := hs.playlistService.GetWithoutItems(c.Req.Context(), &query)
@@ -38,7 +38,7 @@ func (hs *HTTPServer) ValidateOrgPlaylist(c *models.ReqContext) {
// Responses: // Responses:
// 200: searchPlaylistsResponse // 200: searchPlaylistsResponse
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) SearchPlaylists(c *models.ReqContext) response.Response { func (hs *HTTPServer) SearchPlaylists(c *contextmodel.ReqContext) response.Response {
query := c.Query("query") query := c.Query("query")
limit := c.QueryInt("limit") limit := c.QueryInt("limit")
@@ -70,7 +70,7 @@ func (hs *HTTPServer) SearchPlaylists(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetPlaylist(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPlaylist(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
cmd := playlist.GetPlaylistByUidQuery{UID: uid, OrgId: c.OrgID} cmd := playlist.GetPlaylistByUidQuery{UID: uid, OrgId: c.OrgID}
@@ -92,7 +92,7 @@ func (hs *HTTPServer) GetPlaylist(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetPlaylistItems(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPlaylistItems(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
cmd := playlist.GetPlaylistByUidQuery{UID: uid, OrgId: c.OrgID} cmd := playlist.GetPlaylistByUidQuery{UID: uid, OrgId: c.OrgID}
@@ -114,7 +114,7 @@ func (hs *HTTPServer) GetPlaylistItems(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetPlaylistDashboards(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPlaylistDashboards(c *contextmodel.ReqContext) response.Response {
playlistUID := web.Params(c.Req)[":uid"] playlistUID := web.Params(c.Req)[":uid"]
playlists, err := hs.LoadPlaylistDashboards(c.Req.Context(), c.OrgID, c.SignedInUser, playlistUID) playlists, err := hs.LoadPlaylistDashboards(c.Req.Context(), c.OrgID, c.SignedInUser, playlistUID)
@@ -135,7 +135,7 @@ func (hs *HTTPServer) GetPlaylistDashboards(c *models.ReqContext) response.Respo
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeletePlaylist(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeletePlaylist(c *contextmodel.ReqContext) response.Response {
uid := web.Params(c.Req)[":uid"] uid := web.Params(c.Req)[":uid"]
cmd := playlist.DeletePlaylistCommand{UID: uid, OrgId: c.OrgID} cmd := playlist.DeletePlaylistCommand{UID: uid, OrgId: c.OrgID}
@@ -156,7 +156,7 @@ func (hs *HTTPServer) DeletePlaylist(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CreatePlaylist(c *models.ReqContext) response.Response { func (hs *HTTPServer) CreatePlaylist(c *contextmodel.ReqContext) response.Response {
cmd := playlist.CreatePlaylistCommand{} cmd := playlist.CreatePlaylistCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -181,7 +181,7 @@ func (hs *HTTPServer) CreatePlaylist(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdatePlaylist(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdatePlaylist(c *contextmodel.ReqContext) response.Response {
cmd := playlist.UpdatePlaylistCommand{} cmd := playlist.UpdatePlaylistCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -5,8 +5,8 @@ import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/plugindashboards" "github.com/grafana/grafana/pkg/services/plugindashboards"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -14,7 +14,7 @@ import (
// GetPluginDashboards get plugin dashboards. // GetPluginDashboards get plugin dashboards.
// //
// /api/plugins/:pluginId/dashboards // /api/plugins/:pluginId/dashboards
func (hs *HTTPServer) GetPluginDashboards(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginDashboards(c *contextmodel.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
listReq := &plugindashboards.ListPluginDashboardsRequest{ listReq := &plugindashboards.ListPluginDashboardsRequest{

View File

@@ -9,12 +9,12 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/api/pluginproxy" "github.com/grafana/grafana/pkg/api/pluginproxy"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/pluginsettings" "github.com/grafana/grafana/pkg/services/pluginsettings"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) ProxyPluginRequest(c *models.ReqContext) { func (hs *HTTPServer) ProxyPluginRequest(c *contextmodel.ReqContext) {
var once sync.Once var once sync.Once
var pluginProxyTransport *http.Transport var pluginProxyTransport *http.Transport
once.Do(func() { once.Do(func() {
@@ -63,6 +63,6 @@ func extractProxyPath(originalRawPath string) string {
return pluginProxyPathRegexp.ReplaceAllString(originalRawPath, "") return pluginProxyPathRegexp.ReplaceAllString(originalRawPath, "")
} }
func getProxyPath(c *models.ReqContext) string { func getProxyPath(c *contextmodel.ReqContext) string {
return extractProxyPath(c.Req.URL.EscapedPath()) return extractProxyPath(c.Req.URL.EscapedPath())
} }

View File

@@ -12,8 +12,8 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/plugins/backendplugin"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/util/proxyutil" "github.com/grafana/grafana/pkg/util/proxyutil"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -22,11 +22,11 @@ import (
// CallResource passes a resource call from a plugin to the backend plugin. // CallResource passes a resource call from a plugin to the backend plugin.
// //
// /api/plugins/:pluginId/resources/* // /api/plugins/:pluginId/resources/*
func (hs *HTTPServer) CallResource(c *models.ReqContext) { func (hs *HTTPServer) CallResource(c *contextmodel.ReqContext) {
hs.callPluginResource(c, web.Params(c.Req)[":pluginId"]) hs.callPluginResource(c, web.Params(c.Req)[":pluginId"])
} }
func (hs *HTTPServer) callPluginResource(c *models.ReqContext, pluginID string) { func (hs *HTTPServer) callPluginResource(c *contextmodel.ReqContext, pluginID string) {
pCtx, found, err := hs.PluginContextProvider.Get(c.Req.Context(), pluginID, c.SignedInUser) pCtx, found, err := hs.PluginContextProvider.Get(c.Req.Context(), pluginID, c.SignedInUser)
if err != nil { if err != nil {
c.JsonApiErr(500, "Failed to get plugin settings", err) c.JsonApiErr(500, "Failed to get plugin settings", err)
@@ -48,7 +48,7 @@ func (hs *HTTPServer) callPluginResource(c *models.ReqContext, pluginID string)
} }
} }
func (hs *HTTPServer) callPluginResourceWithDataSource(c *models.ReqContext, pluginID string, ds *datasources.DataSource) { func (hs *HTTPServer) callPluginResourceWithDataSource(c *contextmodel.ReqContext, pluginID string, ds *datasources.DataSource) {
pCtx, found, err := hs.PluginContextProvider.GetWithDataSource(c.Req.Context(), pluginID, c.SignedInUser, ds) pCtx, found, err := hs.PluginContextProvider.GetWithDataSource(c.Req.Context(), pluginID, c.SignedInUser, ds)
if err != nil { if err != nil {
c.JsonApiErr(500, "Failed to get plugin settings", err) c.JsonApiErr(500, "Failed to get plugin settings", err)
@@ -81,7 +81,7 @@ func (hs *HTTPServer) callPluginResourceWithDataSource(c *models.ReqContext, plu
} }
} }
func (hs *HTTPServer) pluginResourceRequest(c *models.ReqContext) (*http.Request, error) { func (hs *HTTPServer) pluginResourceRequest(c *contextmodel.ReqContext) (*http.Request, error) {
clonedReq := c.Req.Clone(c.Req.Context()) clonedReq := c.Req.Clone(c.Req.Context())
rawURL := web.Params(c.Req)["*"] rawURL := web.Params(c.Req)["*"]
if clonedReq.URL.RawQuery != "" { if clonedReq.URL.RawQuery != "" {
@@ -207,7 +207,7 @@ func (hs *HTTPServer) flushStream(stream callResourceClientResponseStream, w htt
} }
} }
func handleCallResourceError(err error, reqCtx *models.ReqContext) { func handleCallResourceError(err error, reqCtx *contextmodel.ReqContext) {
if errors.Is(err, backendplugin.ErrPluginUnavailable) { if errors.Is(err, backendplugin.ErrPluginUnavailable) {
reqCtx.JsonApiErr(503, "Plugin unavailable", err) reqCtx.JsonApiErr(503, "Plugin unavailable", err)
return return

View File

@@ -17,8 +17,8 @@ import (
"github.com/grafana/grafana/pkg/infra/httpclient" "github.com/grafana/grafana/pkg/infra/httpclient"
glog "github.com/grafana/grafana/pkg/infra/log" glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/oauthtoken" "github.com/grafana/grafana/pkg/services/oauthtoken"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -33,7 +33,7 @@ var (
type DataSourceProxy struct { type DataSourceProxy struct {
ds *datasources.DataSource ds *datasources.DataSource
ctx *models.ReqContext ctx *contextmodel.ReqContext
targetUrl *url.URL targetUrl *url.URL
proxyPath string proxyPath string
matchedRoute *plugins.Route matchedRoute *plugins.Route
@@ -50,7 +50,7 @@ type httpClient interface {
} }
// NewDataSourceProxy creates a new Datasource proxy // NewDataSourceProxy creates a new Datasource proxy
func NewDataSourceProxy(ds *datasources.DataSource, pluginRoutes []*plugins.Route, ctx *models.ReqContext, func NewDataSourceProxy(ds *datasources.DataSource, pluginRoutes []*plugins.Route, ctx *contextmodel.ReqContext,
proxyPath string, cfg *setting.Cfg, clientProvider httpclient.Provider, proxyPath string, cfg *setting.Cfg, clientProvider httpclient.Provider,
oAuthTokenService oauthtoken.OAuthTokenService, dsService datasources.DataSourceService, oAuthTokenService oauthtoken.OAuthTokenService, dsService datasources.DataSourceService,
tracer tracing.Tracer) (*DataSourceProxy, error) { tracer tracing.Tracer) (*DataSourceProxy, error) {
@@ -343,7 +343,7 @@ func (proxy *DataSourceProxy) logRequest() {
"body", body) "body", body)
} }
func checkWhiteList(c *models.ReqContext, host string) bool { func checkWhiteList(c *contextmodel.ReqContext, host string) bool {
if host != "" && len(setting.DataProxyWhiteList) > 0 { if host != "" && len(setting.DataProxyWhiteList) > 0 {
if _, exists := setting.DataProxyWhiteList[host]; !exists { if _, exists := setting.DataProxyWhiteList[host]; !exists {
c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil) c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)

View File

@@ -28,6 +28,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" 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" "github.com/grafana/grafana/pkg/services/datasources"
datasourceservice "github.com/grafana/grafana/pkg/services/datasources/service" datasourceservice "github.com/grafana/grafana/pkg/services/datasources/service"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
@@ -128,10 +129,10 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
}, },
} }
setUp := func() (*models.ReqContext, *http.Request) { setUp := func() (*contextmodel.ReqContext, *http.Request) {
req, err := http.NewRequest("GET", "http://localhost/asd", nil) req, err := http.NewRequest("GET", "http://localhost/asd", nil)
require.NoError(t, err) require.NoError(t, err)
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor}, SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor},
} }
@@ -286,7 +287,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
req, err := http.NewRequest("GET", "http://localhost/asd", nil) req, err := http.NewRequest("GET", "http://localhost/asd", nil)
require.NoError(t, err) require.NoError(t, err)
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor}, SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor},
} }
@@ -372,7 +373,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
t.Run("When proxying graphite", func(t *testing.T) { t.Run("When proxying graphite", func(t *testing.T) {
var routes []*plugins.Route var routes []*plugins.Route
ds := &datasources.DataSource{Url: "htttp://graphite:8080", Type: datasources.DS_GRAPHITE} ds := &datasources.DataSource{Url: "htttp://graphite:8080", Type: datasources.DS_GRAPHITE}
ctx := &models.ReqContext{} ctx := &contextmodel.ReqContext{}
sqlStore := db.InitTestDB(t) sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore()) secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
@@ -401,7 +402,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
User: "user", User: "user",
} }
ctx := &models.ReqContext{} ctx := &contextmodel.ReqContext{}
var routes []*plugins.Route var routes []*plugins.Route
sqlStore := db.InitTestDB(t) sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore()) secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
@@ -429,7 +430,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
JsonData: json, JsonData: json,
} }
ctx := &models.ReqContext{} ctx := &contextmodel.ReqContext{}
var routes []*plugins.Route var routes []*plugins.Route
sqlStore := db.InitTestDB(t) sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore()) secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
@@ -461,7 +462,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
JsonData: json, JsonData: json,
} }
ctx := &models.ReqContext{} ctx := &contextmodel.ReqContext{}
var pluginRoutes []*plugins.Route var pluginRoutes []*plugins.Route
sqlStore := db.InitTestDB(t) sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore()) secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
@@ -488,7 +489,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
Type: "custom-datasource", Type: "custom-datasource",
Url: "http://host/root/", Url: "http://host/root/",
} }
ctx := &models.ReqContext{} ctx := &contextmodel.ReqContext{}
var routes []*plugins.Route var routes []*plugins.Route
sqlStore := db.InitTestDB(t) sqlStore := db.InitTestDB(t)
secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore()) secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore())
@@ -522,7 +523,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
req, err := http.NewRequest("GET", "http://localhost/asd", nil) req, err := http.NewRequest("GET", "http://localhost/asd", nil)
require.NoError(t, err) require.NoError(t, err)
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{UserID: 1}, SignedInUser: &user.SignedInUser{UserID: 1},
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
} }
@@ -563,7 +564,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
t.Run("When SendUserHeader config is enabled", func(t *testing.T) { t.Run("When SendUserHeader config is enabled", func(t *testing.T) {
req := getDatasourceProxiedRequest( req := getDatasourceProxiedRequest(
t, t,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -576,7 +577,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
t.Run("When SendUserHeader config is disabled", func(t *testing.T) { t.Run("When SendUserHeader config is disabled", func(t *testing.T) {
req := getDatasourceProxiedRequest( req := getDatasourceProxiedRequest(
t, t,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -590,7 +591,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
t.Run("When SendUserHeader config is enabled but user is anonymous", func(t *testing.T) { t.Run("When SendUserHeader config is enabled but user is anonymous", func(t *testing.T) {
req := getDatasourceProxiedRequest( req := getDatasourceProxiedRequest(
t, t,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{IsAnonymous: true}, SignedInUser: &user.SignedInUser{IsAnonymous: true},
}, },
&setting.Cfg{SendUserHeader: true}, &setting.Cfg{SendUserHeader: true},
@@ -635,7 +636,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
writeCb func(w http.ResponseWriter, r *http.Request) writeCb func(w http.ResponseWriter, r *http.Request)
} }
setUp := func(t *testing.T, cfgs ...setUpCfg) (*models.ReqContext, *datasources.DataSource) { setUp := func(t *testing.T, cfgs ...setUpCfg) (*contextmodel.ReqContext, *datasources.DataSource) {
writeErr = nil writeErr = nil
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -668,7 +669,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
} }
} }
return &models.ReqContext{ return &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{}, SignedInUser: &user.SignedInUser{},
Context: &web.Context{ Context: &web.Context{
Req: httptest.NewRequest("GET", "/render", nil), Req: httptest.NewRequest("GET", "/render", nil),
@@ -822,7 +823,7 @@ func TestDataSourceProxy_requestHandling(t *testing.T) {
} }
func TestNewDataSourceProxy_InvalidURL(t *testing.T) { func TestNewDataSourceProxy_InvalidURL(t *testing.T) {
ctx := models.ReqContext{ ctx := contextmodel.ReqContext{
Context: &web.Context{}, Context: &web.Context{},
SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor}, SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor},
} }
@@ -846,7 +847,7 @@ func TestNewDataSourceProxy_InvalidURL(t *testing.T) {
} }
func TestNewDataSourceProxy_ProtocolLessURL(t *testing.T) { func TestNewDataSourceProxy_ProtocolLessURL(t *testing.T) {
ctx := models.ReqContext{ ctx := contextmodel.ReqContext{
Context: &web.Context{}, Context: &web.Context{},
SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor}, SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor},
} }
@@ -871,7 +872,7 @@ func TestNewDataSourceProxy_ProtocolLessURL(t *testing.T) {
// Test wth MSSQL type data sources. // Test wth MSSQL type data sources.
func TestNewDataSourceProxy_MSSQL(t *testing.T) { func TestNewDataSourceProxy_MSSQL(t *testing.T) {
ctx := models.ReqContext{ ctx := contextmodel.ReqContext{
Context: &web.Context{}, Context: &web.Context{},
SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor}, SignedInUser: &user.SignedInUser{OrgRole: org.RoleEditor},
} }
@@ -926,7 +927,7 @@ func TestNewDataSourceProxy_MSSQL(t *testing.T) {
} }
// getDatasourceProxiedRequest is a helper for easier setup of tests based on global config and ReqContext. // getDatasourceProxiedRequest is a helper for easier setup of tests based on global config and ReqContext.
func getDatasourceProxiedRequest(t *testing.T, ctx *models.ReqContext, cfg *setting.Cfg) *http.Request { func getDatasourceProxiedRequest(t *testing.T, ctx *contextmodel.ReqContext, cfg *setting.Cfg) *http.Request {
ds := &datasources.DataSource{ ds := &datasources.DataSource{
Type: "custom", Type: "custom",
Url: "http://host/root/", Url: "http://host/root/",
@@ -1052,7 +1053,7 @@ func createAuthTest(t *testing.T, secretsStore secretskvs.SecretsKVStore, dsType
} }
func runDatasourceAuthTest(t *testing.T, secretsService secrets.Service, secretsStore secretskvs.SecretsKVStore, cfg *setting.Cfg, test *testCase) { func runDatasourceAuthTest(t *testing.T, secretsService secrets.Service, secretsStore secretskvs.SecretsKVStore, cfg *setting.Cfg, test *testCase) {
ctx := &models.ReqContext{} ctx := &contextmodel.ReqContext{}
tracer := tracing.InitializeTracerForTest() tracer := tracing.InitializeTracerForTest()
var routes []*plugins.Route var routes []*plugins.Route
@@ -1089,10 +1090,10 @@ func Test_PathCheck(t *testing.T) {
} }
tracer := tracing.InitializeTracerForTest() tracer := tracing.InitializeTracerForTest()
setUp := func() (*models.ReqContext, *http.Request) { setUp := func() (*contextmodel.ReqContext, *http.Request) {
req, err := http.NewRequest("GET", "http://localhost/asd", nil) req, err := http.NewRequest("GET", "http://localhost/asd", nil)
require.NoError(t, err) require.NoError(t, err)
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
SignedInUser: &user.SignedInUser{OrgRole: org.RoleViewer}, SignedInUser: &user.SignedInUser{OrgRole: org.RoleViewer},
} }

View File

@@ -8,8 +8,8 @@ import (
"net/url" "net/url"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/pluginsettings" "github.com/grafana/grafana/pkg/services/pluginsettings"
"github.com/grafana/grafana/pkg/services/secrets" "github.com/grafana/grafana/pkg/services/secrets"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -22,7 +22,7 @@ import (
type PluginProxy struct { type PluginProxy struct {
ps *pluginsettings.DTO ps *pluginsettings.DTO
pluginRoutes []*plugins.Route pluginRoutes []*plugins.Route
ctx *models.ReqContext ctx *contextmodel.ReqContext
proxyPath string proxyPath string
matchedRoute *plugins.Route matchedRoute *plugins.Route
cfg *setting.Cfg cfg *setting.Cfg
@@ -32,7 +32,7 @@ type PluginProxy struct {
} }
// NewPluginProxy creates a plugin proxy. // NewPluginProxy creates a plugin proxy.
func NewPluginProxy(ps *pluginsettings.DTO, routes []*plugins.Route, ctx *models.ReqContext, func NewPluginProxy(ps *pluginsettings.DTO, routes []*plugins.Route, ctx *contextmodel.ReqContext,
proxyPath string, cfg *setting.Cfg, secretsService secrets.Service, tracer tracing.Tracer, proxyPath string, cfg *setting.Cfg, secretsService secrets.Service, tracer tracing.Tracer,
transport *http.Transport) (*PluginProxy, error) { transport *http.Transport) (*PluginProxy, error) {
return &PluginProxy{ return &PluginProxy{

View File

@@ -10,8 +10,8 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/pluginsettings" "github.com/grafana/grafana/pkg/services/pluginsettings"
"github.com/grafana/grafana/pkg/services/secrets" "github.com/grafana/grafana/pkg/services/secrets"
@@ -49,7 +49,7 @@ func TestPluginProxy(t *testing.T) {
}, },
}, },
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -72,7 +72,7 @@ func TestPluginProxy(t *testing.T) {
t, t,
&pluginsettings.DTO{}, &pluginsettings.DTO{},
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -96,7 +96,7 @@ func TestPluginProxy(t *testing.T) {
t, t,
&pluginsettings.DTO{}, &pluginsettings.DTO{},
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -119,7 +119,7 @@ func TestPluginProxy(t *testing.T) {
t, t,
&pluginsettings.DTO{}, &pluginsettings.DTO{},
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{IsAnonymous: true}, SignedInUser: &user.SignedInUser{IsAnonymous: true},
Context: &web.Context{ Context: &web.Context{
Req: httpReq, Req: httpReq,
@@ -150,7 +150,7 @@ func TestPluginProxy(t *testing.T) {
}, },
}, },
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -178,7 +178,7 @@ func TestPluginProxy(t *testing.T) {
t, t,
&pluginsettings.DTO{}, &pluginsettings.DTO{},
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -216,7 +216,7 @@ func TestPluginProxy(t *testing.T) {
SecureJSONData: encryptedJsonData, SecureJSONData: encryptedJsonData,
}, },
secretsService, secretsService,
&models.ReqContext{ &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{ SignedInUser: &user.SignedInUser{
Login: "test_user", Login: "test_user",
}, },
@@ -250,7 +250,7 @@ func TestPluginProxy(t *testing.T) {
}, },
} }
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{}, SignedInUser: &user.SignedInUser{},
Context: &web.Context{ Context: &web.Context{
Req: httptest.NewRequest("GET", "/", nil), Req: httptest.NewRequest("GET", "/", nil),
@@ -388,7 +388,7 @@ func TestPluginProxyRoutes(t *testing.T) {
responseWriter := web.NewResponseWriter("GET", httptest.NewRecorder()) responseWriter := web.NewResponseWriter("GET", httptest.NewRecorder())
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
SignedInUser: &user.SignedInUser{}, SignedInUser: &user.SignedInUser{},
Context: &web.Context{ Context: &web.Context{
Req: httptest.NewRequest("GET", tc.proxyPath, nil), Req: httptest.NewRequest("GET", tc.proxyPath, nil),
@@ -420,7 +420,7 @@ func TestPluginProxyRoutes(t *testing.T) {
} }
// getPluginProxiedRequest is a helper for easier setup of tests based on global config and ReqContext. // getPluginProxiedRequest is a helper for easier setup of tests based on global config and ReqContext.
func getPluginProxiedRequest(t *testing.T, ps *pluginsettings.DTO, secretsService secrets.Service, ctx *models.ReqContext, cfg *setting.Cfg, route *plugins.Route) *http.Request { func getPluginProxiedRequest(t *testing.T, ps *pluginsettings.DTO, secretsService secrets.Service, ctx *contextmodel.ReqContext, cfg *setting.Cfg, route *plugins.Route) *http.Request {
// insert dummy route if none is specified // insert dummy route if none is specified
if route == nil { if route == nil {
route = &plugins.Route{ route = &plugins.Route{

View File

@@ -18,12 +18,12 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/plugins/backendplugin"
"github.com/grafana/grafana/pkg/plugins/repo" "github.com/grafana/grafana/pkg/plugins/repo"
"github.com/grafana/grafana/pkg/plugins/storage" "github.com/grafana/grafana/pkg/plugins/storage"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
@@ -33,7 +33,7 @@ import (
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) GetPluginList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginList(c *contextmodel.ReqContext) response.Response {
typeFilter := c.Query("type") typeFilter := c.Query("type")
enabledFilter := c.Query("enabled") enabledFilter := c.Query("enabled")
embeddedFilter := c.Query("embedded") embeddedFilter := c.Query("embedded")
@@ -158,7 +158,7 @@ func (hs *HTTPServer) GetPluginList(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, result) return response.JSON(http.StatusOK, result)
} }
func (hs *HTTPServer) GetPluginSettingByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginSettingByID(c *contextmodel.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID) plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID)
@@ -227,7 +227,7 @@ func (hs *HTTPServer) GetPluginSettingByID(c *models.ReqContext) response.Respon
return response.JSON(http.StatusOK, dto) return response.JSON(http.StatusOK, dto)
} }
func (hs *HTTPServer) UpdatePluginSetting(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdatePluginSetting(c *contextmodel.ReqContext) response.Response {
cmd := pluginsettings.UpdatePluginSettingCmd{} cmd := pluginsettings.UpdatePluginSettingCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -256,7 +256,7 @@ func (hs *HTTPServer) UpdatePluginSetting(c *models.ReqContext) response.Respons
return response.Success("Plugin settings updated") return response.Success("Plugin settings updated")
} }
func (hs *HTTPServer) GetPluginMarkdown(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginMarkdown(c *contextmodel.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
name := web.Params(c.Req)[":name"] name := web.Params(c.Req)[":name"]
@@ -286,7 +286,7 @@ func (hs *HTTPServer) GetPluginMarkdown(c *models.ReqContext) response.Response
// CollectPluginMetrics collect metrics from a plugin. // CollectPluginMetrics collect metrics from a plugin.
// //
// /api/plugins/:pluginId/metrics // /api/plugins/:pluginId/metrics
func (hs *HTTPServer) CollectPluginMetrics(c *models.ReqContext) response.Response { func (hs *HTTPServer) CollectPluginMetrics(c *contextmodel.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
resp, err := hs.pluginClient.CollectMetrics(c.Req.Context(), &backend.CollectMetricsRequest{PluginContext: backend.PluginContext{PluginID: pluginID}}) resp, err := hs.pluginClient.CollectMetrics(c.Req.Context(), &backend.CollectMetricsRequest{PluginContext: backend.PluginContext{PluginID: pluginID}})
if err != nil { if err != nil {
@@ -302,7 +302,7 @@ func (hs *HTTPServer) CollectPluginMetrics(c *models.ReqContext) response.Respon
// getPluginAssets returns public plugin assets (images, JS, etc.) // getPluginAssets returns public plugin assets (images, JS, etc.)
// //
// /public/plugins/:pluginId/* // /public/plugins/:pluginId/*
func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) { func (hs *HTTPServer) getPluginAssets(c *contextmodel.ReqContext) {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID) plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID)
if !exists { if !exists {
@@ -359,7 +359,7 @@ func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {
// CheckHealth returns the health of a plugin. // CheckHealth returns the health of a plugin.
// /api/plugins/:pluginId/health // /api/plugins/:pluginId/health
func (hs *HTTPServer) CheckHealth(c *models.ReqContext) response.Response { func (hs *HTTPServer) CheckHealth(c *contextmodel.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
pCtx, found, err := hs.PluginContextProvider.Get(c.Req.Context(), pluginID, c.SignedInUser) pCtx, found, err := hs.PluginContextProvider.Get(c.Req.Context(), pluginID, c.SignedInUser)
@@ -401,11 +401,11 @@ func (hs *HTTPServer) CheckHealth(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, payload) return response.JSON(http.StatusOK, payload)
} }
func (hs *HTTPServer) GetPluginErrorsList(_ *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginErrorsList(_ *contextmodel.ReqContext) response.Response {
return response.JSON(http.StatusOK, hs.pluginErrorResolver.PluginErrors()) return response.JSON(http.StatusOK, hs.pluginErrorResolver.PluginErrors())
} }
func (hs *HTTPServer) InstallPlugin(c *models.ReqContext) response.Response { func (hs *HTTPServer) InstallPlugin(c *contextmodel.ReqContext) response.Response {
dto := dtos.InstallPluginCommand{} dto := dtos.InstallPluginCommand{}
if err := web.Bind(c.Req, &dto); err != nil { if err := web.Bind(c.Req, &dto); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -444,7 +444,7 @@ func (hs *HTTPServer) InstallPlugin(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, []byte{}) return response.JSON(http.StatusOK, []byte{})
} }
func (hs *HTTPServer) UninstallPlugin(c *models.ReqContext) response.Response { func (hs *HTTPServer) UninstallPlugin(c *contextmodel.ReqContext) response.Response {
pluginID := web.Params(c.Req)[":pluginId"] pluginID := web.Params(c.Req)[":pluginId"]
err := hs.pluginInstaller.Remove(c.Req.Context(), pluginID) err := hs.pluginInstaller.Remove(c.Req.Context(), pluginID)

View File

@@ -20,9 +20,9 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/log/logtest" "github.com/grafana/grafana/pkg/infra/log/logtest"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/pluginsettings" "github.com/grafana/grafana/pkg/services/pluginsettings"
@@ -392,7 +392,7 @@ func pluginAssetScenario(t *testing.T, desc string, url string, urlPattern strin
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = func(c *models.ReqContext) { sc.defaultHandler = func(c *contextmodel.ReqContext) {
sc.context = c sc.context = c
hs.getPluginAssets(c) hs.getPluginAssets(c)
} }

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/kinds/preferences" "github.com/grafana/grafana/pkg/kinds/preferences"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
pref "github.com/grafana/grafana/pkg/services/preference" pref "github.com/grafana/grafana/pkg/services/preference"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -20,7 +20,7 @@ const (
) )
// POST /api/preferences/set-home-dash // POST /api/preferences/set-home-dash
func (hs *HTTPServer) SetHomeDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) SetHomeDashboard(c *contextmodel.ReqContext) response.Response {
cmd := pref.SavePreferenceCommand{} cmd := pref.SavePreferenceCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -61,7 +61,7 @@ func (hs *HTTPServer) SetHomeDashboard(c *models.ReqContext) response.Response {
// 200: getPreferencesResponse // 200: getPreferencesResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserPreferences(c *contextmodel.ReqContext) response.Response {
return hs.getPreferencesFor(c.Req.Context(), c.OrgID, c.UserID, 0) return hs.getPreferencesFor(c.Req.Context(), c.OrgID, c.UserID, 0)
} }
@@ -125,7 +125,7 @@ func (hs *HTTPServer) getPreferencesFor(ctx context.Context, orgID, userID, team
// 400: badRequestError // 400: badRequestError
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateUserPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateUserPreferences(c *contextmodel.ReqContext) response.Response {
dtoCmd := dtos.UpdatePrefsCmd{} dtoCmd := dtos.UpdatePrefsCmd{}
if err := web.Bind(c.Req, &dtoCmd); err != nil { if err := web.Bind(c.Req, &dtoCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -182,7 +182,7 @@ func (hs *HTTPServer) updatePreferencesFor(ctx context.Context, orgID, userID, t
// 400: badRequestError // 400: badRequestError
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PatchUserPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) PatchUserPreferences(c *contextmodel.ReqContext) response.Response {
dtoCmd := dtos.PatchPrefsCmd{} dtoCmd := dtos.PatchPrefsCmd{}
if err := web.Bind(c.Req, &dtoCmd); err != nil { if err := web.Bind(c.Req, &dtoCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -241,7 +241,7 @@ func (hs *HTTPServer) patchPreferencesFor(ctx context.Context, orgID, userID, te
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgPreferences(c *contextmodel.ReqContext) response.Response {
return hs.getPreferencesFor(c.Req.Context(), c.OrgID, 0, 0) return hs.getPreferencesFor(c.Req.Context(), c.OrgID, 0, 0)
} }
@@ -255,7 +255,7 @@ func (hs *HTTPServer) GetOrgPreferences(c *models.ReqContext) response.Response
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateOrgPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateOrgPreferences(c *contextmodel.ReqContext) response.Response {
dtoCmd := dtos.UpdatePrefsCmd{} dtoCmd := dtos.UpdatePrefsCmd{}
if err := web.Bind(c.Req, &dtoCmd); err != nil { if err := web.Bind(c.Req, &dtoCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -274,7 +274,7 @@ func (hs *HTTPServer) UpdateOrgPreferences(c *models.ReqContext) response.Respon
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) PatchOrgPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) PatchOrgPreferences(c *contextmodel.ReqContext) response.Response {
dtoCmd := dtos.PatchPrefsCmd{} dtoCmd := dtos.PatchPrefsCmd{}
if err := web.Bind(c.Req, &dtoCmd); err != nil { if err := web.Bind(c.Req, &dtoCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -5,7 +5,7 @@ import (
"strconv" "strconv"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/services/quota"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -22,7 +22,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetCurrentOrgQuotas(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetCurrentOrgQuotas(c *contextmodel.ReqContext) response.Response {
return hs.getOrgQuotasHelper(c, c.OrgID) return hs.getOrgQuotasHelper(c, c.OrgID)
} }
@@ -38,7 +38,7 @@ func (hs *HTTPServer) GetCurrentOrgQuotas(c *models.ReqContext) response.Respons
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetOrgQuotas(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgQuotas(c *contextmodel.ReqContext) response.Response {
orgId, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64) orgId, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64)
if err != nil { if err != nil {
return response.Err(quota.ErrBadRequest.Errorf("orgId is invalid: %w", err)) return response.Err(quota.ErrBadRequest.Errorf("orgId is invalid: %w", err))
@@ -46,7 +46,7 @@ func (hs *HTTPServer) GetOrgQuotas(c *models.ReqContext) response.Response {
return hs.getOrgQuotasHelper(c, orgId) return hs.getOrgQuotasHelper(c, orgId)
} }
func (hs *HTTPServer) getOrgQuotasHelper(c *models.ReqContext, orgID int64) response.Response { func (hs *HTTPServer) getOrgQuotasHelper(c *contextmodel.ReqContext, orgID int64) response.Response {
q, err := hs.QuotaService.GetQuotasByScope(c.Req.Context(), quota.OrgScope, orgID) q, err := hs.QuotaService.GetQuotasByScope(c.Req.Context(), quota.OrgScope, orgID)
if err != nil { if err != nil {
return response.ErrOrFallback(http.StatusInternalServerError, "failed to get quota", err) return response.ErrOrFallback(http.StatusInternalServerError, "failed to get quota", err)
@@ -69,7 +69,7 @@ func (hs *HTTPServer) getOrgQuotasHelper(c *models.ReqContext, orgID int64) resp
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateOrgQuota(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateOrgQuota(c *contextmodel.ReqContext) response.Response {
cmd := quota.UpdateQuotaCmd{} cmd := quota.UpdateQuotaCmd{}
var err error var err error
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
@@ -113,7 +113,7 @@ func (hs *HTTPServer) UpdateOrgQuota(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserQuotas(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserQuotas(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Err(quota.ErrBadRequest.Errorf("id is invalid: %w", err)) return response.Err(quota.ErrBadRequest.Errorf("id is invalid: %w", err))
@@ -142,7 +142,7 @@ func (hs *HTTPServer) GetUserQuotas(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateUserQuota(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateUserQuota(c *contextmodel.ReqContext) response.Response {
cmd := quota.UpdateQuotaCmd{} cmd := quota.UpdateQuotaCmd{}
var err error var err error
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {

View File

@@ -8,12 +8,13 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func (hs *HTTPServer) RenderToPng(c *models.ReqContext) { func (hs *HTTPServer) RenderToPng(c *contextmodel.ReqContext) {
queryReader, err := util.NewURLQueryReader(c.Req.URL) queryReader, err := util.NewURLQueryReader(c.Req.URL)
if err != nil { if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", err) c.Handle(hs.Cfg, 400, "Render parameters error", err)

View File

@@ -11,7 +11,7 @@ import (
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
) )
@@ -19,7 +19,7 @@ import (
// Response is an HTTP response interface. // Response is an HTTP response interface.
type Response interface { type Response interface {
// WriteTo writes to a context. // WriteTo writes to a context.
WriteTo(ctx *models.ReqContext) WriteTo(ctx *contextmodel.ReqContext)
// Body gets the response's body. // Body gets the response's body.
Body() []byte Body() []byte
// Status gets the response's status. // Status gets the response's status.
@@ -77,7 +77,7 @@ func (r *NormalResponse) ErrMessage() string {
return r.errMessage return r.errMessage
} }
func (r *NormalResponse) WriteTo(ctx *models.ReqContext) { func (r *NormalResponse) WriteTo(ctx *contextmodel.ReqContext) {
if r.err != nil { if r.err != nil {
v := map[string]interface{}{} v := map[string]interface{}{}
traceID := tracing.TraceIDFromContext(ctx.Req.Context(), false) traceID := tracing.TraceIDFromContext(ctx.Req.Context(), false)
@@ -132,7 +132,7 @@ func (r StreamingResponse) Body() []byte {
// WriteTo writes the response to the provided context. // WriteTo writes the response to the provided context.
// Required to implement api.Response. // Required to implement api.Response.
func (r StreamingResponse) WriteTo(ctx *models.ReqContext) { func (r StreamingResponse) WriteTo(ctx *contextmodel.ReqContext) {
header := ctx.Resp.Header() header := ctx.Resp.Header()
for k, v := range r.header { for k, v := range r.header {
header[k] = v header[k] = v
@@ -155,7 +155,7 @@ type RedirectResponse struct {
} }
// WriteTo writes to a response. // WriteTo writes to a response.
func (r *RedirectResponse) WriteTo(ctx *models.ReqContext) { func (r *RedirectResponse) WriteTo(ctx *contextmodel.ReqContext) {
ctx.Redirect(r.location) ctx.Redirect(r.location)
} }

View File

@@ -7,17 +7,17 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
type ( type (
handlerStd = func(http.ResponseWriter, *http.Request) handlerStd = func(http.ResponseWriter, *http.Request)
handlerStdCtx = func(http.ResponseWriter, *http.Request, *web.Context) handlerStdCtx = func(http.ResponseWriter, *http.Request, *web.Context)
handlerStdReqCtx = func(http.ResponseWriter, *http.Request, *models.ReqContext) handlerStdReqCtx = func(http.ResponseWriter, *http.Request, *contextmodel.ReqContext)
handlerReqCtx = func(*models.ReqContext) handlerReqCtx = func(*contextmodel.ReqContext)
handlerReqCtxRes = func(*models.ReqContext) Response handlerReqCtxRes = func(*contextmodel.ReqContext) Response
handlerCtx = func(*web.Context) handlerCtx = func(*web.Context)
) )
@@ -67,11 +67,11 @@ func webCtx(w http.ResponseWriter, r *http.Request) *web.Context {
return ctx return ctx
} }
func reqCtx(w http.ResponseWriter, r *http.Request) *models.ReqContext { func reqCtx(w http.ResponseWriter, r *http.Request) *contextmodel.ReqContext {
wCtx := webCtx(w, r) wCtx := webCtx(w, r)
reqCtx, ok := wCtx.Req.Context().Value(ctxkey.Key{}).(*models.ReqContext) reqCtx, ok := wCtx.Req.Context().Value(ctxkey.Key{}).(*contextmodel.ReqContext)
if !ok { if !ok {
panic("no *models.ReqContext found") panic("no *contextmodel.ReqContext found")
} }
return reqCtx return reqCtx
} }

View File

@@ -2,7 +2,7 @@ package routing
import ( import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -12,8 +12,8 @@ var (
} }
) )
func Wrap(handler func(c *models.ReqContext) response.Response) web.Handler { func Wrap(handler func(c *contextmodel.ReqContext) response.Response) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if res := handler(c); res != nil { if res := handler(c); res != nil {
res.WriteTo(c) res.WriteTo(c)
} }

View File

@@ -8,6 +8,7 @@ import (
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/search" "github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -20,7 +21,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 422: unprocessableEntityError // 422: unprocessableEntityError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) Search(c *models.ReqContext) response.Response { func (hs *HTTPServer) Search(c *contextmodel.ReqContext) response.Response {
query := c.Query("query") query := c.Query("query")
tags := c.QueryStrings("tag") tags := c.QueryStrings("tag")
starred := c.Query("starred") starred := c.Query("starred")
@@ -94,7 +95,7 @@ func (hs *HTTPServer) Search(c *models.ReqContext) response.Response {
return hs.searchHitsWithMetadata(c, searchQuery.Result) return hs.searchHitsWithMetadata(c, searchQuery.Result)
} }
func (hs *HTTPServer) searchHitsWithMetadata(c *models.ReqContext, hits models.HitList) response.Response { func (hs *HTTPServer) searchHitsWithMetadata(c *contextmodel.ReqContext, hits models.HitList) response.Response {
folderUIDs := make(map[string]bool) folderUIDs := make(map[string]bool)
dashboardUIDs := make(map[string]bool) dashboardUIDs := make(map[string]bool)
@@ -136,7 +137,7 @@ func (hs *HTTPServer) searchHitsWithMetadata(c *models.ReqContext, hits models.H
// Responses: // Responses:
// 200: listSortOptionsResponse // 200: listSortOptionsResponse
// 401: unauthorisedError // 401: unauthorisedError
func (hs *HTTPServer) ListSortOptions(c *models.ReqContext) response.Response { func (hs *HTTPServer) ListSortOptions(c *contextmodel.ReqContext) response.Response {
opts := hs.SearchService.SortOptions() opts := hs.SearchService.SortOptions()
res := []util.DynMap{} res := []util.DynMap{}

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/shorturls" "github.com/grafana/grafana/pkg/services/shorturls"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@@ -15,7 +15,7 @@ import (
) )
// createShortURL handles requests to create short URLs. // createShortURL handles requests to create short URLs.
func (hs *HTTPServer) createShortURL(c *models.ReqContext) response.Response { func (hs *HTTPServer) createShortURL(c *contextmodel.ReqContext) response.Response {
cmd := dtos.CreateShortURLCmd{} cmd := dtos.CreateShortURLCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Err(shorturls.ErrShortURLBadRequest.Errorf("bad request data: %w", err)) return response.Err(shorturls.ErrShortURLBadRequest.Errorf("bad request data: %w", err))
@@ -37,7 +37,7 @@ func (hs *HTTPServer) createShortURL(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, dto) return response.JSON(http.StatusOK, dto)
} }
func (hs *HTTPServer) redirectFromShortURL(c *models.ReqContext) { func (hs *HTTPServer) redirectFromShortURL(c *contextmodel.ReqContext) {
shortURLUID := web.Params(c.Req)[":uid"] shortURLUID := web.Params(c.Req)[":uid"]
if !util.IsValidShortUID(shortURLUID) { if !util.IsValidShortUID(shortURLUID) {

View File

@@ -10,7 +10,7 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/log" "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/shorturls" "github.com/grafana/grafana/pkg/services/shorturls"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -61,7 +61,7 @@ func createShortURLScenario(t *testing.T, desc string, url string, routePattern
} }
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -10,7 +10,7 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/events" "github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
tempuser "github.com/grafana/grafana/pkg/services/temp_user" tempuser "github.com/grafana/grafana/pkg/services/temp_user"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -19,7 +19,7 @@ import (
) )
// GET /api/user/signup/options // GET /api/user/signup/options
func GetSignUpOptions(c *models.ReqContext) response.Response { func GetSignUpOptions(c *contextmodel.ReqContext) response.Response {
return response.JSON(http.StatusOK, util.DynMap{ return response.JSON(http.StatusOK, util.DynMap{
"verifyEmailEnabled": setting.VerifyEmailEnabled, "verifyEmailEnabled": setting.VerifyEmailEnabled,
"autoAssignOrg": setting.AutoAssignOrg, "autoAssignOrg": setting.AutoAssignOrg,
@@ -27,7 +27,7 @@ func GetSignUpOptions(c *models.ReqContext) response.Response {
} }
// POST /api/user/signup // POST /api/user/signup
func (hs *HTTPServer) SignUp(c *models.ReqContext) response.Response { func (hs *HTTPServer) SignUp(c *contextmodel.ReqContext) response.Response {
form := dtos.SignUpForm{} form := dtos.SignUpForm{}
var err error var err error
if err = web.Bind(c.Req, &form); err != nil { if err = web.Bind(c.Req, &form); err != nil {
@@ -75,7 +75,7 @@ func (hs *HTTPServer) SignUp(c *models.ReqContext) response.Response {
return response.JSON(http.StatusOK, util.DynMap{"status": "SignUpCreated"}) return response.JSON(http.StatusOK, util.DynMap{"status": "SignUpCreated"})
} }
func (hs *HTTPServer) SignUpStep2(c *models.ReqContext) response.Response { func (hs *HTTPServer) SignUpStep2(c *contextmodel.ReqContext) response.Response {
form := dtos.SignUpStep2Form{} form := dtos.SignUpStep2Form{}
if err := web.Bind(c.Req, &form); err != nil { if err := web.Bind(c.Req, &form); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -3,9 +3,9 @@ package api
import ( import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
) )
func swaggerUI(c *models.ReqContext) { func swaggerUI(c *contextmodel.ReqContext) {
c.HTML(http.StatusOK, "swagger", nil) c.HTML(http.StatusOK, "swagger", nil)
} }

View File

@@ -7,7 +7,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/team" "github.com/grafana/grafana/pkg/services/team"
@@ -25,7 +25,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) CreateTeam(c *models.ReqContext) response.Response { func (hs *HTTPServer) CreateTeam(c *contextmodel.ReqContext) response.Response {
cmd := team.CreateTeamCommand{} cmd := team.CreateTeamCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -78,7 +78,7 @@ func (hs *HTTPServer) CreateTeam(c *models.ReqContext) response.Response {
// 404: notFoundError // 404: notFoundError
// 409: conflictError // 409: conflictError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateTeam(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateTeam(c *contextmodel.ReqContext) response.Response {
cmd := team.UpdateTeamCommand{} cmd := team.UpdateTeamCommand{}
var err error var err error
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
@@ -116,7 +116,7 @@ func (hs *HTTPServer) UpdateTeam(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) DeleteTeamByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteTeamByID(c *contextmodel.ReqContext) response.Response {
orgID := c.OrgID orgID := c.OrgID
teamID, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64) teamID, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64)
if err != nil { if err != nil {
@@ -148,7 +148,7 @@ func (hs *HTTPServer) DeleteTeamByID(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) SearchTeams(c *models.ReqContext) response.Response { func (hs *HTTPServer) SearchTeams(c *contextmodel.ReqContext) response.Response {
perPage := c.QueryInt("perpage") perPage := c.QueryInt("perpage")
if perPage <= 0 { if perPage <= 0 {
perPage = 1000 perPage = 1000
@@ -202,7 +202,7 @@ func (hs *HTTPServer) SearchTeams(c *models.ReqContext) response.Response {
// UserFilter returns the user ID used in a filter when querying a team // UserFilter returns the user ID used in a filter when querying a team
// 1. If the user is a viewer or editor, this will return the user's ID. // 1. If the user is a viewer or editor, this will return the user's ID.
// 2. If the user is an admin, this will return models.FilterIgnoreUser (0) // 2. If the user is an admin, this will return models.FilterIgnoreUser (0)
func userFilter(c *models.ReqContext) int64 { func userFilter(c *contextmodel.ReqContext) int64 {
userIdFilter := c.SignedInUser.UserID userIdFilter := c.SignedInUser.UserID
if c.OrgRole == org.RoleAdmin { if c.OrgRole == org.RoleAdmin {
userIdFilter = team.FilterIgnoreUser userIdFilter = team.FilterIgnoreUser
@@ -220,7 +220,7 @@ func userFilter(c *models.ReqContext) int64 {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetTeamByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetTeamByID(c *contextmodel.ReqContext) response.Response {
teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64) teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "teamId is invalid", err) return response.Error(http.StatusBadRequest, "teamId is invalid", err)
@@ -264,7 +264,7 @@ func (hs *HTTPServer) GetTeamByID(c *models.ReqContext) response.Response {
// 200: getPreferencesResponse // 200: getPreferencesResponse
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetTeamPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetTeamPreferences(c *contextmodel.ReqContext) response.Response {
teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64) teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "teamId is invalid", err) return response.Error(http.StatusBadRequest, "teamId is invalid", err)
@@ -290,7 +290,7 @@ func (hs *HTTPServer) GetTeamPreferences(c *models.ReqContext) response.Response
// 400: badRequestError // 400: badRequestError
// 401: unauthorisedError // 401: unauthorisedError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateTeamPreferences(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateTeamPreferences(c *contextmodel.ReqContext) response.Response {
dtoCmd := dtos.UpdatePrefsCmd{} dtoCmd := dtos.UpdatePrefsCmd{}
if err := web.Bind(c.Req, &dtoCmd); err != nil { if err := web.Bind(c.Req, &dtoCmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)

View File

@@ -9,8 +9,8 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/team" "github.com/grafana/grafana/pkg/services/team"
@@ -28,7 +28,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetTeamMembers(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetTeamMembers(c *contextmodel.ReqContext) response.Response {
teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64) teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "teamId is invalid", err) return response.Error(http.StatusBadRequest, "teamId is invalid", err)
@@ -79,7 +79,7 @@ func (hs *HTTPServer) GetTeamMembers(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) AddTeamMember(c *models.ReqContext) response.Response { func (hs *HTTPServer) AddTeamMember(c *contextmodel.ReqContext) response.Response {
cmd := team.AddTeamMemberCommand{} cmd := team.AddTeamMemberCommand{}
var err error var err error
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
@@ -125,7 +125,7 @@ func (hs *HTTPServer) AddTeamMember(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateTeamMember(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateTeamMember(c *contextmodel.ReqContext) response.Response {
cmd := team.UpdateTeamMemberCommand{} cmd := team.UpdateTeamMemberCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -181,7 +181,7 @@ func getPermissionName(permission dashboards.PermissionType) string {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) RemoveTeamMember(c *models.ReqContext) response.Response { func (hs *HTTPServer) RemoveTeamMember(c *contextmodel.ReqContext) response.Response {
orgId := c.OrgID orgId := c.OrgID
teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64) teamId, err := strconv.ParseInt(web.Params(c.Req)[":teamId"], 10, 64)
if err != nil { if err != nil {

View File

@@ -14,10 +14,10 @@ import (
"github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/log/logtest" "github.com/grafana/grafana/pkg/infra/log/logtest"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl"
"github.com/grafana/grafana/pkg/services/accesscontrol/actest" "github.com/grafana/grafana/pkg/services/accesscontrol/actest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
pref "github.com/grafana/grafana/pkg/services/preference" pref "github.com/grafana/grafana/pkg/services/preference"
"github.com/grafana/grafana/pkg/services/preference/preftest" "github.com/grafana/grafana/pkg/services/preference/preftest"
@@ -124,7 +124,7 @@ func TestTeamAPIEndpoint(t *testing.T) {
t.Run("with no real signed in user", func(t *testing.T) { t.Run("with no real signed in user", func(t *testing.T) {
logger := &logtest.Fake{} logger := &logtest.Fake{}
c := &models.ReqContext{ c := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
SignedInUser: &user.SignedInUser{}, SignedInUser: &user.SignedInUser{},
Logger: logger, Logger: logger,
@@ -141,7 +141,7 @@ func TestTeamAPIEndpoint(t *testing.T) {
t.Run("with real signed in user", func(t *testing.T) { t.Run("with real signed in user", func(t *testing.T) {
logger := &logtest.Fake{} logger := &logtest.Fake{}
c := &models.ReqContext{ c := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
SignedInUser: &user.SignedInUser{UserID: 42}, SignedInUser: &user.SignedInUser{UserID: 42},
Logger: logger, Logger: logger,

View File

@@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/team" "github.com/grafana/grafana/pkg/services/team"
@@ -29,7 +30,7 @@ import (
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetSignedInUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetSignedInUser(c *contextmodel.ReqContext) response.Response {
return hs.getUserUserProfile(c, c.UserID) return hs.getUserUserProfile(c, c.UserID)
} }
@@ -43,7 +44,7 @@ func (hs *HTTPServer) GetSignedInUser(c *models.ReqContext) response.Response {
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserByID(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -51,7 +52,7 @@ func (hs *HTTPServer) GetUserByID(c *models.ReqContext) response.Response {
return hs.getUserUserProfile(c, id) return hs.getUserUserProfile(c, id)
} }
func (hs *HTTPServer) getUserUserProfile(c *models.ReqContext, userID int64) response.Response { func (hs *HTTPServer) getUserUserProfile(c *contextmodel.ReqContext, userID int64) response.Response {
query := user.GetUserProfileQuery{UserID: userID} query := user.GetUserProfileQuery{UserID: userID}
userProfile, err := hs.userService.GetProfile(c.Req.Context(), &query) userProfile, err := hs.userService.GetProfile(c.Req.Context(), &query)
@@ -86,7 +87,7 @@ func (hs *HTTPServer) getUserUserProfile(c *models.ReqContext, userID int64) res
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserByLoginOrEmail(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserByLoginOrEmail(c *contextmodel.ReqContext) response.Response {
query := user.GetUserByLoginQuery{LoginOrEmail: c.Query("loginOrEmail")} query := user.GetUserByLoginQuery{LoginOrEmail: c.Query("loginOrEmail")}
usr, err := hs.userService.GetByLogin(c.Req.Context(), &query) usr, err := hs.userService.GetByLogin(c.Req.Context(), &query)
if err != nil { if err != nil {
@@ -118,7 +119,7 @@ func (hs *HTTPServer) GetUserByLoginOrEmail(c *models.ReqContext) response.Respo
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateSignedInUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateSignedInUser(c *contextmodel.ReqContext) response.Response {
cmd := user.UpdateUserCommand{} cmd := user.UpdateUserCommand{}
var err error var err error
if err = web.Bind(c.Req, &cmd); err != nil { if err = web.Bind(c.Req, &cmd); err != nil {
@@ -152,7 +153,7 @@ func (hs *HTTPServer) UpdateSignedInUser(c *models.ReqContext) response.Response
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UpdateUser(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateUser(c *contextmodel.ReqContext) response.Response {
cmd := user.UpdateUserCommand{} cmd := user.UpdateUserCommand{}
var err error var err error
if err = web.Bind(c.Req, &cmd); err != nil { if err = web.Bind(c.Req, &cmd); err != nil {
@@ -171,7 +172,7 @@ func (hs *HTTPServer) UpdateUser(c *models.ReqContext) response.Response {
} }
// POST /api/users/:id/using/:orgId // POST /api/users/:id/using/:orgId
func (hs *HTTPServer) UpdateUserActiveOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) UpdateUserActiveOrg(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -250,7 +251,7 @@ func (hs *HTTPServer) isExternalUser(ctx context.Context, userID int64) (bool, e
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetSignedInUserOrgList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetSignedInUserOrgList(c *contextmodel.ReqContext) response.Response {
return hs.getUserOrgList(c.Req.Context(), c.UserID) return hs.getUserOrgList(c.Req.Context(), c.UserID)
} }
@@ -265,7 +266,7 @@ func (hs *HTTPServer) GetSignedInUserOrgList(c *models.ReqContext) response.Resp
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetSignedInUserTeamList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetSignedInUserTeamList(c *contextmodel.ReqContext) response.Response {
return hs.getUserTeamList(c, c.OrgID, c.UserID) return hs.getUserTeamList(c, c.OrgID, c.UserID)
} }
@@ -281,7 +282,7 @@ func (hs *HTTPServer) GetSignedInUserTeamList(c *models.ReqContext) response.Res
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserTeams(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserTeams(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -289,7 +290,7 @@ func (hs *HTTPServer) GetUserTeams(c *models.ReqContext) response.Response {
return hs.getUserTeamList(c, c.OrgID, id) return hs.getUserTeamList(c, c.OrgID, id)
} }
func (hs *HTTPServer) getUserTeamList(c *models.ReqContext, orgID int64, userID int64) response.Response { func (hs *HTTPServer) getUserTeamList(c *contextmodel.ReqContext, orgID int64, userID int64) response.Response {
query := team.GetTeamsByUserQuery{OrgID: orgID, UserID: userID, SignedInUser: c.SignedInUser} query := team.GetTeamsByUserQuery{OrgID: orgID, UserID: userID, SignedInUser: c.SignedInUser}
queryResult, err := hs.teamService.GetTeamsByUser(c.Req.Context(), &query) queryResult, err := hs.teamService.GetTeamsByUser(c.Req.Context(), &query)
@@ -315,7 +316,7 @@ func (hs *HTTPServer) getUserTeamList(c *models.ReqContext, orgID int64, userID
// 403: forbiddenError // 403: forbiddenError
// 404: notFoundError // 404: notFoundError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserOrgList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserOrgList(c *contextmodel.ReqContext) response.Response {
id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) id, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -365,7 +366,7 @@ func (hs *HTTPServer) validateUsingOrg(ctx context.Context, userID int64, orgID
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) UserSetUsingOrg(c *models.ReqContext) response.Response { func (hs *HTTPServer) UserSetUsingOrg(c *contextmodel.ReqContext) response.Response {
orgID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) orgID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -385,7 +386,7 @@ func (hs *HTTPServer) UserSetUsingOrg(c *models.ReqContext) response.Response {
} }
// GET /profile/switch-org/:id // GET /profile/switch-org/:id
func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *models.ReqContext) { func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *contextmodel.ReqContext) {
orgID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) orgID, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
c.JsonApiErr(http.StatusBadRequest, "id is invalid", err) c.JsonApiErr(http.StatusBadRequest, "id is invalid", err)
@@ -420,7 +421,7 @@ func (hs *HTTPServer) ChangeActiveOrgAndRedirectToHome(c *models.ReqContext) {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) ChangeUserPassword(c *models.ReqContext) response.Response { func (hs *HTTPServer) ChangeUserPassword(c *contextmodel.ReqContext) response.Response {
cmd := user.ChangeUserPasswordCommand{} cmd := user.ChangeUserPasswordCommand{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -468,7 +469,7 @@ func (hs *HTTPServer) ChangeUserPassword(c *models.ReqContext) response.Response
} }
// redirectToChangePassword handles GET /.well-known/change-password. // redirectToChangePassword handles GET /.well-known/change-password.
func redirectToChangePassword(c *models.ReqContext) { func redirectToChangePassword(c *contextmodel.ReqContext) {
c.Redirect("/profile/password", 302) c.Redirect("/profile/password", 302)
} }
@@ -481,7 +482,7 @@ func redirectToChangePassword(c *models.ReqContext) {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) SetHelpFlag(c *models.ReqContext) response.Response { func (hs *HTTPServer) SetHelpFlag(c *contextmodel.ReqContext) response.Response {
flag, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64) flag, err := strconv.ParseInt(web.Params(c.Req)[":id"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "id is invalid", err) return response.Error(http.StatusBadRequest, "id is invalid", err)
@@ -511,7 +512,7 @@ func (hs *HTTPServer) SetHelpFlag(c *models.ReqContext) response.Response {
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) ClearHelpFlags(c *models.ReqContext) response.Response { func (hs *HTTPServer) ClearHelpFlags(c *contextmodel.ReqContext) response.Response {
cmd := user.SetUserHelpFlagCommand{ cmd := user.SetUserHelpFlagCommand{
UserID: c.UserID, UserID: c.UserID,
HelpFlags1: user.HelpFlags1(0), HelpFlags1: user.HelpFlags1(0),

View File

@@ -21,6 +21,7 @@ import (
"github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" 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/authinfoservice" "github.com/grafana/grafana/pkg/services/login/authinfoservice"
authinfostore "github.com/grafana/grafana/pkg/services/login/authinfoservice/database" authinfostore "github.com/grafana/grafana/pkg/services/login/authinfoservice/database"
"github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/login/logintest"
@@ -255,7 +256,7 @@ func updateUserScenario(t *testing.T, ctx updateUserContext, hs *HTTPServer) {
sc.authInfoService = &logintest.AuthInfoServiceFake{} sc.authInfoService = &logintest.AuthInfoServiceFake{}
hs.authInfoService = sc.authInfoService hs.authInfoService = sc.authInfoService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(ctx.cmd) c.Req.Body = mockRequestBody(ctx.cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c
@@ -308,7 +309,7 @@ func updateSignedInUserScenario(t *testing.T, ctx updateUserContext, hs *HTTPSer
sc.authInfoService = &logintest.AuthInfoServiceFake{} sc.authInfoService = &logintest.AuthInfoServiceFake{}
hs.authInfoService = sc.authInfoService hs.authInfoService = sc.authInfoService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(ctx.cmd) c.Req.Body = mockRequestBody(ctx.cmd)
c.Req.Header.Add("Content-Type", "application/json") c.Req.Header.Add("Content-Type", "application/json")
sc.context = c sc.context = c

View File

@@ -8,8 +8,8 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -27,7 +27,7 @@ import (
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) GetUserAuthTokens(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetUserAuthTokens(c *contextmodel.ReqContext) response.Response {
return hs.getUserAuthTokensInternal(c, c.UserID) return hs.getUserAuthTokensInternal(c, c.UserID)
} }
@@ -43,7 +43,7 @@ func (hs *HTTPServer) GetUserAuthTokens(c *models.ReqContext) response.Response
// 401: unauthorisedError // 401: unauthorisedError
// 403: forbiddenError // 403: forbiddenError
// 500: internalServerError // 500: internalServerError
func (hs *HTTPServer) RevokeUserAuthToken(c *models.ReqContext) response.Response { func (hs *HTTPServer) RevokeUserAuthToken(c *contextmodel.ReqContext) response.Response {
cmd := auth.RevokeAuthTokenCmd{} cmd := auth.RevokeAuthTokenCmd{}
if err := web.Bind(c.Req, &cmd); err != nil { if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err) return response.Error(http.StatusBadRequest, "bad request data", err)
@@ -72,7 +72,7 @@ func (hs *HTTPServer) logoutUserFromAllDevicesInternal(ctx context.Context, user
}) })
} }
func (hs *HTTPServer) getUserAuthTokensInternal(c *models.ReqContext, userID int64) response.Response { func (hs *HTTPServer) getUserAuthTokensInternal(c *contextmodel.ReqContext, userID int64) response.Response {
userQuery := user.GetUserByIDQuery{ID: userID} userQuery := user.GetUserByIDQuery{ID: userID}
_, err := hs.userService.GetByID(c.Req.Context(), &userQuery) _, err := hs.userService.GetByID(c.Req.Context(), &userQuery)
@@ -144,7 +144,7 @@ func (hs *HTTPServer) getUserAuthTokensInternal(c *models.ReqContext, userID int
return response.JSON(http.StatusOK, result) return response.JSON(http.StatusOK, result)
} }
func (hs *HTTPServer) revokeUserAuthTokenInternal(c *models.ReqContext, userID int64, cmd auth.RevokeAuthTokenCmd) response.Response { func (hs *HTTPServer) revokeUserAuthTokenInternal(c *contextmodel.ReqContext, userID int64, cmd auth.RevokeAuthTokenCmd) response.Response {
userQuery := user.GetUserByIDQuery{ID: userID} userQuery := user.GetUserByIDQuery{ID: userID}
_, err := hs.userService.GetByID(c.Req.Context(), &userQuery) _, err := hs.userService.GetByID(c.Req.Context(), &userQuery)
if err != nil { if err != nil {

View File

@@ -10,9 +10,9 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/authtest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest" "github.com/grafana/grafana/pkg/services/user/usertest"
@@ -158,7 +158,7 @@ func revokeUserAuthTokenScenario(t *testing.T, desc string, url string, routePat
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(cmd) c.Req.Body = mockRequestBody(cmd)
sc.context = c sc.context = c
sc.context.UserID = userId sc.context.UserID = userId
@@ -185,7 +185,7 @@ func getUserAuthTokensScenario(t *testing.T, desc string, url string, routePatte
sc := setupScenarioContext(t, url) sc := setupScenarioContext(t, url)
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = userId sc.context.UserID = userId
sc.context.OrgID = testOrgID sc.context.OrgID = testOrgID
@@ -208,7 +208,7 @@ func logoutUserFromAllDevicesInternalScenario(t *testing.T, desc string, userId
} }
sc := setupScenarioContext(t, "/") sc := setupScenarioContext(t, "/")
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
sc.context.OrgID = testOrgID sc.context.OrgID = testOrgID
@@ -235,7 +235,7 @@ func revokeUserAuthTokenInternalScenario(t *testing.T, desc string, cmd auth.Rev
sc := setupScenarioContext(t, "/") sc := setupScenarioContext(t, "/")
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
sc.context.OrgID = testOrgID sc.context.OrgID = testOrgID
@@ -260,7 +260,7 @@ func getUserAuthTokensInternalScenario(t *testing.T, desc string, token *auth.Us
sc := setupScenarioContext(t, "/") sc := setupScenarioContext(t, "/")
sc.userAuthTokenService = fakeAuthTokenService sc.userAuthTokenService = fakeAuthTokenService
sc.defaultHandler = routing.Wrap(func(c *models.ReqContext) response.Response { sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
sc.context = c sc.context = c
sc.context.UserID = testUserID sc.context.UserID = testUserID
sc.context.OrgID = testOrgID sc.context.OrgID = testOrgID

View File

@@ -4,8 +4,8 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
grpccontext "github.com/grafana/grafana/pkg/services/grpcserver/context" grpccontext "github.com/grafana/grafana/pkg/services/grpcserver/context"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
) )
@@ -33,7 +33,7 @@ func User(ctx context.Context) (*user.SignedInUser, error) {
} }
// Set by incoming HTTP request // Set by incoming HTTP request
c, ok := ctxkey.Get(ctx).(*models.ReqContext) c, ok := ctxkey.Get(ctx).(*contextmodel.ReqContext)
if ok && c.SignedInUser != nil { if ok && c.SignedInUser != nil {
return c.SignedInUser, nil return c.SignedInUser, nil
} }

View File

@@ -8,8 +8,8 @@ import (
"github.com/grafana/grafana/pkg/infra/appcontext" "github.com/grafana/grafana/pkg/infra/appcontext"
"github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
grpccontext "github.com/grafana/grafana/pkg/services/grpcserver/context" grpccontext "github.com/grafana/grafana/pkg/services/grpcserver/context"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@@ -47,7 +47,7 @@ func TestUserFromContext(t *testing.T) {
t.Run("should return user set by HTTP ReqContext", func(t *testing.T) { t.Run("should return user set by HTTP ReqContext", func(t *testing.T) {
expected := testUser() expected := testUser()
ctx := ctxkey.Set(context.Background(), &models.ReqContext{ ctx := ctxkey.Set(context.Background(), &contextmodel.ReqContext{
SignedInUser: expected, SignedInUser: expected,
}) })
actual, err := appcontext.User(ctx) actual, err := appcontext.User(ctx)

View File

@@ -6,8 +6,8 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/middleware" "github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
) )
const rootUrl = "/api/admin" const rootUrl = "/api/admin"
@@ -20,7 +20,7 @@ func (uss *UsageStats) registerAPIEndpoints() {
}) })
} }
func (uss *UsageStats) getUsageReportPreview(ctx *models.ReqContext) response.Response { func (uss *UsageStats) getUsageReportPreview(ctx *contextmodel.ReqContext) response.Response {
usageReport, err := uss.GetUsageReport(ctx.Req.Context()) usageReport, err := uss.GetUsageReport(ctx.Req.Context())
if err != nil { if err != nil {
return response.Error(http.StatusInternalServerError, "failed to get usage report", err) return response.Error(http.StatusInternalServerError, "failed to get usage report", err)

View File

@@ -11,8 +11,8 @@ import (
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/stats" "github.com/grafana/grafana/pkg/services/stats"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -93,7 +93,7 @@ type testContext struct {
func contextProvider(tc *testContext) web.Handler { func contextProvider(tc *testContext) web.Handler {
return func(c *web.Context) { return func(c *web.Context) {
signedIn := tc.user != nil signedIn := tc.user != nil
reqCtx := &models.ReqContext{ reqCtx := &contextmodel.ReqContext{
Context: c, Context: c,
SignedInUser: tc.user, SignedInUser: tc.user,
IsSignedIn: signedIn, IsSignedIn: signedIn,

View File

@@ -10,9 +10,9 @@ import (
"github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/middleware/cookies" "github.com/grafana/grafana/pkg/middleware/cookies"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/services/auth"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/folder" "github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
@@ -27,7 +27,7 @@ type AuthOptions struct {
ReqNoAnonynmous bool ReqNoAnonynmous bool
} }
func accessForbidden(c *models.ReqContext) { func accessForbidden(c *contextmodel.ReqContext) {
if c.IsApiRequest() { if c.IsApiRequest() {
c.JsonApiErr(403, "Permission denied", nil) c.JsonApiErr(403, "Permission denied", nil)
return return
@@ -36,7 +36,7 @@ func accessForbidden(c *models.ReqContext) {
c.Redirect(setting.AppSubUrl + "/") c.Redirect(setting.AppSubUrl + "/")
} }
func notAuthorized(c *models.ReqContext) { func notAuthorized(c *contextmodel.ReqContext) {
if c.IsApiRequest() { if c.IsApiRequest() {
c.WriteErrOrFallback(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized), c.LookupTokenErr) c.WriteErrOrFallback(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized), c.LookupTokenErr)
return return
@@ -46,7 +46,7 @@ func notAuthorized(c *models.ReqContext) {
c.Redirect(setting.AppSubUrl + "/login") c.Redirect(setting.AppSubUrl + "/login")
} }
func tokenRevoked(c *models.ReqContext, err *auth.TokenRevokedError) { func tokenRevoked(c *contextmodel.ReqContext, err *auth.TokenRevokedError) {
if c.IsApiRequest() { if c.IsApiRequest() {
c.JSON(401, map[string]interface{}{ c.JSON(401, map[string]interface{}{
"message": "Token revoked", "message": "Token revoked",
@@ -62,7 +62,7 @@ func tokenRevoked(c *models.ReqContext, err *auth.TokenRevokedError) {
c.Redirect(setting.AppSubUrl + "/login") c.Redirect(setting.AppSubUrl + "/login")
} }
func writeRedirectCookie(c *models.ReqContext) { func writeRedirectCookie(c *contextmodel.ReqContext) {
redirectTo := c.Req.RequestURI redirectTo := c.Req.RequestURI
if setting.AppSubUrl != "" && !strings.HasPrefix(redirectTo, setting.AppSubUrl) { if setting.AppSubUrl != "" && !strings.HasPrefix(redirectTo, setting.AppSubUrl) {
redirectTo = setting.AppSubUrl + c.Req.RequestURI redirectTo = setting.AppSubUrl + c.Req.RequestURI
@@ -83,14 +83,14 @@ func removeForceLoginParams(str string) string {
return forceLoginParamsRegexp.ReplaceAllString(str, "") return forceLoginParamsRegexp.ReplaceAllString(str, "")
} }
func EnsureEditorOrViewerCanEdit(c *models.ReqContext) { func EnsureEditorOrViewerCanEdit(c *contextmodel.ReqContext) {
if !c.SignedInUser.HasRole(org.RoleEditor) && !setting.ViewersCanEdit { if !c.SignedInUser.HasRole(org.RoleEditor) && !setting.ViewersCanEdit {
accessForbidden(c) accessForbidden(c)
} }
} }
func CanAdminPlugins(cfg *setting.Cfg) func(c *models.ReqContext) { func CanAdminPlugins(cfg *setting.Cfg) func(c *contextmodel.ReqContext) {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if !plugins.ReqCanAdminPlugins(cfg)(c) { if !plugins.ReqCanAdminPlugins(cfg)(c) {
accessForbidden(c) accessForbidden(c)
return return
@@ -99,7 +99,7 @@ func CanAdminPlugins(cfg *setting.Cfg) func(c *models.ReqContext) {
} }
func RoleAuth(roles ...org.RoleType) web.Handler { func RoleAuth(roles ...org.RoleType) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
ok := false ok := false
for _, role := range roles { for _, role := range roles {
if role == c.OrgRole { if role == c.OrgRole {
@@ -114,7 +114,7 @@ func RoleAuth(roles ...org.RoleType) web.Handler {
} }
func Auth(options *AuthOptions) web.Handler { func Auth(options *AuthOptions) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
forceLogin := false forceLogin := false
if c.AllowAnonymous { if c.AllowAnonymous {
forceLogin = shouldForceLogin(c) forceLogin = shouldForceLogin(c)
@@ -153,7 +153,7 @@ func Auth(options *AuthOptions) web.Handler {
// Intended for when feature flags open up access to APIs that // Intended for when feature flags open up access to APIs that
// are otherwise only available to admins. // are otherwise only available to admins.
func AdminOrEditorAndFeatureEnabled(enabled bool) web.Handler { func AdminOrEditorAndFeatureEnabled(enabled bool) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if c.OrgRole == org.RoleAdmin { if c.OrgRole == org.RoleAdmin {
return return
} }
@@ -169,7 +169,7 @@ func AdminOrEditorAndFeatureEnabled(enabled bool) web.Handler {
// SnapshotPublicModeOrSignedIn creates a middleware that allows access // SnapshotPublicModeOrSignedIn creates a middleware that allows access
// if snapshot public mode is enabled or if user is signed in. // if snapshot public mode is enabled or if user is signed in.
func SnapshotPublicModeOrSignedIn(cfg *setting.Cfg) web.Handler { func SnapshotPublicModeOrSignedIn(cfg *setting.Cfg) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if cfg.SnapshotPublicMode { if cfg.SnapshotPublicMode {
return return
} }
@@ -181,7 +181,7 @@ func SnapshotPublicModeOrSignedIn(cfg *setting.Cfg) web.Handler {
} }
} }
func ReqNotSignedIn(c *models.ReqContext) { func ReqNotSignedIn(c *contextmodel.ReqContext) {
if c.IsSignedIn { if c.IsSignedIn {
c.Redirect(setting.AppSubUrl + "/") c.Redirect(setting.AppSubUrl + "/")
} }
@@ -190,7 +190,7 @@ func ReqNotSignedIn(c *models.ReqContext) {
// NoAuth creates a middleware that doesn't require any authentication. // NoAuth creates a middleware that doesn't require any authentication.
// If forceLogin param is set it will redirect the user to the login page. // If forceLogin param is set it will redirect the user to the login page.
func NoAuth() web.Handler { func NoAuth() web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if shouldForceLogin(c) { if shouldForceLogin(c) {
notAuthorized(c) notAuthorized(c)
return return
@@ -200,7 +200,7 @@ func NoAuth() web.Handler {
// shouldForceLogin checks if user should be enforced to login. // shouldForceLogin checks if user should be enforced to login.
// Returns true if forceLogin parameter is set. // Returns true if forceLogin parameter is set.
func shouldForceLogin(c *models.ReqContext) bool { func shouldForceLogin(c *contextmodel.ReqContext) bool {
forceLogin := false forceLogin := false
forceLoginParam, err := strconv.ParseBool(c.Req.URL.Query().Get("forceLogin")) forceLoginParam, err := strconv.ParseBool(c.Req.URL.Query().Get("forceLogin"))
if err == nil { if err == nil {
@@ -210,8 +210,8 @@ func shouldForceLogin(c *models.ReqContext) bool {
return forceLogin return forceLogin
} }
func OrgAdminDashOrFolderAdminOrTeamAdmin(ss db.DB, ds dashboards.DashboardService, ts team.Service) func(c *models.ReqContext) { func OrgAdminDashOrFolderAdminOrTeamAdmin(ss db.DB, ds dashboards.DashboardService, ts team.Service) func(c *contextmodel.ReqContext) {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if c.OrgRole == org.RoleAdmin { if c.OrgRole == org.RoleAdmin {
return return
} }

View File

@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
@@ -87,7 +87,7 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "Snapshot public mode disabled and unauthenticated request should return 401", func( middlewareScenario(t, "Snapshot public mode disabled and unauthenticated request should return 401", func(
t *testing.T, sc *scenarioContext) { t *testing.T, sc *scenarioContext) {
sc.m.Get("/api/snapshot", func(c *models.ReqContext) { sc.m.Get("/api/snapshot", func(c *contextmodel.ReqContext) {
c.IsSignedIn = false c.IsSignedIn = false
}, SnapshotPublicModeOrSignedIn(sc.cfg), sc.defaultHandler) }, SnapshotPublicModeOrSignedIn(sc.cfg), sc.defaultHandler)
sc.fakeReq("GET", "/api/snapshot").exec() sc.fakeReq("GET", "/api/snapshot").exec()
@@ -96,7 +96,7 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "Snapshot public mode disabled and authenticated request should return 200", func( middlewareScenario(t, "Snapshot public mode disabled and authenticated request should return 200", func(
t *testing.T, sc *scenarioContext) { t *testing.T, sc *scenarioContext) {
sc.m.Get("/api/snapshot", func(c *models.ReqContext) { sc.m.Get("/api/snapshot", func(c *contextmodel.ReqContext) {
c.IsSignedIn = true c.IsSignedIn = true
}, SnapshotPublicModeOrSignedIn(sc.cfg), sc.defaultHandler) }, SnapshotPublicModeOrSignedIn(sc.cfg), sc.defaultHandler)
sc.fakeReq("GET", "/api/snapshot").exec() sc.fakeReq("GET", "/api/snapshot").exec()

View File

@@ -5,7 +5,7 @@ import (
"net/url" "net/url"
"time" "time"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
@@ -55,7 +55,7 @@ func WriteCookie(w http.ResponseWriter, name string, value string, maxAge int, g
http.SetCookie(w, &cookie) http.SetCookie(w, &cookie)
} }
func WriteSessionCookie(ctx *models.ReqContext, cfg *setting.Cfg, value string, maxLifetime time.Duration) { func WriteSessionCookie(ctx *contextmodel.ReqContext, cfg *setting.Cfg, value string, maxLifetime time.Duration) {
if cfg.Env == setting.Dev { if cfg.Env == setting.Dev {
ctx.Logger.Info("New token", "unhashed token", value) ctx.Logger.Info("New token", "unhashed token", value)
} }

View File

@@ -4,14 +4,14 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
// In Grafana v7.0 we changed panel edit & view query parameters. // In Grafana v7.0 we changed panel edit & view query parameters.
// This middleware tries to detect those old url parameters and direct to the new url query params // This middleware tries to detect those old url parameters and direct to the new url query params
func RedirectFromLegacyPanelEditURL(cfg *setting.Cfg) func(c *models.ReqContext) { func RedirectFromLegacyPanelEditURL(cfg *setting.Cfg) func(c *contextmodel.ReqContext) {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
queryParams := c.Req.URL.Query() queryParams := c.Req.URL.Query()
panelID, hasPanelID := queryParams["panelId"] panelID, hasPanelID := queryParams["panelId"]

View File

@@ -21,8 +21,8 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/contexthandler" "github.com/grafana/grafana/pkg/services/contexthandler"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -89,7 +89,7 @@ var sensitiveQueryStrings = [...]string{
"auth_token", "auth_token",
} }
func SanitizeURL(ctx *models.ReqContext, s string) string { func SanitizeURL(ctx *contextmodel.ReqContext, s string) string {
if s == "" { if s == "" {
return s return s
} }

View File

@@ -4,13 +4,13 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func Test_sanitizeURL(t *testing.T) { func Test_sanitizeURL(t *testing.T) {
type args struct { type args struct {
ctx *models.ReqContext ctx *contextmodel.ReqContext
s string s string
} }
tests := []struct { tests := []struct {
@@ -21,7 +21,7 @@ func Test_sanitizeURL(t *testing.T) {
{ {
name: "Receiving empty string should return it", name: "Receiving empty string should return it",
args: args{ args: args{
ctx: &models.ReqContext{ ctx: &contextmodel.ReqContext{
Logger: log.New("test.logger"), Logger: log.New("test.logger"),
}, },
s: "", s: "",
@@ -31,7 +31,7 @@ func Test_sanitizeURL(t *testing.T) {
{ {
name: "Receiving valid URL string should return it parsed", name: "Receiving valid URL string should return it parsed",
args: args{ args: args{
ctx: &models.ReqContext{ ctx: &contextmodel.ReqContext{
Logger: log.New("test.logger"), Logger: log.New("test.logger"),
}, },
s: "https://grafana.com/", s: "https://grafana.com/",
@@ -41,7 +41,7 @@ func Test_sanitizeURL(t *testing.T) {
{ {
name: "Receiving invalid URL string should return empty string", name: "Receiving invalid URL string should return empty string",
args: args{ args: args{
ctx: &models.ReqContext{ ctx: &contextmodel.ReqContext{
Logger: log.New("test.logger"), Logger: log.New("test.logger"),
}, },
s: "this is not a valid URL", s: "this is not a valid URL",

View File

@@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
@@ -21,7 +21,7 @@ var (
ReqOrgAdmin = RoleAuth(org.RoleAdmin) ReqOrgAdmin = RoleAuth(org.RoleAdmin)
) )
func HandleNoCacheHeader(ctx *models.ReqContext) { func HandleNoCacheHeader(ctx *contextmodel.ReqContext) {
ctx.SkipCache = ctx.Req.Header.Get("X-Grafana-NoCache") == "true" ctx.SkipCache = ctx.Req.Header.Get("X-Grafana-NoCache") == "true"
} }

View File

@@ -33,6 +33,7 @@ import (
"github.com/grafana/grafana/pkg/services/authn/authntest" "github.com/grafana/grafana/pkg/services/authn/authntest"
"github.com/grafana/grafana/pkg/services/contexthandler" "github.com/grafana/grafana/pkg/services/contexthandler"
"github.com/grafana/grafana/pkg/services/contexthandler/authproxy" "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/featuremgmt"
"github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/login/logintest"
@@ -162,7 +163,7 @@ func TestMiddlewareContext(t *testing.T) {
middlewareScenario(t, "middleware should add Cache-Control header for requests with HTML response", func( middlewareScenario(t, "middleware should add Cache-Control header for requests with HTML response", func(
t *testing.T, sc *scenarioContext) { t *testing.T, sc *scenarioContext) {
sc.handlerFunc = func(c *models.ReqContext) { sc.handlerFunc = func(c *contextmodel.ReqContext) {
t.Log("Handler called") t.Log("Handler called")
data := &dtos.IndexViewData{ data := &dtos.IndexViewData{
User: &dtos.CurrentUser{}, User: &dtos.CurrentUser{},
@@ -721,7 +722,7 @@ func TestMiddlewareContext(t *testing.T) {
body := "key=value" body := "key=value"
sc.req.Body = io.NopCloser(strings.NewReader(body)) sc.req.Body = io.NopCloser(strings.NewReader(body))
sc.handlerFunc = func(c *models.ReqContext) { sc.handlerFunc = func(c *contextmodel.ReqContext) {
t.Log("Handler called") t.Log("Handler called")
defer func() { defer func() {
err := c.Req.Body.Close() err := c.Req.Body.Close()
@@ -745,7 +746,7 @@ func TestMiddlewareContext(t *testing.T) {
body := "key=value" body := "key=value"
sc.req.Body = io.NopCloser(strings.NewReader(body)) sc.req.Body = io.NopCloser(strings.NewReader(body))
sc.handlerFunc = func(c *models.ReqContext) { sc.handlerFunc = func(c *contextmodel.ReqContext) {
t.Log("Handler called") t.Log("Handler called")
defer func() { defer func() {
err := c.Req.Body.Close() err := c.Req.Body.Close()
@@ -889,7 +890,7 @@ func middlewareScenario(t *testing.T, desc string, fn scenarioFunc, cbs ...func(
sc.jwtAuthService = ctxHdlr.JWTAuthService.(*jwt.FakeJWTService) sc.jwtAuthService = ctxHdlr.JWTAuthService.(*jwt.FakeJWTService)
sc.remoteCacheService = ctxHdlr.RemoteCache sc.remoteCacheService = ctxHdlr.RemoteCache
sc.defaultHandler = func(c *models.ReqContext) { sc.defaultHandler = func(c *contextmodel.ReqContext) {
require.NotNil(t, c) require.NotNil(t, c)
t.Log("Default HTTP handler called") t.Log("Default HTTP handler called")
sc.context = c sc.context = c

View File

@@ -3,7 +3,7 @@ package middleware
import ( import (
"fmt" "fmt"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/services/quota"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -15,7 +15,7 @@ func Quota(quotaService quota.Service) func(string) web.Handler {
} }
//https://open.spotify.com/track/7bZSoBEAEEUsGEuLOf94Jm?si=T1Tdju5qRSmmR0zph_6RBw fuuuuunky //https://open.spotify.com/track/7bZSoBEAEEUsGEuLOf94Jm?si=T1Tdju5qRSmmR0zph_6RBw fuuuuunky
return func(targetSrv string) web.Handler { return func(targetSrv string) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
limitReached, err := quotaService.QuotaReached(c, quota.TargetSrv(targetSrv)) limitReached, err := quotaService.QuotaReached(c, quota.TargetSrv(targetSrv))
if err != nil { if err != nil {
c.JsonApiErr(500, "Failed to get quota", err) c.JsonApiErr(500, "Failed to get quota", err)

View File

@@ -9,8 +9,8 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/authtest"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -42,7 +42,7 @@ func TestRecoveryMiddleware(t *testing.T) {
}) })
} }
func panicHandler(c *models.ReqContext) { func panicHandler(c *contextmodel.ReqContext) {
panic("Handler has panicked") panic("Handler has panicked")
} }
@@ -73,7 +73,7 @@ func recoveryScenario(t *testing.T, desc string, url string, fn scenarioFunc) {
// mock out gc goroutine // mock out gc goroutine
sc.m.Use(OrgRedirect(cfg, sc.userService)) sc.m.Use(OrgRedirect(cfg, sc.userService))
sc.defaultHandler = func(c *models.ReqContext) { sc.defaultHandler = func(c *contextmodel.ReqContext) {
sc.context = c sc.context = c
if sc.handlerFunc != nil { if sc.handlerFunc != nil {
sc.handlerFunc(sc.context) sc.handlerFunc(sc.context)

View File

@@ -11,12 +11,12 @@ import (
"github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/apikey/apikeytest" "github.com/grafana/grafana/pkg/services/apikey/apikeytest"
"github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/authtest"
"github.com/grafana/grafana/pkg/services/auth/jwt" "github.com/grafana/grafana/pkg/services/auth/jwt"
"github.com/grafana/grafana/pkg/services/contexthandler" "github.com/grafana/grafana/pkg/services/contexthandler"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/user/usertest" "github.com/grafana/grafana/pkg/services/user/usertest"
@@ -27,7 +27,7 @@ import (
type scenarioContext struct { type scenarioContext struct {
t *testing.T t *testing.T
m *web.Mux m *web.Mux
context *models.ReqContext context *contextmodel.ReqContext
resp *httptest.ResponseRecorder resp *httptest.ResponseRecorder
apiKey string apiKey string
authHeader string authHeader string
@@ -80,7 +80,7 @@ func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext {
req, err := http.NewRequest(method, url, nil) req, err := http.NewRequest(method, url, nil)
require.NoError(sc.t, err) require.NoError(sc.t, err)
reqCtx := &models.ReqContext{ reqCtx := &contextmodel.ReqContext{
Context: web.FromContext(req.Context()), Context: web.FromContext(req.Context()),
} }
sc.req = req.WithContext(ctxkey.Set(req.Context(), reqCtx)) sc.req = req.WithContext(ctxkey.Set(req.Context(), reqCtx))
@@ -102,7 +102,7 @@ func (sc *scenarioContext) fakeReqWithParams(method, url string, queryParams map
req.URL.RawQuery = q.Encode() req.URL.RawQuery = q.Encode()
require.NoError(sc.t, err) require.NoError(sc.t, err)
reqCtx := &models.ReqContext{ reqCtx := &contextmodel.ReqContext{
Context: web.FromContext(req.Context()), Context: web.FromContext(req.Context()),
} }
sc.req = req.WithContext(ctxkey.Set(req.Context(), reqCtx)) sc.req = req.WithContext(ctxkey.Set(req.Context(), reqCtx))
@@ -147,4 +147,4 @@ func (sc *scenarioContext) exec() {
} }
type scenarioFunc func(t *testing.T, c *scenarioContext) type scenarioFunc func(t *testing.T, c *scenarioContext)
type handlerFunc func(c *models.ReqContext) type handlerFunc func(c *contextmodel.ReqContext)

View File

@@ -3,13 +3,13 @@ package middleware
import ( import (
"strings" "strings"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func ValidateHostHeader(cfg *setting.Cfg) web.Handler { func ValidateHostHeader(cfg *setting.Cfg) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
// ignore local render calls // ignore local render calls
if c.IsRenderCall { if c.IsRenderCall {
return return

View File

@@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"time" "time"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -59,7 +60,7 @@ type RequestURIKey struct{}
// COMMANDS // COMMANDS
type UpsertUserCommand struct { type UpsertUserCommand struct {
ReqContext *ReqContext ReqContext *contextmodel.ReqContext
ExternalUser *ExternalUserInfo ExternalUser *ExternalUserInfo
UserLookupParams UserLookupParams
SignupAllowed bool SignupAllowed bool
@@ -89,7 +90,7 @@ type DeleteAuthInfoCommand struct {
// QUERIES // QUERIES
type LoginUserQuery struct { type LoginUserQuery struct {
ReqContext *ReqContext ReqContext *contextmodel.ReqContext
Username string Username string
Password string Password string
User *user.User User *user.User

View File

@@ -1,8 +1,8 @@
package plugins package plugins
import ( import (
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
) )
@@ -22,9 +22,9 @@ var (
AdminAccessEvaluator = ac.EvalAny(ac.EvalPermission(ActionWrite), ac.EvalPermission(ActionInstall)) AdminAccessEvaluator = ac.EvalAny(ac.EvalPermission(ActionWrite), ac.EvalPermission(ActionInstall))
) )
func ReqCanAdminPlugins(cfg *setting.Cfg) func(rc *models.ReqContext) bool { func ReqCanAdminPlugins(cfg *setting.Cfg) func(rc *contextmodel.ReqContext) bool {
// Legacy handler that protects access to the Configuration > Plugins page // Legacy handler that protects access to the Configuration > Plugins page
return func(rc *models.ReqContext) bool { return func(rc *contextmodel.ReqContext) bool {
return rc.OrgRole == org.RoleAdmin || cfg.PluginAdminEnabled && rc.IsGrafanaAdmin return rc.OrgRole == org.RoleAdmin || cfg.PluginAdminEnabled && rc.IsGrafanaAdmin
} }
} }

View File

@@ -7,10 +7,10 @@ import (
"testing" "testing"
"github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/plugins/manager/client" "github.com/grafana/grafana/pkg/plugins/manager/client"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@@ -130,7 +130,7 @@ type ClientDecoratorTest struct {
TestClient *TestClient TestClient *TestClient
Middlewares []plugins.ClientMiddleware Middlewares []plugins.ClientMiddleware
Decorator *client.Decorator Decorator *client.Decorator
ReqContext *models.ReqContext ReqContext *contextmodel.ReqContext
QueryDataReq *backend.QueryDataRequest QueryDataReq *backend.QueryDataRequest
QueryDataCtx context.Context QueryDataCtx context.Context
CallResourceReq *backend.CallResourceRequest CallResourceReq *backend.CallResourceRequest
@@ -181,7 +181,7 @@ func NewClientDecoratorTest(t *testing.T, opts ...ClientDecoratorTestOption) *Cl
func WithReqContext(req *http.Request, user *user.SignedInUser) ClientDecoratorTestOption { func WithReqContext(req *http.Request, user *user.SignedInUser) ClientDecoratorTestOption {
return ClientDecoratorTestOption(func(cdt *ClientDecoratorTest) { return ClientDecoratorTestOption(func(cdt *ClientDecoratorTest) {
if cdt.ReqContext == nil { if cdt.ReqContext == nil {
cdt.ReqContext = &models.ReqContext{ cdt.ReqContext = &contextmodel.ReqContext{
Context: &web.Context{}, Context: &web.Context{},
SignedInUser: user, SignedInUser: user,
} }

View File

@@ -5,8 +5,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/registry"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -100,8 +100,8 @@ type User struct {
} }
// HasGlobalAccess checks user access with globally assigned permissions only // HasGlobalAccess checks user access with globally assigned permissions only
func HasGlobalAccess(ac AccessControl, service Service, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool { func HasGlobalAccess(ac AccessControl, service Service, c *contextmodel.ReqContext) func(fallback func(*contextmodel.ReqContext) bool, evaluator Evaluator) bool {
return func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool { return func(fallback func(*contextmodel.ReqContext) bool, evaluator Evaluator) bool {
if ac.IsDisabled() { if ac.IsDisabled() {
return fallback(c) return fallback(c)
} }
@@ -131,8 +131,8 @@ func HasGlobalAccess(ac AccessControl, service Service, c *models.ReqContext) fu
} }
} }
func HasAccess(ac AccessControl, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool { func HasAccess(ac AccessControl, c *contextmodel.ReqContext) func(fallback func(*contextmodel.ReqContext) bool, evaluator Evaluator) bool {
return func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool { return func(fallback func(*contextmodel.ReqContext) bool, evaluator Evaluator) bool {
if ac.IsDisabled() { if ac.IsDisabled() {
return fallback(c) return fallback(c)
} }
@@ -147,31 +147,31 @@ func HasAccess(ac AccessControl, c *models.ReqContext) func(fallback func(*model
} }
} }
var ReqSignedIn = func(c *models.ReqContext) bool { var ReqSignedIn = func(c *contextmodel.ReqContext) bool {
return c.IsSignedIn return c.IsSignedIn
} }
var ReqGrafanaAdmin = func(c *models.ReqContext) bool { var ReqGrafanaAdmin = func(c *contextmodel.ReqContext) bool {
return c.IsGrafanaAdmin return c.IsGrafanaAdmin
} }
// ReqViewer returns true if the current user has org.RoleViewer. Note: this can be anonymous user as well // ReqViewer returns true if the current user has org.RoleViewer. Note: this can be anonymous user as well
var ReqViewer = func(c *models.ReqContext) bool { var ReqViewer = func(c *contextmodel.ReqContext) bool {
return c.OrgRole.Includes(org.RoleViewer) return c.OrgRole.Includes(org.RoleViewer)
} }
var ReqOrgAdmin = func(c *models.ReqContext) bool { var ReqOrgAdmin = func(c *contextmodel.ReqContext) bool {
return c.OrgRole == org.RoleAdmin return c.OrgRole == org.RoleAdmin
} }
var ReqOrgAdminOrEditor = func(c *models.ReqContext) bool { var ReqOrgAdminOrEditor = func(c *contextmodel.ReqContext) bool {
return c.OrgRole == org.RoleAdmin || c.OrgRole == org.RoleEditor return c.OrgRole == org.RoleAdmin || c.OrgRole == org.RoleEditor
} }
// ReqHasRole generates a fallback to check whether the user has a role // ReqHasRole generates a fallback to check whether the user has a role
// Note that while ReqOrgAdmin returns false for a Grafana Admin / Viewer, ReqHasRole(org.RoleAdmin) will return true // Note that while ReqOrgAdmin returns false for a Grafana Admin / Viewer, ReqHasRole(org.RoleAdmin) will return true
func ReqHasRole(role org.RoleType) func(c *models.ReqContext) bool { func ReqHasRole(role org.RoleType) func(c *contextmodel.ReqContext) bool {
return func(c *models.ReqContext) bool { return c.HasRole(role) } return func(c *contextmodel.ReqContext) bool { return c.HasRole(role) }
} }
func BuildPermissionsMap(permissions []Permission) map[string]bool { func BuildPermissionsMap(permissions []Permission) map[string]bool {

View File

@@ -7,8 +7,8 @@ import (
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/middleware" "github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/models"
ac "github.com/grafana/grafana/pkg/services/accesscontrol" ac "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -47,7 +47,7 @@ func (api *AccessControlAPI) RegisterAPIEndpoints() {
} }
// GET /api/access-control/user/actions // GET /api/access-control/user/actions
func (api *AccessControlAPI) getUserActions(c *models.ReqContext) response.Response { func (api *AccessControlAPI) getUserActions(c *contextmodel.ReqContext) response.Response {
reloadCache := c.QueryBool("reloadcache") reloadCache := c.QueryBool("reloadcache")
permissions, err := api.Service.GetUserPermissions(c.Req.Context(), permissions, err := api.Service.GetUserPermissions(c.Req.Context(),
c.SignedInUser, ac.Options{ReloadCache: reloadCache}) c.SignedInUser, ac.Options{ReloadCache: reloadCache})
@@ -59,7 +59,7 @@ func (api *AccessControlAPI) getUserActions(c *models.ReqContext) response.Respo
} }
// GET /api/access-control/user/permissions // GET /api/access-control/user/permissions
func (api *AccessControlAPI) getUserPermissions(c *models.ReqContext) response.Response { func (api *AccessControlAPI) getUserPermissions(c *contextmodel.ReqContext) response.Response {
reloadCache := c.QueryBool("reloadcache") reloadCache := c.QueryBool("reloadcache")
permissions, err := api.Service.GetUserPermissions(c.Req.Context(), permissions, err := api.Service.GetUserPermissions(c.Req.Context(),
c.SignedInUser, ac.Options{ReloadCache: reloadCache}) c.SignedInUser, ac.Options{ReloadCache: reloadCache})
@@ -71,7 +71,7 @@ func (api *AccessControlAPI) getUserPermissions(c *models.ReqContext) response.R
} }
// GET /api/access-control/users/permissions // GET /api/access-control/users/permissions
func (api *AccessControlAPI) searchUsersPermissions(c *models.ReqContext) response.Response { func (api *AccessControlAPI) searchUsersPermissions(c *contextmodel.ReqContext) response.Response {
searchOptions := ac.SearchOptions{ searchOptions := ac.SearchOptions{
ActionPrefix: c.Query("actionPrefix"), ActionPrefix: c.Query("actionPrefix"),
Action: c.Query("action"), Action: c.Query("action"),
@@ -98,7 +98,7 @@ func (api *AccessControlAPI) searchUsersPermissions(c *models.ReqContext) respon
} }
// GET /api/access-control/user/:userID/permissions/search // GET /api/access-control/user/:userID/permissions/search
func (api *AccessControlAPI) searchUserPermissions(c *models.ReqContext) response.Response { func (api *AccessControlAPI) searchUserPermissions(c *contextmodel.ReqContext) response.Response {
userIDString := web.Params(c.Req)[":userID"] userIDString := web.Params(c.Req)[":userID"]
userID, err := strconv.ParseInt(userIDString, 10, 64) userID, err := strconv.ParseInt(userIDString, 10, 64)
if err != nil { if err != nil {

View File

@@ -14,8 +14,8 @@ import (
"time" "time"
"github.com/grafana/grafana/pkg/middleware/cookies" "github.com/grafana/grafana/pkg/middleware/cookies"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models/usertoken" "github.com/grafana/grafana/pkg/models/usertoken"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@@ -29,7 +29,7 @@ func Middleware(ac AccessControl) func(web.Handler, Evaluator) web.Handler {
return fallback return fallback
} }
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if c.AllowAnonymous { if c.AllowAnonymous {
forceLogin, _ := strconv.ParseBool(c.Req.URL.Query().Get("forceLogin")) // ignoring error, assuming false for non-true values is ok. forceLogin, _ := strconv.ParseBool(c.Req.URL.Query().Get("forceLogin")) // ignoring error, assuming false for non-true values is ok.
orgID, err := strconv.ParseInt(c.Req.URL.Query().Get("orgId"), 10, 64) orgID, err := strconv.ParseInt(c.Req.URL.Query().Get("orgId"), 10, 64)
@@ -53,7 +53,7 @@ func Middleware(ac AccessControl) func(web.Handler, Evaluator) web.Handler {
} }
} }
func authorize(c *models.ReqContext, ac AccessControl, user *user.SignedInUser, evaluator Evaluator) { func authorize(c *contextmodel.ReqContext, ac AccessControl, user *user.SignedInUser, evaluator Evaluator) {
injected, err := evaluator.MutateScopes(c.Req.Context(), scopeInjector(scopeParams{ injected, err := evaluator.MutateScopes(c.Req.Context(), scopeInjector(scopeParams{
OrgID: c.OrgID, OrgID: c.OrgID,
URLParams: web.Params(c.Req), URLParams: web.Params(c.Req),
@@ -70,7 +70,7 @@ func authorize(c *models.ReqContext, ac AccessControl, user *user.SignedInUser,
} }
} }
func deny(c *models.ReqContext, evaluator Evaluator, err error) { func deny(c *contextmodel.ReqContext, evaluator Evaluator, err error) {
id := newID() id := newID()
if err != nil { if err != nil {
c.Logger.Error("Error from access control system", "error", err, "accessErrorID", id) c.Logger.Error("Error from access control system", "error", err, "accessErrorID", id)
@@ -106,7 +106,7 @@ func deny(c *models.ReqContext, evaluator Evaluator, err error) {
}) })
} }
func unauthorized(c *models.ReqContext, err error) { func unauthorized(c *contextmodel.ReqContext, err error) {
if c.IsApiRequest() { if c.IsApiRequest() {
response := map[string]interface{}{ response := map[string]interface{}{
"message": "Unauthorized", "message": "Unauthorized",
@@ -129,7 +129,7 @@ func unauthorized(c *models.ReqContext, err error) {
c.Redirect(setting.AppSubUrl + "/login") c.Redirect(setting.AppSubUrl + "/login")
} }
func writeRedirectCookie(c *models.ReqContext) { func writeRedirectCookie(c *contextmodel.ReqContext) {
redirectTo := c.Req.RequestURI redirectTo := c.Req.RequestURI
if setting.AppSubUrl != "" && !strings.HasPrefix(redirectTo, setting.AppSubUrl) { if setting.AppSubUrl != "" && !strings.HasPrefix(redirectTo, setting.AppSubUrl) {
redirectTo = setting.AppSubUrl + c.Req.RequestURI redirectTo = setting.AppSubUrl + c.Req.RequestURI
@@ -159,7 +159,7 @@ func newID() string {
return "ACE" + id return "ACE" + id
} }
type OrgIDGetter func(c *models.ReqContext) (int64, error) type OrgIDGetter func(c *contextmodel.ReqContext) (int64, error)
type userCache interface { type userCache interface {
GetSignedInUserWithCacheCtx(ctx context.Context, query *user.GetSignedInUserQuery) (*user.SignedInUser, error) GetSignedInUserWithCacheCtx(ctx context.Context, query *user.GetSignedInUserQuery) (*user.SignedInUser, error)
@@ -171,7 +171,7 @@ func AuthorizeInOrgMiddleware(ac AccessControl, service Service, cache userCache
return fallback return fallback
} }
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
// using a copy of the user not to modify the signedInUser, yet perform the permission evaluation in another org // using a copy of the user not to modify the signedInUser, yet perform the permission evaluation in another org
userCopy := *(c.SignedInUser) userCopy := *(c.SignedInUser)
orgID, err := getTargetOrg(c) orgID, err := getTargetOrg(c)
@@ -211,7 +211,7 @@ func AuthorizeInOrgMiddleware(ac AccessControl, service Service, cache userCache
} }
} }
func UseOrgFromContextParams(c *models.ReqContext) (int64, error) { func UseOrgFromContextParams(c *contextmodel.ReqContext) (int64, error) {
orgID, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64) orgID, err := strconv.ParseInt(web.Params(c.Req)[":orgId"], 10, 64)
// Special case of macaron handling invalid params // Special case of macaron handling invalid params
@@ -222,12 +222,12 @@ func UseOrgFromContextParams(c *models.ReqContext) (int64, error) {
return orgID, nil return orgID, nil
} }
func UseGlobalOrg(c *models.ReqContext) (int64, error) { func UseGlobalOrg(c *contextmodel.ReqContext) (int64, error) {
return GlobalOrgID, nil return GlobalOrgID, nil
} }
func LoadPermissionsMiddleware(service Service) web.Handler { func LoadPermissionsMiddleware(service Service) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if service.IsDisabled() { if service.IsDisabled() {
return return
} }

View File

@@ -8,10 +8,10 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/grafana/grafana/pkg/infra/log" "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/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/mock" "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -55,7 +55,7 @@ func TestMiddleware(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
fallbackCalled := false fallbackCalled := false
fallback := func(c *models.ReqContext) { fallback := func(c *contextmodel.ReqContext) {
fallbackCalled = true fallbackCalled = true
} }
@@ -66,7 +66,7 @@ func TestMiddleware(t *testing.T) {
server.Use(accesscontrol.Middleware(test.ac)(fallback, test.evaluator)) server.Use(accesscontrol.Middleware(test.ac)(fallback, test.evaluator))
endpointCalled := false endpointCalled := false
server.Get("/", func(c *models.ReqContext) { server.Get("/", func(c *contextmodel.ReqContext) {
endpointCalled = true endpointCalled = true
c.Resp.WriteHeader(http.StatusOK) c.Resp.WriteHeader(http.StatusOK)
}) })
@@ -99,13 +99,13 @@ func TestMiddleware_forceLogin(t *testing.T) {
server := web.New() server := web.New()
server.UseMiddleware(web.Renderer("../../public/views", "[[", "]]")) server.UseMiddleware(web.Renderer("../../public/views", "[[", "]]"))
server.Get("/endpoint", func(c *models.ReqContext) { server.Get("/endpoint", func(c *contextmodel.ReqContext) {
endpointCalled = true endpointCalled = true
c.Resp.WriteHeader(http.StatusOK) c.Resp.WriteHeader(http.StatusOK)
}) })
ac := mock.New().WithPermissions([]accesscontrol.Permission{{Action: "endpoint:read", Scope: "endpoint:1"}}) ac := mock.New().WithPermissions([]accesscontrol.Permission{{Action: "endpoint:read", Scope: "endpoint:1"}})
server.Use(contextProvider(func(c *models.ReqContext) { server.Use(contextProvider(func(c *contextmodel.ReqContext) {
c.AllowAnonymous = true c.AllowAnonymous = true
c.SignedInUser.IsAnonymous = true c.SignedInUser.IsAnonymous = true
c.IsSignedIn = false c.IsSignedIn = false
@@ -129,9 +129,9 @@ func TestMiddleware_forceLogin(t *testing.T) {
} }
} }
func contextProvider(modifiers ...func(c *models.ReqContext)) web.Handler { func contextProvider(modifiers ...func(c *contextmodel.ReqContext)) web.Handler {
return func(c *web.Context) { return func(c *web.Context) {
reqCtx := &models.ReqContext{ reqCtx := &contextmodel.ReqContext{
Context: c, Context: c,
Logger: log.New(""), Logger: log.New(""),
SignedInUser: &user.SignedInUser{}, SignedInUser: &user.SignedInUser{},

View File

@@ -8,8 +8,8 @@ import (
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
@@ -68,7 +68,7 @@ type Description struct {
Permissions []string `json:"permissions"` Permissions []string `json:"permissions"`
} }
func (a *api) getDescription(c *models.ReqContext) response.Response { func (a *api) getDescription(c *contextmodel.ReqContext) response.Response {
return response.JSON(http.StatusOK, &Description{ return response.JSON(http.StatusOK, &Description{
Permissions: a.permissions, Permissions: a.permissions,
Assignments: a.service.options.Assignments, Assignments: a.service.options.Assignments,
@@ -91,7 +91,7 @@ type resourcePermissionDTO struct {
Permission string `json:"permission"` Permission string `json:"permission"`
} }
func (a *api) getPermissions(c *models.ReqContext) response.Response { func (a *api) getPermissions(c *contextmodel.ReqContext) response.Response {
resourceID := web.Params(c.Req)[":resourceID"] resourceID := web.Params(c.Req)[":resourceID"]
permissions, err := a.service.GetPermissions(c.Req.Context(), c.SignedInUser, resourceID) permissions, err := a.service.GetPermissions(c.Req.Context(), c.SignedInUser, resourceID)
@@ -144,7 +144,7 @@ type setPermissionsCommand struct {
Permissions []accesscontrol.SetResourcePermissionCommand `json:"permissions"` Permissions []accesscontrol.SetResourcePermissionCommand `json:"permissions"`
} }
func (a *api) setUserPermission(c *models.ReqContext) response.Response { func (a *api) setUserPermission(c *contextmodel.ReqContext) response.Response {
userID, err := strconv.ParseInt(web.Params(c.Req)[":userID"], 10, 64) userID, err := strconv.ParseInt(web.Params(c.Req)[":userID"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "userID is invalid", err) return response.Error(http.StatusBadRequest, "userID is invalid", err)
@@ -164,7 +164,7 @@ func (a *api) setUserPermission(c *models.ReqContext) response.Response {
return permissionSetResponse(cmd) return permissionSetResponse(cmd)
} }
func (a *api) setTeamPermission(c *models.ReqContext) response.Response { func (a *api) setTeamPermission(c *contextmodel.ReqContext) response.Response {
teamID, err := strconv.ParseInt(web.Params(c.Req)[":teamID"], 10, 64) teamID, err := strconv.ParseInt(web.Params(c.Req)[":teamID"], 10, 64)
if err != nil { if err != nil {
return response.Error(http.StatusBadRequest, "teamID is invalid", err) return response.Error(http.StatusBadRequest, "teamID is invalid", err)
@@ -184,7 +184,7 @@ func (a *api) setTeamPermission(c *models.ReqContext) response.Response {
return permissionSetResponse(cmd) return permissionSetResponse(cmd)
} }
func (a *api) setBuiltinRolePermission(c *models.ReqContext) response.Response { func (a *api) setBuiltinRolePermission(c *contextmodel.ReqContext) response.Response {
builtInRole := web.Params(c.Req)[":builtInRole"] builtInRole := web.Params(c.Req)[":builtInRole"]
resourceID := web.Params(c.Req)[":resourceID"] resourceID := web.Params(c.Req)[":resourceID"]
@@ -201,7 +201,7 @@ func (a *api) setBuiltinRolePermission(c *models.ReqContext) response.Response {
return permissionSetResponse(cmd) return permissionSetResponse(cmd)
} }
func (a *api) setPermissions(c *models.ReqContext) response.Response { func (a *api) setPermissions(c *contextmodel.ReqContext) response.Response {
resourceID := web.Params(c.Req)[":resourceID"] resourceID := web.Params(c.Req)[":resourceID"]
cmd := setPermissionsCommand{} cmd := setPermissionsCommand{}

View File

@@ -15,9 +15,9 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/log" "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/accesscontrol"
"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey" "github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org/orgimpl" "github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotatest" "github.com/grafana/grafana/pkg/services/quota/quotatest"
"github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore"
@@ -444,7 +444,7 @@ type testContext struct {
func contextProvider(tc *testContext) web.Handler { func contextProvider(tc *testContext) web.Handler {
return func(c *web.Context) { return func(c *web.Context) {
signedIn := tc.user != nil signedIn := tc.user != nil
reqCtx := &models.ReqContext{ reqCtx := &contextmodel.ReqContext{
Context: c, Context: c,
SignedInUser: tc.user, SignedInUser: tc.user,
IsSignedIn: signedIn, IsSignedIn: signedIn,

View File

@@ -3,12 +3,12 @@ package resourcepermissions
import ( import (
"net/http" "net/http"
"github.com/grafana/grafana/pkg/models" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web"
) )
func disableMiddleware(shouldDisable bool) web.Handler { func disableMiddleware(shouldDisable bool) web.Handler {
return func(c *models.ReqContext) { return func(c *contextmodel.ReqContext) {
if shouldDisable { if shouldDisable {
c.Resp.WriteHeader(http.StatusNotFound) c.Resp.WriteHeader(http.StatusNotFound)
return return
@@ -16,4 +16,4 @@ func disableMiddleware(shouldDisable bool) web.Handler {
} }
} }
func nopMiddleware(c *models.ReqContext) {} func nopMiddleware(c *contextmodel.ReqContext) {}

View File

@@ -12,6 +12,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models/roletype" "github.com/grafana/grafana/pkg/models/roletype"
authJWT "github.com/grafana/grafana/pkg/services/auth/jwt" authJWT "github.com/grafana/grafana/pkg/services/auth/jwt"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user"
) )
@@ -22,7 +23,7 @@ const (
UserNotFound = "User not found" UserNotFound = "User not found"
) )
func (h *ContextHandler) initContextWithJWT(ctx *models.ReqContext, orgId int64) bool { func (h *ContextHandler) initContextWithJWT(ctx *contextmodel.ReqContext, orgId int64) bool {
if !h.Cfg.JWTAuthEnabled || h.Cfg.JWTAuthHeaderName == "" { if !h.Cfg.JWTAuthEnabled || h.Cfg.JWTAuthHeaderName == "" {
return false return false
} }

View File

@@ -17,6 +17,7 @@ import (
"github.com/grafana/grafana/pkg/services/auth/jwt" "github.com/grafana/grafana/pkg/services/auth/jwt"
"github.com/grafana/grafana/pkg/services/authn/authntest" "github.com/grafana/grafana/pkg/services/authn/authntest"
"github.com/grafana/grafana/pkg/services/contexthandler/authproxy" "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/featuremgmt"
"github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/org/orgtest"
@@ -42,7 +43,7 @@ func TestInitContextWithAuthProxy_CachedInvalidUserID(t *testing.T) {
req, err := http.NewRequest("POST", "http://example.com", nil) req, err := http.NewRequest("POST", "http://example.com", nil)
require.NoError(t, err) require.NoError(t, err)
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
Logger: log.New("Test"), Logger: log.New("Test"),
} }

View File

@@ -17,6 +17,7 @@ import (
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/models" "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/ldap"
"github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/services/multildap"
@@ -98,7 +99,7 @@ func (auth *AuthProxy) IsEnabled() bool {
} }
// HasHeader checks if we have specified header // HasHeader checks if we have specified header
func (auth *AuthProxy) HasHeader(reqCtx *models.ReqContext) bool { func (auth *AuthProxy) HasHeader(reqCtx *contextmodel.ReqContext) bool {
header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName) header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName)
return len(header) != 0 return len(header) != 0
} }
@@ -149,7 +150,7 @@ func HashCacheKey(key string) (string, error) {
// getKey forms a key for the cache based on the headers received as part of the authentication flow. // getKey forms a key for the cache based on the headers received as part of the authentication flow.
// Our configuration supports multiple headers. The main header contains the email or username. // Our configuration supports multiple headers. The main header contains the email or username.
// And the additional ones that allow us to specify extra attributes: Name, Email, Role, or Groups. // And the additional ones that allow us to specify extra attributes: Name, Email, Role, or Groups.
func (auth *AuthProxy) getKey(reqCtx *models.ReqContext) (string, error) { func (auth *AuthProxy) getKey(reqCtx *contextmodel.ReqContext) (string, error) {
header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName) header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName)
key := strings.TrimSpace(header) // start the key with the main header key := strings.TrimSpace(header) // start the key with the main header
@@ -165,7 +166,7 @@ func (auth *AuthProxy) getKey(reqCtx *models.ReqContext) (string, error) {
} }
// Login logs in user ID by whatever means possible. // Login logs in user ID by whatever means possible.
func (auth *AuthProxy) Login(reqCtx *models.ReqContext, ignoreCache bool) (int64, error) { func (auth *AuthProxy) Login(reqCtx *contextmodel.ReqContext, ignoreCache bool) (int64, error) {
if !ignoreCache { if !ignoreCache {
// Error here means absent cache - we don't need to handle that // Error here means absent cache - we don't need to handle that
id, err := auth.getUserViaCache(reqCtx) id, err := auth.getUserViaCache(reqCtx)
@@ -195,7 +196,7 @@ func (auth *AuthProxy) Login(reqCtx *models.ReqContext, ignoreCache bool) (int64
} }
// getUserViaCache gets user ID from cache. // getUserViaCache gets user ID from cache.
func (auth *AuthProxy) getUserViaCache(reqCtx *models.ReqContext) (int64, error) { func (auth *AuthProxy) getUserViaCache(reqCtx *contextmodel.ReqContext) (int64, error) {
cacheKey, err := auth.getKey(reqCtx) cacheKey, err := auth.getKey(reqCtx)
if err != nil { if err != nil {
return 0, err return 0, err
@@ -212,7 +213,7 @@ func (auth *AuthProxy) getUserViaCache(reqCtx *models.ReqContext) (int64, error)
} }
// RemoveUserFromCache removes user from cache. // RemoveUserFromCache removes user from cache.
func (auth *AuthProxy) RemoveUserFromCache(reqCtx *models.ReqContext) error { func (auth *AuthProxy) RemoveUserFromCache(reqCtx *contextmodel.ReqContext) error {
cacheKey, err := auth.getKey(reqCtx) cacheKey, err := auth.getKey(reqCtx)
if err != nil { if err != nil {
return err return err
@@ -227,7 +228,7 @@ func (auth *AuthProxy) RemoveUserFromCache(reqCtx *models.ReqContext) error {
} }
// LoginViaLDAP logs in user via LDAP request // LoginViaLDAP logs in user via LDAP request
func (auth *AuthProxy) LoginViaLDAP(reqCtx *models.ReqContext) (int64, error) { func (auth *AuthProxy) LoginViaLDAP(reqCtx *contextmodel.ReqContext) (int64, error) {
config, err := getLDAPConfig(auth.cfg) config, err := getLDAPConfig(auth.cfg)
if err != nil { if err != nil {
return 0, newError("failed to get LDAP config", err) return 0, newError("failed to get LDAP config", err)
@@ -259,7 +260,7 @@ func (auth *AuthProxy) LoginViaLDAP(reqCtx *models.ReqContext) (int64, error) {
} }
// loginViaHeader logs in user from the header only // loginViaHeader logs in user from the header only
func (auth *AuthProxy) loginViaHeader(reqCtx *models.ReqContext) (int64, error) { func (auth *AuthProxy) loginViaHeader(reqCtx *contextmodel.ReqContext) (int64, error) {
header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName) header := auth.getDecodedHeader(reqCtx, auth.cfg.AuthProxyHeaderName)
extUser := &models.ExternalUserInfo{ extUser := &models.ExternalUserInfo{
AuthModule: login.AuthProxyAuthModule, AuthModule: login.AuthProxyAuthModule,
@@ -323,7 +324,7 @@ func (auth *AuthProxy) loginViaHeader(reqCtx *models.ReqContext) (int64, error)
} }
// getDecodedHeader gets decoded value of a header with given headerName // getDecodedHeader gets decoded value of a header with given headerName
func (auth *AuthProxy) getDecodedHeader(reqCtx *models.ReqContext, headerName string) string { func (auth *AuthProxy) getDecodedHeader(reqCtx *contextmodel.ReqContext, headerName string) string {
headerValue := reqCtx.Req.Header.Get(headerName) headerValue := reqCtx.Req.Header.Get(headerName)
if auth.cfg.AuthProxyHeadersEncoded { if auth.cfg.AuthProxyHeadersEncoded {
@@ -334,7 +335,7 @@ func (auth *AuthProxy) getDecodedHeader(reqCtx *models.ReqContext, headerName st
} }
// headersIterator iterates over all non-empty supported additional headers // headersIterator iterates over all non-empty supported additional headers
func (auth *AuthProxy) headersIterator(reqCtx *models.ReqContext, fn func(field string, header string)) { func (auth *AuthProxy) headersIterator(reqCtx *contextmodel.ReqContext, fn func(field string, header string)) {
for _, field := range supportedHeaderFields { for _, field := range supportedHeaderFields {
h := auth.cfg.AuthProxyHeaders[field] h := auth.cfg.AuthProxyHeaders[field]
if h == "" { if h == "" {
@@ -356,7 +357,7 @@ func (auth *AuthProxy) GetSignedInUser(userID int64, orgID int64) (*user.SignedI
} }
// Remember user in cache // Remember user in cache
func (auth *AuthProxy) Remember(reqCtx *models.ReqContext, id int64) error { func (auth *AuthProxy) Remember(reqCtx *contextmodel.ReqContext, id int64) error {
key, err := auth.getKey(reqCtx) key, err := auth.getKey(reqCtx)
if err != nil { if err != nil {
return err return err

View File

@@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/remotecache" "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/ldap"
"github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/loginservice"
"github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/services/multildap"
@@ -23,7 +23,7 @@ import (
const hdrName = "markelog" const hdrName = "markelog"
const id int64 = 42 const id int64 = 42
func prepareMiddleware(t *testing.T, remoteCache *remotecache.RemoteCache, configureReq func(*http.Request, *setting.Cfg)) (*AuthProxy, *models.ReqContext) { func prepareMiddleware(t *testing.T, remoteCache *remotecache.RemoteCache, configureReq func(*http.Request, *setting.Cfg)) (*AuthProxy, *contextmodel.ReqContext) {
t.Helper() t.Helper()
req, err := http.NewRequest("POST", "http://example.com", nil) req, err := http.NewRequest("POST", "http://example.com", nil)
@@ -38,7 +38,7 @@ func prepareMiddleware(t *testing.T, remoteCache *remotecache.RemoteCache, confi
req.Header.Set(cfg.AuthProxyHeaderName, hdrName) req.Header.Set(cfg.AuthProxyHeaderName, hdrName)
} }
ctx := &models.ReqContext{ ctx := &contextmodel.ReqContext{
Context: &web.Context{Req: req}, Context: &web.Context{Req: req},
} }

Some files were not shown because too many files have changed in this diff Show More