grafana/pkg/middleware/auth.go

96 lines
2.0 KiB
Go
Raw Normal View History

2014-10-05 14:13:01 -05:00
package middleware
import (
"errors"
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/session"
"strconv"
"strings"
"github.com/torkelo/grafana-pro/pkg/bus"
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
)
2014-11-20 05:11:07 -06:00
func authGetRequestAccountId(c *Context, sess session.Store) (int64, error) {
2014-10-05 14:13:01 -05:00
accountId := sess.Get("accountId")
urlQuery := c.Req.URL.Query()
// TODO: check that this is a localhost request
2014-10-05 14:13:01 -05:00
if len(urlQuery["render"]) > 0 {
2014-12-01 15:25:57 -06:00
accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
2014-10-05 14:13:01 -05:00
sess.Set("accountId", accId)
accountId = accId
}
if accountId == nil {
if setting.Anonymous {
return setting.AnonymousAccountId, nil
}
2014-10-05 14:13:01 -05:00
return -1, errors.New("Auth: session account id not found")
}
2014-11-20 05:11:07 -06:00
return accountId.(int64), nil
2014-10-05 14:13:01 -05:00
}
func authDenied(c *Context) {
2015-01-04 14:03:40 -06:00
c.Redirect(setting.AppSubUrl + "/login")
2014-10-05 14:13:01 -05:00
}
func authByToken(c *Context) {
header := c.Req.Header.Get("Authorization")
parts := strings.SplitN(header, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
return
}
token := parts[1]
userQuery := m.GetAccountByTokenQuery{Token: token}
2015-01-14 03:14:07 -06:00
if err := bus.Dispatch(&userQuery); err != nil {
return
}
2014-10-05 14:13:01 -05:00
usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
2015-01-14 03:14:07 -06:00
if err := bus.Dispatch(&usingQuery); err != nil {
return
}
2014-10-05 14:13:01 -05:00
c.UserAccount = userQuery.Result
c.Account = usingQuery.Result
}
2014-10-05 14:13:01 -05:00
func authBySession(c *Context, sess session.Store) {
accountId, err := authGetRequestAccountId(c, sess)
2014-10-05 14:13:01 -05:00
if err != nil && c.Req.URL.Path != "/login" {
authDenied(c)
return
}
userQuery := m.GetAccountByIdQuery{Id: accountId}
2015-01-14 03:14:07 -06:00
if err := bus.Dispatch(&userQuery); err != nil {
authDenied(c)
return
}
usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
2015-01-14 03:14:07 -06:00
if err := bus.Dispatch(&usingQuery); err != nil {
authDenied(c)
return
}
c.UserAccount = userQuery.Result
c.Account = usingQuery.Result
}
func Auth() macaron.Handler {
return func(c *Context, sess session.Store) {
authByToken(c)
if c.UserAccount == nil {
authBySession(c, sess)
}
2014-10-05 14:13:01 -05:00
}
}