grafana/pkg/models/context.go

90 lines
1.9 KiB
Go
Raw Normal View History

package models
import (
"strings"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting"
2019-01-17 10:11:52 -06:00
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/macaron.v1"
)
2018-03-07 10:54:50 -06:00
type ReqContext struct {
*macaron.Context
*SignedInUser
UserToken *auth.UserToken
2019-01-23 05:41:15 -06:00
// This should only be used by the auth_proxy
Session session.SessionStore
IsSignedIn bool
IsRenderCall bool
AllowAnonymous bool
2018-10-26 03:40:33 -05:00
SkipCache bool
Logger log.Logger
}
// Handle handles and logs error by given status.
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) Handle(status int, title string, err error) {
if err != nil {
ctx.Logger.Error(title, "error", err)
if setting.Env != setting.PROD {
ctx.Data["ErrorMsg"] = err
}
}
ctx.Data["Title"] = title
ctx.Data["AppSubUrl"] = setting.AppSubUrl
ctx.Data["Theme"] = "dark"
2018-11-02 04:49:46 -05:00
ctx.HTML(status, setting.ERR_TEMPLATE_NAME)
}
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) JsonOK(message string) {
resp := make(map[string]interface{})
resp["message"] = message
ctx.JSON(200, resp)
}
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) IsApiRequest() bool {
return strings.HasPrefix(ctx.Req.URL.Path, "/api")
}
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) JsonApiErr(status int, message string, err error) {
resp := make(map[string]interface{})
if err != nil {
ctx.Logger.Error(message, "error", err)
if setting.Env != setting.PROD {
resp["error"] = err.Error()
}
}
switch status {
case 404:
resp["message"] = "Not Found"
case 500:
resp["message"] = "Internal Server Error"
}
if message != "" {
resp["message"] = message
}
ctx.JSON(status, resp)
}
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) HasUserRole(role RoleType) bool {
return ctx.OrgRole.Includes(role)
}
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) HasHelpFlag(flag HelpFlags1) bool {
return ctx.HelpFlags1.HasFlag(flag)
}
2018-03-07 10:54:50 -06:00
func (ctx *ReqContext) TimeRequest(timer prometheus.Summary) {
ctx.Data["perfmon.timer"] = timer
}