Add auth util for saving the user in the ctx

This commit is contained in:
Jannis Mattheis 2018-01-27 15:17:35 +01:00 committed by Jannis Mattheis
parent 8a989dc29a
commit aa66e9792b
3 changed files with 63 additions and 1 deletions

View File

@ -96,7 +96,8 @@ func (a *Auth) requireToken(auth authenticate) gin.HandlerFunc {
user := a.userFromBasicAuth(ctx) user := a.userFromBasicAuth(ctx)
if user != nil || token != "" { if user != nil || token != "" {
if ok, _ := auth(token, user); ok { if ok, userId := auth(token, user); ok {
RegisterAuthentication(ctx, user, userId)
ctx.Next() ctx.Next()
return return
} }

24
auth/util.go Normal file
View File

@ -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
}

37
auth/util_test.go Normal file
View File

@ -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)
}