grafana/pkg/middleware/auth.go

82 lines
1.3 KiB
Go
Raw Normal View History

2014-10-05 14:13:01 -05:00
package middleware
import (
"strings"
2015-01-14 07:25:12 -06:00
"github.com/Unknwon/macaron"
m "github.com/torkelo/grafana-pro/pkg/models"
2015-01-04 14:03:40 -06:00
"github.com/torkelo/grafana-pro/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("userId")
2014-10-05 14:13:01 -05:00
if userId != nil {
return userId.(int64)
}
2015-01-16 10:00:31 -06:00
// TODO: figure out a way to secure this
if c.Query("render") == "1" {
userId := c.QueryInt64("userId")
c.Session.Set("userId", userId)
return userId
2014-10-05 14:13:01 -05:00
}
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-05 14:13:01 -05:00
}
return ""
2014-10-05 14:13:01 -05:00
}
func authDenied(c *Context) {
2015-01-14 07:25:12 -06:00
if c.IsApiRequest() {
c.JsonApiErr(401, "Access denied", nil)
}
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.AccountRole {
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-05 14:13:01 -05:00
}
}