From 8e8705c6e50f3153196671b56fbca4ace5c2f1d3 Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Tue, 30 Jan 2018 21:33:45 +0100 Subject: [PATCH] Add tokenkey to the gin context --- auth/authentication.go | 2 +- auth/util.go | 10 ++++++++-- auth/util_test.go | 11 +++++++++-- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/auth/authentication.go b/auth/authentication.go index dbdc314..4ceed4f 100644 --- a/auth/authentication.go +++ b/auth/authentication.go @@ -104,7 +104,7 @@ func (a *Auth) requireToken(auth authenticate) gin.HandlerFunc { if user != nil || token != "" { if ok, userID := auth(token, user); ok { - RegisterAuthentication(ctx, user, userID) + RegisterAuthentication(ctx, user, userID, token) ctx.Next() return } diff --git a/auth/util.go b/auth/util.go index 21b0e97..e6468dc 100644 --- a/auth/util.go +++ b/auth/util.go @@ -5,10 +5,11 @@ import ( "github.com/jmattheis/memo/model" ) -// RegisterAuthentication registers the user or the user id; The id can later be obtained by GetUserID. -func RegisterAuthentication(ctx *gin.Context, user *model.User, userID uint) { +// RegisterAuthentication registers the user id, user and or token. +func RegisterAuthentication(ctx *gin.Context, user *model.User, userID uint, tokenID string) { ctx.Set("user", user) ctx.Set("userid", userID) + ctx.Set("tokenid", tokenID) } // GetUserID returns the user id which was previously registered by RegisterAuthentication. @@ -24,3 +25,8 @@ func GetUserID(ctx *gin.Context) uint { return user.ID } + +// GetTokenID returns the tokenID +func GetTokenID(ctx *gin.Context) string { + return ctx.MustGet("tokenid").(string) +} diff --git a/auth/util_test.go b/auth/util_test.go index 2af626a..79fa3b9 100644 --- a/auth/util_test.go +++ b/auth/util_test.go @@ -29,9 +29,16 @@ func (s *UtilSuite) Test_getID() { }) } -func (s *UtilSuite) expectUserIDWith(user *model.User, tokenID uint, expectedID uint) { +func (s *UtilSuite) Test_getToken() { ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) - RegisterAuthentication(ctx, user, tokenID) + RegisterAuthentication(ctx, nil, 1, "asdasda") + actualID := GetTokenID(ctx) + assert.Equal(s.T(), "asdasda", actualID) +} + +func (s *UtilSuite) expectUserIDWith(user *model.User, tokenUserID uint, expectedID uint) { + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + RegisterAuthentication(ctx, user, tokenUserID, "") actualID := GetUserID(ctx) assert.Equal(s.T(), expectedID, actualID) }