From aa66e9792bf229a5b173fc535b08ab5c1c96081c Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Sat, 27 Jan 2018 15:17:35 +0100 Subject: [PATCH] Add auth util for saving the user in the ctx --- auth/authentication.go | 3 ++- auth/util.go | 24 ++++++++++++++++++++++++ auth/util_test.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 auth/util.go create mode 100644 auth/util_test.go diff --git a/auth/authentication.go b/auth/authentication.go index 6f3c036..e251cfd 100644 --- a/auth/authentication.go +++ b/auth/authentication.go @@ -96,7 +96,8 @@ func (a *Auth) requireToken(auth authenticate) gin.HandlerFunc { user := a.userFromBasicAuth(ctx) if user != nil || token != "" { - if ok, _ := auth(token, user); ok { + if ok, userId := auth(token, user); ok { + RegisterAuthentication(ctx, user, userId) ctx.Next() return } diff --git a/auth/util.go b/auth/util.go new file mode 100644 index 0000000..90785e9 --- /dev/null +++ b/auth/util.go @@ -0,0 +1,24 @@ +package auth + +import ( + "github.com/gin-gonic/gin" + "github.com/jmattheis/memo/model" +) + +func RegisterAuthentication(ctx *gin.Context, user *model.User, userId uint) { + ctx.Set("user", user) + ctx.Set("userid", userId) +} + +func GetUserId(ctx *gin.Context) uint { + user := ctx.MustGet("user").(*model.User) + if user == nil { + userId := ctx.MustGet("userid").(uint) + if userId == 0 { + panic("token and user may not be null") + } + return userId + } + + return user.Id +} diff --git a/auth/util_test.go b/auth/util_test.go new file mode 100644 index 0000000..6d22fbd --- /dev/null +++ b/auth/util_test.go @@ -0,0 +1,37 @@ +package auth + +import ( + "github.com/gin-gonic/gin" + "github.com/jmattheis/memo/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "net/http/httptest" + "testing" +) + +func TestUtilSuite(t *testing.T) { + suite.Run(t, new(UtilSuite)) +} + +type UtilSuite struct { + suite.Suite +} + +func (s *UtilSuite) BeforeTest(suiteName, testName string) { + gin.SetMode(gin.TestMode) +} + +func (s *UtilSuite) Test_getId() { + s.expectUserIdWith(&model.User{Id: 2}, 0, 2) + s.expectUserIdWith(nil, 5, 5) + assert.Panics(s.T(), func() { + s.expectUserIdWith(nil, 0, 0) + }) +} + +func (s *UtilSuite) expectUserIdWith(user *model.User, tokenId uint, expectedId uint) { + ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) + RegisterAuthentication(ctx, user, tokenId) + actualId := GetUserId(ctx) + assert.Equal(s.T(), expectedId, actualId) +}