Add auth util for saving the user in the ctx
This commit is contained in:
parent
8a989dc29a
commit
aa66e9792b
|
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
@ -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)
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue