move UserToken and UserTokenService to models package

This commit is contained in:
Marcus Efraimsson 2019-02-06 16:45:48 +01:00
parent a60124a88c
commit 8678620730
No known key found for this signature in database
GPG Key ID: EBFE0FB04612DD4A
12 changed files with 85 additions and 86 deletions

View File

@ -21,7 +21,6 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/auth/authtoken"
"github.com/grafana/grafana/pkg/services/cache" "github.com/grafana/grafana/pkg/services/cache"
"github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/hooks" "github.com/grafana/grafana/pkg/services/hooks"
@ -48,14 +47,14 @@ type HTTPServer struct {
streamManager *live.StreamManager streamManager *live.StreamManager
httpSrv *http.Server httpSrv *http.Server
RouteRegister routing.RouteRegister `inject:""` RouteRegister routing.RouteRegister `inject:""`
Bus bus.Bus `inject:""` Bus bus.Bus `inject:""`
RenderService rendering.Service `inject:""` RenderService rendering.Service `inject:""`
Cfg *setting.Cfg `inject:""` Cfg *setting.Cfg `inject:""`
HooksService *hooks.HooksService `inject:""` HooksService *hooks.HooksService `inject:""`
CacheService *cache.CacheService `inject:""` CacheService *cache.CacheService `inject:""`
DatasourceCache datasources.CacheService `inject:""` DatasourceCache datasources.CacheService `inject:""`
AuthTokenService authtoken.UserAuthTokenService `inject:""` AuthTokenService models.UserTokenService `inject:""`
} }
func (hs *HTTPServer) Init() error { func (hs *HTTPServer) Init() error {

View File

@ -5,8 +5,6 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"github.com/grafana/grafana/pkg/services/auth/authtoken"
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/log"
@ -141,7 +139,7 @@ func (hs *HTTPServer) loginUserWithUser(user *m.User, c *m.ReqContext) {
} }
func (hs *HTTPServer) Logout(c *m.ReqContext) { func (hs *HTTPServer) Logout(c *m.ReqContext) {
if err := hs.AuthTokenService.RevokeToken(c.UserToken); err != nil && err != authtoken.ErrAuthTokenNotFound { if err := hs.AuthTokenService.RevokeToken(c.UserToken); err != nil && err != m.ErrUserTokenNotFound {
hs.log.Error("failed to revoke auth token", "error", err) hs.log.Error("failed to revoke auth token", "error", err)
} }

View File

@ -10,7 +10,6 @@ import (
"github.com/grafana/grafana/pkg/components/apikeygen" "github.com/grafana/grafana/pkg/components/apikeygen"
"github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/log"
m "github.com/grafana/grafana/pkg/models" m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth/authtoken"
"github.com/grafana/grafana/pkg/services/session" "github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
@ -24,7 +23,7 @@ var (
ReqOrgAdmin = RoleAuth(m.ROLE_ADMIN) ReqOrgAdmin = RoleAuth(m.ROLE_ADMIN)
) )
func GetContextHandler(ats authtoken.UserAuthTokenService) macaron.Handler { func GetContextHandler(ats m.UserTokenService) macaron.Handler {
return func(c *macaron.Context) { return func(c *macaron.Context) {
ctx := &m.ReqContext{ ctx := &m.ReqContext{
Context: c, Context: c,
@ -169,7 +168,7 @@ func initContextWithBasicAuth(ctx *m.ReqContext, orgId int64) bool {
return true return true
} }
func initContextWithToken(authTokenService authtoken.UserAuthTokenService, ctx *m.ReqContext, orgID int64) bool { func initContextWithToken(authTokenService m.UserTokenService, ctx *m.ReqContext, orgID int64) bool {
rawToken := ctx.GetCookie(setting.LoginCookieName) rawToken := ctx.GetCookie(setting.LoginCookieName)
if rawToken == "" { if rawToken == "" {
return false return false

View File

@ -11,7 +11,6 @@ import (
msession "github.com/go-macaron/session" msession "github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models" m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/auth/authtoken" "github.com/grafana/grafana/pkg/services/auth/authtoken"
"github.com/grafana/grafana/pkg/services/session" "github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@ -157,8 +156,8 @@ func TestMiddlewareContext(t *testing.T) {
return nil return nil
}) })
sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*auth.UserToken, error) { sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 12, UserId: 12,
UnhashedToken: unhashedToken, UnhashedToken: unhashedToken,
}, nil }, nil
@ -186,14 +185,14 @@ func TestMiddlewareContext(t *testing.T) {
return nil return nil
}) })
sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*auth.UserToken, error) { sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 12, UserId: 12,
UnhashedToken: "", UnhashedToken: "",
}, nil }, nil
} }
sc.userAuthTokenService.tryRotateTokenProvider = func(userToken *auth.UserToken, clientIP, userAgent string) (bool, error) { sc.userAuthTokenService.tryRotateTokenProvider = func(userToken *m.UserToken, clientIP, userAgent string) (bool, error) {
userToken.UnhashedToken = "rotated" userToken.UnhashedToken = "rotated"
return true, nil return true, nil
} }
@ -228,7 +227,7 @@ func TestMiddlewareContext(t *testing.T) {
middlewareScenario("Invalid/expired auth token in cookie", func(sc *scenarioContext) { middlewareScenario("Invalid/expired auth token in cookie", func(sc *scenarioContext) {
sc.withTokenSessionCookie("token") sc.withTokenSessionCookie("token")
sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*auth.UserToken, error) { sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*m.UserToken, error) {
return nil, authtoken.ErrAuthTokenNotFound return nil, authtoken.ErrAuthTokenNotFound
} }
@ -680,47 +679,47 @@ type scenarioFunc func(c *scenarioContext)
type handlerFunc func(c *m.ReqContext) type handlerFunc func(c *m.ReqContext)
type fakeUserAuthTokenService struct { type fakeUserAuthTokenService struct {
createTokenProvider func(userId int64, clientIP, userAgent string) (*auth.UserToken, error) createTokenProvider func(userId int64, clientIP, userAgent string) (*m.UserToken, error)
tryRotateTokenProvider func(token *auth.UserToken, clientIP, userAgent string) (bool, error) tryRotateTokenProvider func(token *m.UserToken, clientIP, userAgent string) (bool, error)
lookupTokenProvider func(unhashedToken string) (*auth.UserToken, error) lookupTokenProvider func(unhashedToken string) (*m.UserToken, error)
revokeTokenProvider func(token *auth.UserToken) error revokeTokenProvider func(token *m.UserToken) error
} }
func newFakeUserAuthTokenService() *fakeUserAuthTokenService { func newFakeUserAuthTokenService() *fakeUserAuthTokenService {
return &fakeUserAuthTokenService{ return &fakeUserAuthTokenService{
createTokenProvider: func(userId int64, clientIP, userAgent string) (*auth.UserToken, error) { createTokenProvider: func(userId int64, clientIP, userAgent string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 0, UserId: 0,
UnhashedToken: "", UnhashedToken: "",
}, nil }, nil
}, },
tryRotateTokenProvider: func(token *auth.UserToken, clientIP, userAgent string) (bool, error) { tryRotateTokenProvider: func(token *m.UserToken, clientIP, userAgent string) (bool, error) {
return false, nil return false, nil
}, },
lookupTokenProvider: func(unhashedToken string) (*auth.UserToken, error) { lookupTokenProvider: func(unhashedToken string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 0, UserId: 0,
UnhashedToken: "", UnhashedToken: "",
}, nil }, nil
}, },
revokeTokenProvider: func(token *auth.UserToken) error { revokeTokenProvider: func(token *m.UserToken) error {
return nil return nil
}, },
} }
} }
func (s *fakeUserAuthTokenService) CreateToken(userId int64, clientIP, userAgent string) (*auth.UserToken, error) { func (s *fakeUserAuthTokenService) CreateToken(userId int64, clientIP, userAgent string) (*m.UserToken, error) {
return s.createTokenProvider(userId, clientIP, userAgent) return s.createTokenProvider(userId, clientIP, userAgent)
} }
func (s *fakeUserAuthTokenService) LookupToken(unhashedToken string) (*auth.UserToken, error) { func (s *fakeUserAuthTokenService) LookupToken(unhashedToken string) (*m.UserToken, error) {
return s.lookupTokenProvider(unhashedToken) return s.lookupTokenProvider(unhashedToken)
} }
func (s *fakeUserAuthTokenService) TryRotateToken(token *auth.UserToken, clientIP, userAgent string) (bool, error) { func (s *fakeUserAuthTokenService) TryRotateToken(token *m.UserToken, clientIP, userAgent string) (bool, error) {
return s.tryRotateTokenProvider(token, clientIP, userAgent) return s.tryRotateTokenProvider(token, clientIP, userAgent)
} }
func (s *fakeUserAuthTokenService) RevokeToken(token *auth.UserToken) error { func (s *fakeUserAuthTokenService) RevokeToken(token *m.UserToken) error {
return s.revokeTokenProvider(token) return s.revokeTokenProvider(token)
} }

View File

@ -3,8 +3,6 @@ package middleware
import ( import (
"testing" "testing"
"github.com/grafana/grafana/pkg/services/auth"
"fmt" "fmt"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@ -26,8 +24,8 @@ func TestOrgRedirectMiddleware(t *testing.T) {
return nil return nil
}) })
sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*auth.UserToken, error) { sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 0, UserId: 0,
UnhashedToken: "", UnhashedToken: "",
}, nil }, nil
@ -52,8 +50,8 @@ func TestOrgRedirectMiddleware(t *testing.T) {
return nil return nil
}) })
sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*auth.UserToken, error) { sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 12, UserId: 12,
UnhashedToken: "", UnhashedToken: "",
}, nil }, nil

View File

@ -5,7 +5,6 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models" m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/session" "github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
@ -81,8 +80,8 @@ func TestMiddlewareQuota(t *testing.T) {
return nil return nil
}) })
sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*auth.UserToken, error) { sc.userAuthTokenService.lookupTokenProvider = func(unhashedToken string) (*m.UserToken, error) {
return &auth.UserToken{ return &m.UserToken{
UserId: 12, UserId: 12,
UnhashedToken: "", UnhashedToken: "",
}, nil }, nil

View File

@ -4,7 +4,6 @@ import (
"strings" "strings"
"github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/session" "github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -14,7 +13,7 @@ import (
type ReqContext struct { type ReqContext struct {
*macaron.Context *macaron.Context
*SignedInUser *SignedInUser
UserToken *auth.UserToken UserToken *UserToken
// This should only be used by the auth_proxy // This should only be used by the auth_proxy
Session session.SessionStore Session session.SessionStore

32
pkg/models/user_token.go Normal file
View File

@ -0,0 +1,32 @@
package models
import "errors"
// Typed errors
var (
ErrUserTokenNotFound = errors.New("user token not found")
)
// UserToken represents a user token
type UserToken struct {
Id int64
UserId int64
AuthToken string
PrevAuthToken string
UserAgent string
ClientIp string
AuthTokenSeen bool
SeenAt int64
RotatedAt int64
CreatedAt int64
UpdatedAt int64
UnhashedToken string
}
// UserTokenService are used for generating and validating user tokens
type UserTokenService interface {
CreateToken(userId int64, clientIP, userAgent string) (*UserToken, error)
LookupToken(unhashedToken string) (*UserToken, error)
TryRotateToken(token *UserToken, clientIP, userAgent string) (bool, error)
RevokeToken(token *UserToken) error
}

View File

@ -1,16 +1 @@
package auth package auth
type UserToken struct {
Id int64
UserId int64
AuthToken string
PrevAuthToken string
UserAgent string
ClientIp string
AuthTokenSeen bool
SeenAt int64
RotatedAt int64
CreatedAt int64
UpdatedAt int64
UnhashedToken string
}

View File

@ -5,11 +5,10 @@ import (
"encoding/hex" "encoding/hex"
"time" "time"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/infra/serverlock" "github.com/grafana/grafana/pkg/infra/serverlock"
"github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
@ -40,7 +39,7 @@ func (s *UserAuthTokenServiceImpl) Init() error {
return nil return nil
} }
func (s *UserAuthTokenServiceImpl) CreateToken(userId int64, clientIP, userAgent string) (*auth.UserToken, error) { func (s *UserAuthTokenServiceImpl) CreateToken(userId int64, clientIP, userAgent string) (*models.UserToken, error) {
clientIP = util.ParseIPAddress(clientIP) clientIP = util.ParseIPAddress(clientIP)
token, err := util.RandomHex(16) token, err := util.RandomHex(16)
if err != nil { if err != nil {
@ -72,13 +71,13 @@ func (s *UserAuthTokenServiceImpl) CreateToken(userId int64, clientIP, userAgent
s.log.Debug("user auth token created", "tokenId", userAuthToken.Id, "userId", userAuthToken.UserId, "clientIP", userAuthToken.ClientIp, "userAgent", userAuthToken.UserAgent, "authToken", userAuthToken.AuthToken) s.log.Debug("user auth token created", "tokenId", userAuthToken.Id, "userId", userAuthToken.UserId, "clientIP", userAuthToken.ClientIp, "userAgent", userAuthToken.UserAgent, "authToken", userAuthToken.AuthToken)
var userToken auth.UserToken var userToken models.UserToken
err = userAuthToken.toUserToken(&userToken) err = userAuthToken.toUserToken(&userToken)
return &userToken, err return &userToken, err
} }
func (s *UserAuthTokenServiceImpl) LookupToken(unhashedToken string) (*auth.UserToken, error) { func (s *UserAuthTokenServiceImpl) LookupToken(unhashedToken string) (*models.UserToken, error) {
hashedToken := hashToken(unhashedToken) hashedToken := hashToken(unhashedToken)
if setting.Env == setting.DEV { if setting.Env == setting.DEV {
s.log.Debug("looking up token", "unhashed", unhashedToken, "hashed", hashedToken) s.log.Debug("looking up token", "unhashed", unhashedToken, "hashed", hashedToken)
@ -137,13 +136,13 @@ func (s *UserAuthTokenServiceImpl) LookupToken(unhashedToken string) (*auth.User
model.UnhashedToken = unhashedToken model.UnhashedToken = unhashedToken
var userToken auth.UserToken var userToken models.UserToken
err = model.toUserToken(&userToken) err = model.toUserToken(&userToken)
return &userToken, err return &userToken, err
} }
func (s *UserAuthTokenServiceImpl) TryRotateToken(token *auth.UserToken, clientIP, userAgent string) (bool, error) { func (s *UserAuthTokenServiceImpl) TryRotateToken(token *models.UserToken, clientIP, userAgent string) (bool, error) {
if token == nil { if token == nil {
return false, nil return false, nil
} }
@ -202,7 +201,7 @@ func (s *UserAuthTokenServiceImpl) TryRotateToken(token *auth.UserToken, clientI
return false, nil return false, nil
} }
func (s *UserAuthTokenServiceImpl) RevokeToken(token *auth.UserToken) error { func (s *UserAuthTokenServiceImpl) RevokeToken(token *models.UserToken) error {
if token == nil { if token == nil {
return ErrAuthTokenNotFound return ErrAuthTokenNotFound
} }

View File

@ -9,7 +9,7 @@ import (
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
) )
@ -163,7 +163,7 @@ func TestUserAuthToken(t *testing.T) {
model, err := ctx.getAuthTokenByID(userToken.Id) model, err := ctx.getAuthTokenByID(userToken.Id)
So(err, ShouldBeNil) So(err, ShouldBeNil)
var tok auth.UserToken var tok models.UserToken
model.toUserToken(&tok) model.toUserToken(&tok)
getTime = func() time.Time { getTime = func() time.Time {
@ -345,7 +345,7 @@ func TestUserAuthToken(t *testing.T) {
}) })
Convey("When populating userAuthToken from UserToken should copy all properties", func() { Convey("When populating userAuthToken from UserToken should copy all properties", func() {
ut := auth.UserToken{ ut := models.UserToken{
Id: 1, Id: 1,
UserId: 2, UserId: 2,
AuthToken: "a", AuthToken: "a",
@ -397,7 +397,7 @@ func TestUserAuthToken(t *testing.T) {
So(err, ShouldBeNil) So(err, ShouldBeNil)
uatMap := uatJSON.MustMap() uatMap := uatJSON.MustMap()
var ut auth.UserToken var ut models.UserToken
err = uat.toUserToken(&ut) err = uat.toUserToken(&ut)
So(err, ShouldBeNil) So(err, ShouldBeNil)
utBytes, err := json.Marshal(ut) utBytes, err := json.Marshal(ut)

View File

@ -4,7 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/models"
) )
// Typed errors // Typed errors
@ -27,13 +27,13 @@ type userAuthToken struct {
UnhashedToken string `xorm:"-"` UnhashedToken string `xorm:"-"`
} }
func userAuthTokenFromUserToken(ut *auth.UserToken) *userAuthToken { func userAuthTokenFromUserToken(ut *models.UserToken) *userAuthToken {
var uat userAuthToken var uat userAuthToken
uat.fromUserToken(ut) uat.fromUserToken(ut)
return &uat return &uat
} }
func (uat *userAuthToken) fromUserToken(ut *auth.UserToken) { func (uat *userAuthToken) fromUserToken(ut *models.UserToken) {
uat.Id = ut.Id uat.Id = ut.Id
uat.UserId = ut.UserId uat.UserId = ut.UserId
uat.AuthToken = ut.AuthToken uat.AuthToken = ut.AuthToken
@ -48,7 +48,7 @@ func (uat *userAuthToken) fromUserToken(ut *auth.UserToken) {
uat.UnhashedToken = ut.UnhashedToken uat.UnhashedToken = ut.UnhashedToken
} }
func (uat *userAuthToken) toUserToken(ut *auth.UserToken) error { func (uat *userAuthToken) toUserToken(ut *models.UserToken) error {
if uat == nil { if uat == nil {
return fmt.Errorf("needs pointer to userAuthToken struct") return fmt.Errorf("needs pointer to userAuthToken struct")
} }
@ -68,11 +68,3 @@ func (uat *userAuthToken) toUserToken(ut *auth.UserToken) error {
return nil return nil
} }
// UserAuthTokenService are used for generating and validating user auth tokens
type UserAuthTokenService interface {
CreateToken(userId int64, clientIP, userAgent string) (*auth.UserToken, error)
LookupToken(unhashedToken string) (*auth.UserToken, error)
TryRotateToken(token *auth.UserToken, clientIP, userAgent string) (bool, error)
RevokeToken(token *auth.UserToken) error
}