Skip to content

Commit

Permalink
add redis gateway/twirp/middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
dehwyy committed Nov 22, 2023
1 parent c206365 commit a145e90
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 16 deletions.
3 changes: 3 additions & 0 deletions apps/gateway/twirp/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ require (
)

require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/kelseyhightower/envconfig v1.4.0 // indirect
github.com/redis/go-redis/v9 v9.3.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.26.0 // indirect
golang.org/x/net v0.14.0 // indirect
Expand Down
6 changes: 6 additions & 0 deletions apps/gateway/twirp/go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
Expand All @@ -18,6 +22,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.3.0 h1:RiVDjmig62jIWp7Kk4XVLs0hzV6pI3PyTnnL0cnn0u0=
github.com/redis/go-redis/v9 v9.3.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchtv/twirp v8.1.3+incompatible h1:+F4TdErPgSUbMZMwp13Q/KgDVuI7HJXP61mNV3/7iuU=
Expand Down
5 changes: 3 additions & 2 deletions apps/gateway/twirp/internal/middleware/only_authorized.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import (
"net/http"

"github.com/dehwyy/makoto/libs/logger"
"github.com/redis/go-redis/v9"
)

type onlyAuthorized struct {
md *withAuthorization
}

func NewMiddleware_OnlyAuthorized(url string, l logger.Logger) *onlyAuthorized {
func NewMiddleware_OnlyAuthorized(url string, rds *redis.Client, l logger.Logger) *onlyAuthorized {
return &onlyAuthorized{
md: NewMiddleware_WithAuthorization(url, l),
md: NewMiddleware_WithAuthorization(url, rds, l),
}
}

Expand Down
48 changes: 35 additions & 13 deletions apps/gateway/twirp/internal/middleware/with_authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,25 @@ import (
"context"
"net/http"
"strings"
"time"

"github.com/dehwyy/makoto/libs/grpc/generated/auth"
"github.com/dehwyy/makoto/libs/logger"
"github.com/redis/go-redis/v9"
"github.com/twitchtv/twirp"
)

type withAuthorization struct {
authorizationClientUrl string
l logger.Logger
redis *redis.Client
}

func NewMiddleware_WithAuthorization(authorizationClientUrl string, l logger.Logger) *withAuthorization {
func NewMiddleware_WithAuthorization(authorizationClientUrl string, rds *redis.Client, l logger.Logger) *withAuthorization {
return &withAuthorization{
authorizationClientUrl: authorizationClientUrl,
l: l,
redis: rds,
}
}

Expand All @@ -34,24 +38,42 @@ func (middleware *withAuthorization) Middleware(next http.Handler) http.Handler
return
}

var userId string
token = split_token[1]

twirpAuthorizationClient := auth.NewAuthRPCProtobufClient(middleware.authorizationClientUrl, &http.Client{})
// try to get values from redis
// looks like {"token": "userId"}
redis_value, err := middleware.redis.Get(ctx, token).Result()

res, err := twirpAuthorizationClient.SignIn(ctx, &auth.SignInRequest{
AuthMethod: &auth.SignInRequest_Token{
Token: token,
},
})
if err != nil {
middleware.l.Errorf("failed to call SignIn in AuthorizationMiddleware: %v", err)
next.ServeHTTP(w, r)
return
middleware.l.Infof("redis value: for %s, %s", token, redis_value)

if err == redis.Nil {
twirpAuthorizationClient := auth.NewAuthRPCProtobufClient(middleware.authorizationClientUrl, &http.Client{})

res, err := twirpAuthorizationClient.SignIn(ctx, &auth.SignInRequest{
AuthMethod: &auth.SignInRequest_Token{
Token: token,
},
})
if err != nil {
middleware.l.Errorf("failed to call SignIn in AuthorizationMiddleware: %v", err)
next.ServeHTTP(w, r)
return
}

// cache for 10 minutes
middleware.redis.Set(ctx, token, res.UserId, time.Minute*10)

userId = res.UserId
token = res.Token
} else {
// if value was found
userId = redis_value
}

// set value to ctx
ctx = context.WithValue(ctx, _CtxKeyUserId, res.UserId)
ctx = context.WithValue(ctx, _CtxKeyAuthorizationHeader, res.Token)
ctx = context.WithValue(ctx, _CtxKeyUserId, userId)
ctx = context.WithValue(ctx, _CtxKeyAuthorizationHeader, token)

// attach context to request
r = r.WithContext(ctx)
Expand Down
9 changes: 8 additions & 1 deletion apps/gateway/twirp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,18 @@ import (
"github.com/dehwyy/makoto/libs/logger"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
"github.com/redis/go-redis/v9"
)

func main() {
log := logger.New()
config := makoto_config.New()

rds := redis.NewClient(&redis.Options{
Addr: config.GatewayRedisUrl,
DB: 0,
})

r := chi.NewRouter()

r.Use(cors.Handler(cors.Options{
Expand All @@ -28,7 +35,7 @@ func main() {
// middleware that reads the `Authorization` header (as twirp doesn't give access to it directly)
md_with_authorization_header := middleware.NewMiddleware_WithAuthorizationHeader()
// md_with_authorization := middleware.NewMiddleware_WithAuthorization(config.AuthUrl, log)
md_only_with_authorization := middleware.NewMiddleware_OnlyAuthorized(config.AuthUrl, log)
md_only_with_authorization := middleware.NewMiddleware_OnlyAuthorized(config.AuthUrl, rds, log)

// services
authorization_service := twirp.NewAuthorizationService(config.AuthUrl, config.UserUrl, twirp.TwirpAuthorizationService{
Expand Down

0 comments on commit a145e90

Please sign in to comment.