Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get the user roles/status from the db instead of token #18

Merged
merged 2 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions casbin/policy.csv
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,19 @@ p, any, /google, GET
p, any, /oauth2/*/login, GET
p, any, /oauth2/*/callback, GET

p, user, /me, (GET)|(PUT)
p, user, /me, (GET)|(PATCH)
p, user, /me/personal_access_tokens, (GET)|(POST)
p, user, /me/personal_access_tokens/:id, (GET)|(DELETE)
p, user, /tasks, (GET)|(POST)
p, user, /tasks/:id, (GET)|(PUT)|(DELETE)
p, user, /tasks/:id, (GET)|(PATCH)|(DELETE)
p, user, /tasks/:id/transition, PUT
p, user, /users/:id, GET
p, user, /users/:id_or_username, GET

p, admin, /users, GET
p, admin, /users/:id, PUT
p, admin, /users/:id/status, PUT
p, admin, /users/:id_or_username, PATCH
p, admin, /users/:id_or_username/ban, (PUT)|(DELETE)
p, admin, /users/:id_or_username/lock, (PUT)|(DELETE)
p, admin, /users/:id_or_username/roles/:role, (PUT)|(DELETE)

g, *, any
g, user, any
Expand Down
16 changes: 8 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ require (
github.com/alexferl/golib/http/api v0.0.0-20240228040247-93f62184757c
github.com/alexferl/golib/log v0.0.0-20240228040247-93f62184757c
github.com/alexferl/httplink v0.1.0
github.com/casbin/casbin/v2 v2.82.0
github.com/casbin/casbin/v2 v2.84.1
github.com/labstack/echo/v4 v4.11.4
github.com/lestrrat-go/jwx/v2 v2.0.21
github.com/matthewhartstonge/argon2 v1.0.0
Expand All @@ -22,22 +22,22 @@ require (
github.com/stretchr/testify v1.9.0
go.mongodb.org/mongo-driver v1.14.0
go.uber.org/automaxprocs v1.5.3
golang.org/x/oauth2 v0.15.0
golang.org/x/oauth2 v0.18.0
)

require (
cloud.google.com/go/compute v1.23.3 // indirect
cloud.google.com/go/compute v1.25.0 // indirect
cloud.google.com/go/compute/metadata v0.2.3 // indirect
github.com/casbin/govaluate v1.1.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/getkin/kin-openapi v0.123.0 // indirect
github.com/go-openapi/jsonpointer v0.20.3 // indirect
github.com/go-openapi/swag v0.22.10 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
Expand Down Expand Up @@ -82,8 +82,8 @@ require (
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.31.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
36 changes: 17 additions & 19 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk=
cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI=
cloud.google.com/go/compute v1.25.0 h1:H1/4SqSUhjPFE7L5ddzHOfY2bCAvjwNRZPNl6Ni5oYU=
cloud.google.com/go/compute v1.25.0/go.mod h1:GR7F0ZPZH8EhChlMo9FkLd7eUTwEymjqQagxzilIxIE=
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
github.com/alexferl/echo-casbin v1.0.0 h1:5EV1DpVvpVtygtKK50s0Sk8YLZKmKJCaoUnOSu9D/LA=
Expand All @@ -18,8 +18,8 @@ github.com/alexferl/golib/log v0.0.0-20240228040247-93f62184757c h1:EGHN+74BItaX
github.com/alexferl/golib/log v0.0.0-20240228040247-93f62184757c/go.mod h1:fX5j3IQXCTT7IXVzZxzv4rR1Umt/vVNXwSjr7M9kiiI=
github.com/alexferl/httplink v0.1.0 h1:2Wps+hbWSFEz1cOCddmE3BJg7YoKuFU/XPFBjHFFGYg=
github.com/alexferl/httplink v0.1.0/go.mod h1:fNi0VlNX8Dro/6KZKTV3huWTdevbIeIuNZJykIxe1MQ=
github.com/casbin/casbin/v2 v2.82.0 h1:2CgvunqQQoepcbGRnMc9vEcDhuqh3B5yWKoj+kKSxf8=
github.com/casbin/casbin/v2 v2.82.0/go.mod h1:jX8uoN4veP85O/n2674r2qtfSXI6myvxW85f6TH50fw=
github.com/casbin/casbin/v2 v2.84.1 h1:pmIo88Os4cL7rrjwe+/8N8yBPIMxTC+LiKKzY5z+Xdo=
github.com/casbin/casbin/v2 v2.84.1/go.mod h1:jX8uoN4veP85O/n2674r2qtfSXI6myvxW85f6TH50fw=
github.com/casbin/govaluate v1.1.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
github.com/casbin/govaluate v1.1.1 h1:J1rFKIBhiC5xr0APd5HP6rDL+xt+BRoyq1pa4o2i/5c=
github.com/casbin/govaluate v1.1.1/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
Expand All @@ -36,10 +36,10 @@ github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nos
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/getkin/kin-openapi v0.123.0 h1:zIik0mRwFNLyvtXK274Q6ut+dPh6nlxBp0x7mNrPhs8=
github.com/getkin/kin-openapi v0.123.0/go.mod h1:wb1aSZA/iWmorQP9KTAS/phLj/t17B5jT7+fS8ed9NM=
github.com/go-openapi/jsonpointer v0.20.3 h1:jykzYWS/kyGtsHfRt6aV8JTB9pcQAXPIA7qlZ5aRlyk=
github.com/go-openapi/jsonpointer v0.20.3/go.mod h1:c7l0rjoouAuIxCm8v/JWKRgMjDG/+/7UBWsXMrv6PsM=
github.com/go-openapi/swag v0.22.10 h1:4y86NVn7Z2yYd6pfS4Z+Nyh3aAUL3Nul+LMbhFKy0gA=
github.com/go-openapi/swag v0.22.10/go.mod h1:Cnn8BYtRlx6BNE3DPN86f/xkapGIcLWzh3CLEb4C1jI=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
Expand All @@ -49,10 +49,10 @@ github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keL
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc=
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
Expand Down Expand Up @@ -182,14 +182,13 @@ golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/oauth2 v0.15.0 h1:s8pnnxNVzjWyrvYdFUQq5llS1PX2zhPXmccZv99h7uQ=
golang.org/x/oauth2 v0.15.0/go.mod h1:q48ptWNTY5XWf+JNten23lcvHpLJ0ZSxF5ttTHKVCAM=
golang.org/x/oauth2 v0.18.0 h1:09qnuIAgzdx1XplqJvW6CQqMCtGZykZWcXzPMPUusvI=
golang.org/x/oauth2 v0.18.0/go.mod h1:Wf7knwG0MPoWIMMBgFlEaSUDaKskp0dCfrlJRJXbBi8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
Expand All @@ -208,7 +207,6 @@ golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
Expand All @@ -222,12 +220,12 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
Expand Down
10 changes: 6 additions & 4 deletions handlers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,13 @@ type LogoutRequest struct {
}

func (h *AuthHandler) logout(c echo.Context) error {
token := c.Get("refresh_token").(jwx.Token)
currentUser := c.Get("user").(*models.User)
encodedToken := c.Get("refresh_token_encoded").(string)

ctx, cancel := context.WithTimeout(c.Request().Context(), time.Second*10)
defer cancel()

user, err := h.svc.Read(ctx, token.Subject())
user, err := h.svc.Read(ctx, currentUser.Id)
if err != nil {
var se *services.Error
if errors.As(err, &se) {
Expand Down Expand Up @@ -237,8 +237,9 @@ func (h *AuthHandler) signup(c echo.Context) error {
if se.Kind == services.Exist {
return h.Validate(c, http.StatusConflict, echo.Map{"message": se.Message})
}
} else {
log.Error().Err(err).Msg("failed getting user")
}
log.Error().Err(err).Msg("failed getting user")
}

user := models.NewUser(body.Email, body.Username)
Expand All @@ -259,8 +260,9 @@ func (h *AuthHandler) signup(c echo.Context) error {
if se.Kind == services.Exist {
return h.Validate(c, http.StatusConflict, echo.Map{"message": se.Message})
}
} else {
log.Error().Err(err).Msg("failed inserting new user")
}
log.Error().Err(err).Msg("failed inserting new user")
return err
}

Expand Down
33 changes: 12 additions & 21 deletions handlers/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/alexferl/echo-boilerplate/config"
"github.com/alexferl/echo-boilerplate/handlers"
"github.com/alexferl/echo-boilerplate/models"
"github.com/alexferl/echo-boilerplate/server"
"github.com/alexferl/echo-boilerplate/services"
"github.com/alexferl/echo-boilerplate/util/cookie"
"github.com/alexferl/echo-boilerplate/util/jwt"
Expand All @@ -34,9 +33,10 @@ type AuthHandlerTestSuite struct {

func (s *AuthHandlerTestSuite) SetupTest() {
svc := handlers.NewMockUserService(s.T())
patSvc := handlers.NewMockPersonalAccessTokenService(s.T())
h := handlers.NewAuthHandler(openapi.NewHandler(), svc)
s.svc = svc
s.server = server.NewTestServer(h)
s.server = getServer(svc, patSvc, h)
}

func TestAuthHandlerTestSuite(t *testing.T) {
Expand Down Expand Up @@ -158,19 +158,6 @@ func (s *AuthHandlerTestSuite) TestAuthHandler_Login_400() {
assert.Equal(s.T(), http.StatusBadRequest, resp.Code)
}

// TODO: fix
//func (s *AuthHandlerTestSuite) TestAuthHandler_Login_422() {
// b, _ := json.Marshal(`{"username":"foo","password":"bar","derp":"dep"}`)
//
// req := httptest.NewRequest(http.MethodPost, "/auth/login", bytes.NewBuffer(b))
// req.Header.Set("Content-Type", "application/json")
// resp := httptest.NewRecorder()
//
// s.server.ServeHTTP(resp, req)
//
// assert.Equal(s.T(), http.StatusUnprocessableEntity, resp.Code)
//}

func (s *AuthHandlerTestSuite) TestAuthHandler_Logout_204_Cookie() {
user := models.NewUser("test@example.com", "test")
_, refresh, _ := user.Login()
Expand Down Expand Up @@ -600,28 +587,30 @@ func (s *AuthHandlerTestSuite) TestAuthHandler_Signup_422() {
func (s *AuthHandlerTestSuite) TestAuthHandler_Token_200() {
user := models.NewUser("test@example.com", "test")
access, _, _ := user.Login()

token, _ := jwt.ParseEncoded(access)

req := httptest.NewRequest(http.MethodGet, "/auth/token", nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", access))
resp := httptest.NewRecorder()

// middleware
s.svc.EXPECT().
Read(mock.Anything, mock.Anything).
Return(user, nil).Once()

s.server.ServeHTTP(resp, req)

var result handlers.TokenResponse
_ = json.Unmarshal(resp.Body.Bytes(), &result)

roles, _ := token.Get("roles")
typ, _ := token.Get("type")

assert.Equal(s.T(), http.StatusOK, resp.Code)
assert.Equal(s.T(), token.Expiration(), result.Exp)
assert.Equal(s.T(), token.IssuedAt(), result.Iat)
assert.Equal(s.T(), token.Issuer(), result.Iss)
assert.Equal(s.T(), token.NotBefore(), result.Nbf)
assert.ElementsMatch(s.T(), roles, user.Roles)
assert.Equal(s.T(), token.Subject(), result.Sub)
assert.Equal(s.T(), typ, result.Type)
}
Expand All @@ -643,28 +632,30 @@ func (s *AuthHandlerTestSuite) TestAuthHandler_Token_401() {
func (s *AuthHandlerTestSuite) TestAuthHandler_Cookie_200() {
user := models.NewUser("test@example.com", "test")
access, _, _ := user.Login()

token, _ := jwt.ParseEncoded(access)

req := httptest.NewRequest(http.MethodGet, "/auth/token", nil)
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie.NewAccessToken(access))
resp := httptest.NewRecorder()

// middleware
s.svc.EXPECT().
Read(mock.Anything, mock.Anything).
Return(user, nil).Once()

s.server.ServeHTTP(resp, req)

var result handlers.TokenResponse
_ = json.Unmarshal(resp.Body.Bytes(), &result)

roles, _ := token.Get("roles")
typ, _ := token.Get("type")

assert.Equal(s.T(), http.StatusOK, resp.Code)
assert.Equal(s.T(), token.Expiration(), result.Exp)
assert.Equal(s.T(), token.IssuedAt(), result.Iat)
assert.Equal(s.T(), token.Issuer(), result.Iss)
assert.Equal(s.T(), token.NotBefore(), result.Nbf)
assert.ElementsMatch(s.T(), roles, user.Roles)
assert.Equal(s.T(), token.Subject(), result.Sub)
assert.Equal(s.T(), typ, result.Type)
}
Expand Down
11 changes: 5 additions & 6 deletions handlers/personal_access_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/alexferl/echo-openapi"
"github.com/alexferl/golib/http/api/server"
"github.com/labstack/echo/v4"
jwx "github.com/lestrrat-go/jwx/v2/jwt"
"github.com/rs/zerolog/log"

"github.com/alexferl/echo-boilerplate/models"
Expand Down Expand Up @@ -49,7 +48,7 @@ type CreatePersonalAccessTokenRequest struct {
}

func (h *PersonalAccessTokenHandler) create(c echo.Context) error {
token := c.Get("token").(jwx.Token)
currentUser := c.Get("user").(*models.User)

body := &CreatePersonalAccessTokenRequest{}
if err := c.Bind(body); err != nil {
Expand All @@ -60,7 +59,7 @@ func (h *PersonalAccessTokenHandler) create(c echo.Context) error {
ctx, cancel := context.WithTimeout(c.Request().Context(), time.Second*10)
defer cancel()

res, err := h.svc.FindOne(ctx, token.Subject(), body.Name)
res, err := h.svc.FindOne(ctx, currentUser.Id, body.Name)
if err != nil {
var se *services.Error
if !errors.As(err, &se) {
Expand All @@ -73,7 +72,7 @@ func (h *PersonalAccessTokenHandler) create(c echo.Context) error {
return h.Validate(c, http.StatusConflict, echo.Map{"message": "token name already in-use"})
}

newPAT, err := models.NewPersonalAccessToken(token, body.Name, body.ExpiresAt)
newPAT, err := models.NewPersonalAccessToken(currentUser.Id, body.Name, body.ExpiresAt)
if err != nil {
if errors.Is(err, models.ErrExpiresAtPast) {
m := echo.Map{
Expand Down Expand Up @@ -104,12 +103,12 @@ func (h *PersonalAccessTokenHandler) create(c echo.Context) error {
}

func (h *PersonalAccessTokenHandler) list(c echo.Context) error {
token := c.Get("token").(jwx.Token)
currentUser := c.Get("user").(*models.User)

ctx, cancel := context.WithTimeout(c.Request().Context(), time.Second*10)
defer cancel()

pats, err := h.svc.Find(ctx, token.Subject())
pats, err := h.svc.Find(ctx, currentUser.Id)
if err != nil {
log.Error().Err(err).Msg("failed getting personal access token")
return err
Expand Down
Loading
Loading