grafana/pkg/middleware/auth.go

84 lines
1.4 KiB
Go
Raw Normal View History

2014-10-06 03:13:01 +08:00
package middleware
import (
"strconv"
"strings"
2015-01-14 21:25:12 +08:00
"github.com/Unknwon/macaron"
m "github.com/torkelo/grafana-pro/pkg/models"
2015-01-05 04:03:40 +08:00
"github.com/torkelo/grafana-pro/pkg/setting"
2014-10-06 03:13:01 +08:00
)
type AuthOptions struct {
ReqGrafanaAdmin bool
ReqSignedIn bool
}
func getRequestAccountId(c *Context) int64 {
2015-01-14 21:25:12 +08:00
accountId := c.Session.Get("accountId")
2014-10-06 03:13:01 +08:00
if accountId != nil {
return accountId.(int64)
}
// localhost render query
urlQuery := c.Req.URL.Query()
2014-10-06 03:13:01 +08:00
if len(urlQuery["render"]) > 0 {
2014-12-02 05:25:57 +08:00
accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
2015-01-14 21:25:12 +08:00
c.Session.Set("accountId", accId)
2014-10-06 03:13:01 +08:00
accountId = accId
}
return 0
}
func getApiToken(c *Context) string {
header := c.Req.Header.Get("Authorization")
parts := strings.SplitN(header, " ", 2)
if len(parts) == 2 || parts[0] == "Bearer" {
token := parts[1]
return token
2014-10-06 03:13:01 +08:00
}
return ""
2014-10-06 03:13:01 +08:00
}
func authDenied(c *Context) {
2015-01-14 21:25:12 +08:00
if c.IsApiRequest() {
c.JsonApiErr(401, "Access denied", nil)
}
2015-01-05 04:03:40 +08:00
c.Redirect(setting.AppSubUrl + "/login")
2014-10-06 03:13:01 +08:00
}
func RoleAuth(roles ...m.RoleType) macaron.Handler {
return func(c *Context) {
ok := false
for _, role := range roles {
if role == c.UserRole {
ok = true
break
}
}
if !ok {
authDenied(c)
}
}
}
func Auth(options *AuthOptions) macaron.Handler {
return func(c *Context) {
if !c.IsSignedIn && options.ReqSignedIn {
authDenied(c)
return
}
if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
authDenied(c)
return
}
2014-10-06 03:13:01 +08:00
}
}