2014-10-05 14:13:01 -05:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2015-01-14 02:33:34 -06:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2014-11-20 08:19:44 -06:00
|
|
|
|
2015-01-14 07:25:12 -06:00
|
|
|
"github.com/Unknwon/macaron"
|
|
|
|
|
2014-12-19 06:40:02 -06:00
|
|
|
"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
|
|
|
)
|
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
type AuthOptions struct {
|
|
|
|
ReqAdmin bool
|
|
|
|
ReqSignedIn bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func getRequestAccountId(c *Context) (int64, error) {
|
2015-01-14 07:25:12 -06:00
|
|
|
accountId := c.Session.Get("accountId")
|
2014-10-05 14:13:01 -05:00
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
if accountId != nil {
|
|
|
|
return accountId.(int64), nil
|
|
|
|
}
|
2015-01-07 09:37:24 -06:00
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
// localhost render query
|
|
|
|
urlQuery := c.Req.URL.Query()
|
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)
|
2015-01-14 07:25:12 -06:00
|
|
|
c.Session.Set("accountId", accId)
|
2014-10-05 14:13:01 -05:00
|
|
|
accountId = accId
|
|
|
|
}
|
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
// check api token
|
|
|
|
header := c.Req.Header.Get("Authorization")
|
|
|
|
parts := strings.SplitN(header, " ", 2)
|
|
|
|
if len(parts) == 2 || parts[0] == "Bearer" {
|
|
|
|
token := parts[1]
|
|
|
|
userQuery := m.GetAccountByTokenQuery{Token: token}
|
|
|
|
if err := bus.Dispatch(&userQuery); err != nil {
|
|
|
|
return -1, err
|
2015-01-07 09:37:24 -06:00
|
|
|
}
|
2015-01-15 05:16:54 -06:00
|
|
|
return userQuery.Result.Id, nil
|
|
|
|
}
|
2015-01-07 09:37:24 -06:00
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
// anonymous gues user
|
|
|
|
if setting.Anonymous {
|
|
|
|
return setting.AnonymousAccountId, nil
|
2014-10-05 14:13:01 -05:00
|
|
|
}
|
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
return -1, errors.New("Auth: session account id not found")
|
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
|
|
|
}
|
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
func Auth(options *AuthOptions) macaron.Handler {
|
|
|
|
return func(c *Context) {
|
2015-01-14 02:33:34 -06:00
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
if !c.IsSignedIn && options.ReqSignedIn {
|
|
|
|
authDenied(c)
|
|
|
|
return
|
|
|
|
}
|
2015-01-14 02:33:34 -06:00
|
|
|
|
2015-01-15 05:16:54 -06:00
|
|
|
if !c.IsAdmin && options.ReqAdmin {
|
|
|
|
authDenied(c)
|
|
|
|
return
|
2015-01-14 02:33:34 -06:00
|
|
|
}
|
2014-10-05 14:13:01 -05:00
|
|
|
}
|
|
|
|
}
|