grafana/pkg/api/index.go

240 lines
7.9 KiB
Go
Raw Normal View History

package api
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
2022-04-15 07:01:58 -05:00
"net/http"
"strings"
2015-02-05 03:37:13 -06:00
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/middleware"
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/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/login"
pref "github.com/grafana/grafana/pkg/services/preference"
"github.com/grafana/grafana/pkg/services/user"
2015-02-05 03:37:13 -06:00
"github.com/grafana/grafana/pkg/setting"
)
func (hs *HTTPServer) editorInAnyFolder(c *contextmodel.ReqContext) bool {
hasEditPermissionInFoldersQuery := folder.HasEditPermissionInFoldersQuery{SignedInUser: c.SignedInUser}
hasEditPermissionInFoldersQueryResult, err := hs.DashboardService.HasEditPermissionInFolders(c.Req.Context(), &hasEditPermissionInFoldersQuery)
if err != nil {
return false
}
return hasEditPermissionInFoldersQueryResult
}
func (hs *HTTPServer) setIndexViewData(c *contextmodel.ReqContext) (*dtos.IndexViewData, error) {
Access control: Use access control for dashboard and folder (#44702) * Add actions and scopes * add resource service for dashboard and folder * Add dashboard guardian with fgac permission evaluation * Add CanDelete function to guardian interface * Add CanDelete property to folder and dashboard dto and set values * change to correct function name * Add accesscontrol to folder endpoints * add access control to dashboard endpoints * check access for nav links * Add fixed roles for dashboard and folders * use correct package * add hack to override guardian Constructor if accesscontrol is enabled * Add services * Add function to handle api backward compatability * Add permissionServices to HttpServer * Set permission when new dashboard is created * Add default permission when creating new dashboard * Set default permission when creating folder and dashboard * Add access control filter for dashboard search * Add to accept list * Add accesscontrol to dashboardimport * Disable access control in tests * Add check to see if user is allow to create a dashboard * Use SetPermissions * Use function to set several permissions at once * remove permissions for folder and dashboard on delete * update required permission * set permission for provisioning * Add CanCreate to dashboard guardian and set correct permisisons for provisioning * Dont set admin on folder / dashboard creation * Add dashboard and folder permission migrations * Add tests for CanCreate * Add roles and update descriptions * Solve uid to id for dashboard and folder permissions * Add folder and dashboard actions to permission filter * Handle viewer_can_edit flag * set folder and dashboard permissions services * Add dashboard permissions when importing a new dashboard * Set access control permissions on provisioning * Pass feature flags and only set permissions if access control is enabled * only add default permissions for folders and dashboards without folders * Batch create permissions in migrations * Remove `dashboards:edit` action * Remove unused function from interface * Update pkg/services/guardian/accesscontrol_guardian_test.go Co-authored-by: Gabriel MABILLE <gamab@users.noreply.github.com> Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>
2022-03-03 08:05:47 -06:00
hasAccess := ac.HasAccess(hs.AccessControl, c)
hasEditPerm := hasAccess(hs.editorInAnyFolder, ac.EvalAny(ac.EvalPermission(dashboards.ActionDashboardsCreate), ac.EvalPermission(dashboards.ActionFoldersCreate)))
settings, err := hs.getFrontendSettings(c)
if err != nil {
return nil, err
}
settings.IsPublicDashboardView = c.IsPublicDashboardView
prefsQuery := pref.GetPreferenceWithDefaultsQuery{UserID: c.UserID, OrgID: c.OrgID, Teams: c.Teams}
prefs, err := hs.preferenceService.GetWithDefaults(c.Req.Context(), &prefsQuery)
if err != nil {
return nil, err
}
if hs.Features.IsEnabled(featuremgmt.FlagIndividualCookiePreferences) {
if !prefs.Cookies("analytics") {
settings.GoogleAnalytics4Id = ""
settings.GoogleAnalyticsId = ""
}
}
// Locale is used for some number and date/time formatting, whereas language is used just for
// translating words in the interface
acceptLangHeader := c.Req.Header.Get("Accept-Language")
locale := "en-US"
language := "" // frontend will set the default language
if hs.Features.IsEnabled(featuremgmt.FlagInternationalization) && prefs.JSONData.Language != "" {
language = prefs.JSONData.Language
}
if len(acceptLangHeader) > 0 {
parts := strings.Split(acceptLangHeader, ",")
locale = parts[0]
}
appURL := setting.AppUrl
appSubURL := hs.Cfg.AppSubURL
// special case when doing localhost call from image renderer
if c.IsRenderCall && !hs.Cfg.ServeFromSubPath {
appURL = fmt.Sprintf("%s://localhost:%s", hs.Cfg.Protocol, hs.Cfg.HTTPPort)
appSubURL = ""
settings.AppSubUrl = ""
}
navTree, err := hs.navTreeService.GetNavTree(c, hasEditPerm, prefs)
if err != nil {
return nil, err
}
weekStart := ""
if prefs.WeekStart != nil {
weekStart = *prefs.WeekStart
}
theme := hs.getThemeForIndexData(prefs.Theme, c.Query("theme"))
data := dtos.IndexViewData{
User: &dtos.CurrentUser{
Id: c.UserID,
IsSignedIn: c.IsSignedIn,
Login: c.Login,
Email: c.Email,
Name: c.Name,
OrgCount: c.OrgCount,
OrgId: c.OrgID,
OrgName: c.OrgName,
OrgRole: c.OrgRole,
GravatarUrl: dtos.GetGravatarUrl(c.Email),
IsGrafanaAdmin: c.IsGrafanaAdmin,
Theme: theme.ID,
LightTheme: theme.Type == "light",
Timezone: prefs.Timezone,
WeekStart: weekStart,
Locale: locale,
Language: language,
HelpFlags1: c.HelpFlags1,
HasEditPermissionInFolders: hasEditPerm,
Analytics: hs.buildUserAnalyticsSettings(c.Req.Context(), c.SignedInUser),
},
Settings: settings,
ThemeType: theme.Type,
AppUrl: appURL,
AppSubUrl: appSubURL,
GoogleAnalyticsId: settings.GoogleAnalyticsId,
GoogleAnalytics4Id: settings.GoogleAnalytics4Id,
GoogleAnalytics4SendManualPageViews: hs.Cfg.GoogleAnalytics4SendManualPageViews,
GoogleTagManagerId: hs.Cfg.GoogleTagManagerID,
BuildVersion: setting.BuildVersion,
BuildCommit: setting.BuildCommit,
NewGrafanaVersion: hs.grafanaUpdateChecker.LatestVersion(),
NewGrafanaVersionExists: hs.grafanaUpdateChecker.UpdateAvailable(),
AppName: setting.ApplicationName,
AppNameBodyClass: "app-grafana",
FavIcon: "public/img/fav32.png",
AppleTouchIcon: "public/img/apple-touch-icon.png",
AppTitle: "Grafana",
NavTree: navTree,
Nonce: c.RequestNonce,
ContentDeliveryURL: hs.Cfg.GetContentDeliveryURL(hs.License.ContentDeliveryPrefix()),
LoadingLogo: "public/img/grafana_icon.svg",
IsDevelopmentEnv: hs.Cfg.Env == setting.Dev,
}
if hs.Cfg.CSPEnabled {
data.CSPEnabled = true
data.CSPContent = middleware.ReplacePolicyVariables(hs.Cfg.CSPTemplate, appURL, c.RequestNonce)
}
if !hs.AccessControl.IsDisabled() {
userPermissions, err := hs.accesscontrolService.GetUserPermissions(c.Req.Context(), c.SignedInUser, ac.Options{ReloadCache: false})
if err != nil {
return nil, err
}
data.User.Permissions = ac.BuildPermissionsMap(userPermissions)
}
if setting.DisableGravatar {
data.User.GravatarUrl = hs.Cfg.AppSubURL + "/public/img/user_profile.png"
}
if len(data.User.Name) == 0 {
data.User.Name = data.User.Login
}
hs.HooksService.RunIndexDataHooks(&data, c)
data.NavTree.ApplyAdminIA()
data.NavTree.Sort()
return &data, nil
}
func (hs *HTTPServer) buildUserAnalyticsSettings(ctx context.Context, signedInUser *user.SignedInUser) dtos.AnalyticsSettings {
identifier := signedInUser.Email + "@" + setting.AppUrl
authInfo, err := hs.authInfoService.GetAuthInfo(ctx, &login.GetAuthInfoQuery{UserId: signedInUser.UserID})
if err != nil && !errors.Is(err, user.ErrUserNotFound) {
hs.log.Error("Failed to get auth info for analytics", "error", err)
}
if authInfo != nil && authInfo.AuthModule == login.GrafanaComAuthModule {
identifier = authInfo.AuthId
}
return dtos.AnalyticsSettings{
Identifier: identifier,
IntercomIdentifier: hashUserIdentifier(identifier, hs.Cfg.IntercomSecret),
}
}
func hashUserIdentifier(identifier string, secret string) string {
if secret == "" {
return ""
}
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(identifier))
return hex.EncodeToString(h.Sum(nil))
}
func (hs *HTTPServer) Index(c *contextmodel.ReqContext) {
data, err := hs.setIndexViewData(c)
2018-03-22 06:37:35 -05:00
if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err)
return
}
2022-04-15 07:01:58 -05:00
c.HTML(http.StatusOK, "index", data)
}
func (hs *HTTPServer) NotFoundHandler(c *contextmodel.ReqContext) {
if c.IsApiRequest() {
2015-03-22 14:14:00 -05:00
c.JsonApiErr(404, "Not found", nil)
return
}
data, err := hs.setIndexViewData(c)
2018-03-22 06:37:35 -05:00
if err != nil {
c.Handle(hs.Cfg, 500, "Failed to get settings", err)
return
}
2018-03-22 06:37:35 -05:00
c.HTML(404, "index", data)
}
func (hs *HTTPServer) getThemeForIndexData(themePrefId string, themeURLParam string) *pref.ThemeDTO {
if themeURLParam != "" && pref.IsValidThemeID(themeURLParam) {
return pref.GetThemeByID(themeURLParam)
}
if pref.IsValidThemeID(themePrefId) {
theme := pref.GetThemeByID(themePrefId)
if !theme.IsExtra || hs.Features.IsEnabled(featuremgmt.FlagExtraThemes) {
return theme
}
}
return pref.GetThemeByID(hs.Cfg.DefaultTheme)
}