grafana/pkg/middleware/auth.go

63 lines
1.3 KiB
Go
Raw Normal View History

2014-10-06 03:13:01 +08:00
package middleware
import (
"errors"
"strconv"
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/session"
"github.com/torkelo/grafana-pro/pkg/bus"
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
)
2014-11-20 19:11:07 +08:00
func authGetRequestAccountId(c *Context, sess session.Store) (int64, error) {
2014-10-06 03:13:01 +08:00
accountId := sess.Get("accountId")
urlQuery := c.Req.URL.Query()
if len(urlQuery["render"]) > 0 {
2014-12-02 05:25:57 +08:00
accId, _ := strconv.ParseInt(urlQuery["accountId"][0], 10, 64)
2014-10-06 03:13:01 +08:00
sess.Set("accountId", accId)
accountId = accId
}
if accountId == nil {
return -1, errors.New("Auth: session account id not found")
}
2014-11-20 19:11:07 +08:00
return accountId.(int64), nil
2014-10-06 03:13:01 +08:00
}
func authDenied(c *Context) {
2015-01-05 04:03:40 +08:00
c.Redirect(setting.AppSubUrl + "/login")
2014-10-06 03:13:01 +08:00
}
func Auth() macaron.Handler {
return func(c *Context, sess session.Store) {
accountId, err := authGetRequestAccountId(c, sess)
if err != nil && c.Req.URL.Path != "/login" {
authDenied(c)
return
}
userQuery := m.GetAccountByIdQuery{Id: accountId}
err = bus.Dispatch(&userQuery)
2014-10-06 03:13:01 +08:00
if err != nil {
authDenied(c)
return
}
usingQuery := m.GetAccountByIdQuery{Id: userQuery.Result.UsingAccountId}
err = bus.Dispatch(&usingQuery)
2014-10-06 03:13:01 +08:00
if err != nil {
authDenied(c)
return
}
c.UserAccount = userQuery.Result
c.Account = usingQuery.Result
2014-10-06 03:13:01 +08:00
}
}