grafana/pkg/middleware/auth.go

87 lines
1.6 KiB
Go
Raw Normal View History

2014-10-05 14:13:01 -05:00
package middleware
import (
"net/url"
"strings"
"gopkg.in/macaron.v1"
2015-01-14 07:25:12 -06:00
2015-02-05 03:37:13 -06:00
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
2014-10-05 14:13:01 -05:00
)
type AuthOptions struct {
ReqGrafanaAdmin bool
ReqSignedIn bool
}
func getRequestUserId(c *Context) int64 {
userId := c.Session.Get(SESS_KEY_USERID)
2014-10-05 14:13:01 -05:00
if userId != nil {
return userId.(int64)
}
return 0
}
2015-01-27 01:26:11 -06:00
func getApiKey(c *Context) string {
header := c.Req.Header.Get("Authorization")
parts := strings.SplitN(header, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
2015-01-27 01:26:11 -06:00
key := parts[1]
return key
2014-10-05 14:13:01 -05:00
}
return ""
2014-10-05 14:13:01 -05:00
}
func accessForbidden(c *Context) {
2015-01-14 07:25:12 -06:00
if c.IsApiRequest() {
c.JsonApiErr(403, "Permission denied", nil)
return
}
c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
c.Redirect(setting.AppSubUrl + "/login")
}
func notAuthorized(c *Context) {
if c.IsApiRequest() {
c.JsonApiErr(401, "Unauthorized", nil)
return
2015-01-14 07:25:12 -06:00
}
c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
2015-01-04 14:03:40 -06:00
c.Redirect(setting.AppSubUrl + "/login")
2014-10-05 14:13:01 -05:00
}
func RoleAuth(roles ...m.RoleType) macaron.Handler {
return func(c *Context) {
ok := false
for _, role := range roles {
if role == c.OrgRole {
ok = true
break
}
}
if !ok {
accessForbidden(c)
}
}
}
func Auth(options *AuthOptions) macaron.Handler {
return func(c *Context) {
if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
notAuthorized(c)
return
}
if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
accessForbidden(c)
return
}
2014-10-05 14:13:01 -05:00
}
}