auth.go 1.59 KB
Newer Older
1 2 3
package middleware

import (
4
	"net/url"
5
	"strings"
6

7
	"gopkg.in/macaron.v1"
8

9 10
	m "github.com/grafana/grafana/pkg/models"
	"github.com/grafana/grafana/pkg/setting"
11 12
)

13
type AuthOptions struct {
14 15
	ReqGrafanaAdmin bool
	ReqSignedIn     bool
16 17
}

18
func getRequestUserId(c *Context) int64 {
19
	userId := c.Session.Get(SESS_KEY_USERID)
20

21 22
	if userId != nil {
		return userId.(int64)
23
	}
24

25 26 27
	return 0
}

28
func getApiKey(c *Context) string {
29 30
	header := c.Req.Header.Get("Authorization")
	parts := strings.SplitN(header, " ", 2)
31
	if len(parts) == 2 && parts[0] == "Bearer" {
32 33
		key := parts[1]
		return key
34 35
	}

36
	return ""
37 38
}

39
func accessForbidden(c *Context) {
40
	if c.IsApiRequest() {
41 42 43 44 45 46 47 48 49 50 51
		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)
52
		return
53 54
	}

55
	c.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+c.Req.RequestURI), 0, setting.AppSubUrl+"/")
56
	c.Redirect(setting.AppSubUrl + "/login")
57 58
}

59 60 61 62
func RoleAuth(roles ...m.RoleType) macaron.Handler {
	return func(c *Context) {
		ok := false
		for _, role := range roles {
63
			if role == c.OrgRole {
64 65 66 67 68
				ok = true
				break
			}
		}
		if !ok {
69
			accessForbidden(c)
70 71 72 73
		}
	}
}

74 75
func Auth(options *AuthOptions) macaron.Handler {
	return func(c *Context) {
76 77
		if !c.IsSignedIn && options.ReqSignedIn && !c.AllowAnonymous {
			notAuthorized(c)
78 79
			return
		}
80

81 82
		if !c.IsGrafanaAdmin && options.ReqGrafanaAdmin {
			accessForbidden(c)
83
			return
84
		}
85 86
	}
}