feat: implement session delete using redis
This commit is contained in:
@ -23,25 +23,31 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/model"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/usecase/usecase"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/middleware/authn"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Session interface {
|
||||
Create(*gin.Context)
|
||||
Delete(*gin.Context)
|
||||
}
|
||||
|
||||
type SessionController struct {
|
||||
userUsecase usecase.User
|
||||
cache core.Cache
|
||||
}
|
||||
|
||||
func NewSessionController(u usecase.User) Session {
|
||||
return &SessionController{u}
|
||||
func NewSessionController(u usecase.User, cache core.Cache) Session {
|
||||
return &SessionController{u, cache}
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
@ -88,3 +94,27 @@ func (sc *SessionController) Create(ctx *gin.Context) {
|
||||
Token: tokenString,
|
||||
})
|
||||
}
|
||||
|
||||
// Delete deletes a session by putting the jwt token into the cache
|
||||
func (sc *SessionController) Delete(ctx *gin.Context) {
|
||||
tk, err := token.ParseRequest(ctx)
|
||||
if err != nil || tk == nil {
|
||||
// Unlikely
|
||||
core.WriteResponse(ctx, authn.ErrTokenInvalid, nil)
|
||||
return
|
||||
}
|
||||
|
||||
exp := time.Until(tk.Expiry)
|
||||
key := fmt.Sprintf("jwt:%s", tk.Identity)
|
||||
|
||||
log.DebugLog("session delete", "key", key, "exp", exp.String())
|
||||
err = sc.cache.Set(ctx, key, tk.Raw, exp)
|
||||
if err != nil {
|
||||
// unexpected
|
||||
log.ErrorLog("error writing logged out jwt into cache", "err", err)
|
||||
core.WriteResponse(ctx, errno.InternalServerErr, nil)
|
||||
return
|
||||
}
|
||||
|
||||
core.WriteResponse(ctx, nil, "logged out")
|
||||
}
|
||||
|
@ -59,7 +59,7 @@ func TestSessionCreate(t *testing.T) {
|
||||
for _, tst := range tests {
|
||||
t.Run(tst.Name, func(t *testing.T) {
|
||||
testUserUsecase := usecasemock.NewtestUserUsecase()
|
||||
sessionController := NewSessionController(testUserUsecase)
|
||||
sessionController := NewSessionController(testUserUsecase, nil)
|
||||
r := gin.New()
|
||||
r.POST(
|
||||
"/session/create",
|
||||
|
@ -39,6 +39,7 @@ import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/pkg/version/verflag"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/net/context"
|
||||
@ -126,15 +127,23 @@ func run() error {
|
||||
}
|
||||
defer dbConn.Close(context.Background())
|
||||
|
||||
// Init Cache
|
||||
cache := datastore.NewCache(&redis.Options{
|
||||
Addr: viper.GetString("cache.host"),
|
||||
Password: viper.GetString("cache.password"),
|
||||
DB: 0,
|
||||
})
|
||||
defer cache.Close()
|
||||
|
||||
// Init token
|
||||
token.Init(viper.GetString("web.token-secret"), viper.GetDuration("web.token-expiry-time"))
|
||||
|
||||
// Register the core service
|
||||
r := registry.NewRegistry(dbConn)
|
||||
r := registry.NewRegistry(dbConn, cache)
|
||||
|
||||
engine := gin.Default()
|
||||
|
||||
engine = router.Routes(engine, r.NewAppController())
|
||||
engine = router.Routes(engine, r.NewAppController(), cache)
|
||||
|
||||
server := http.Server{
|
||||
Addr: viper.GetString("web.addr"),
|
||||
|
66
internal/howmuch/infra/datastore/cache.go
Normal file
66
internal/howmuch/infra/datastore/cache.go
Normal file
@ -0,0 +1,66 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package datastore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisCache struct {
|
||||
redis *redis.Client
|
||||
}
|
||||
|
||||
func NewCache(opt interface{}) core.Cache {
|
||||
redisOpt := opt.(*redis.Options)
|
||||
return &RedisCache{redis.NewClient(redisOpt)}
|
||||
}
|
||||
|
||||
func (c *RedisCache) Get(ctx context.Context, key string) (string, error) {
|
||||
val, err := c.redis.Get(ctx, key).Result()
|
||||
if err == redis.Nil {
|
||||
log.DebugLog("redis key not found", "key", key)
|
||||
return "", nil
|
||||
} else if err != nil {
|
||||
log.DebugLog("redis cache get error", "err", err)
|
||||
return "", err
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
func (c *RedisCache) Set(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
value interface{},
|
||||
expiration time.Duration,
|
||||
) error {
|
||||
return c.redis.Set(ctx, key, value, expiration).Err()
|
||||
}
|
||||
|
||||
func (c *RedisCache) Close() error {
|
||||
return c.redis.Close()
|
||||
}
|
@ -29,11 +29,19 @@ import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/middleware"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/middleware/authn"
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Routes(engine *gin.Engine, c controller.AppController) *gin.Engine {
|
||||
// Routes can take some options to init middlewares.
|
||||
// - Cache
|
||||
func Routes(engine *gin.Engine, c controller.AppController, opt ...interface{}) *gin.Engine {
|
||||
cache, ok := opt[0].(core.Cache)
|
||||
if !ok {
|
||||
panic("the first option must be a cache driver")
|
||||
}
|
||||
|
||||
// Middlewares
|
||||
// Cors
|
||||
corsCfg := cors.DefaultConfig()
|
||||
@ -56,14 +64,20 @@ func Routes(engine *gin.Engine, c controller.AppController) *gin.Engine {
|
||||
{
|
||||
userV1.POST("/create", func(ctx *gin.Context) { c.User.Create(ctx) })
|
||||
|
||||
userV1.Use(middleware.Authn())
|
||||
userV1.Use(authn.Authn(cache))
|
||||
userV1.GET(
|
||||
":id/info",
|
||||
func(ctx *gin.Context) { ctx.JSON(http.StatusOK, "Hello world") },
|
||||
)
|
||||
}
|
||||
|
||||
v1.POST("/session/create", func(ctx *gin.Context) { c.Session.Create(ctx) })
|
||||
sessionV1 := v1.Group("/session")
|
||||
{
|
||||
sessionV1.POST("/create", func(ctx *gin.Context) { c.Session.Create(ctx) })
|
||||
sessionV1.Use(authn.Authn(cache))
|
||||
sessionV1.POST("/delete", func(ctx *gin.Context) { c.Session.Delete(ctx) })
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return engine
|
||||
|
@ -24,6 +24,7 @@ package registry
|
||||
|
||||
import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/adapter/controller"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
@ -32,7 +33,8 @@ import (
|
||||
// It might holds other drivers when the projects grows. For example
|
||||
// the object needed to connect to Redis or Kafka.
|
||||
type registry struct {
|
||||
db *pgx.Conn
|
||||
db *pgx.Conn
|
||||
cache core.Cache
|
||||
}
|
||||
|
||||
// Registry returns a new app controller that will be used by main()/run()
|
||||
@ -43,8 +45,8 @@ type Registry interface {
|
||||
}
|
||||
|
||||
// NewRegistry returns a new Registry's implementation.
|
||||
func NewRegistry(db *pgx.Conn) Registry {
|
||||
return ®istry{db: db}
|
||||
func NewRegistry(db *pgx.Conn, cache core.Cache) Registry {
|
||||
return ®istry{db: db, cache: cache}
|
||||
}
|
||||
|
||||
// NewAppController creates a new AppController with controller struct for
|
||||
|
@ -31,5 +31,5 @@ import (
|
||||
// NewSessionController returns a session controller's implementation
|
||||
func (r *registry) NewSessionController() controller.Session {
|
||||
u := usecase.NewUserUsecase(repo.NewUserRepository(r.db), repo.NewDBRepository(r.db))
|
||||
return controller.NewSessionController(u)
|
||||
return controller.NewSessionController(u, r.cache)
|
||||
}
|
||||
|
34
internal/pkg/core/cache.go
Normal file
34
internal/pkg/core/cache.go
Normal file
@ -0,0 +1,34 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Cache interface {
|
||||
Get(ctx context.Context, key string) (string, error)
|
||||
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
|
||||
Close() error
|
||||
}
|
@ -20,13 +20,15 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package middleware
|
||||
package authn
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/shared"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"github.com/gin-gonic/gin"
|
||||
@ -38,8 +40,14 @@ var ErrTokenInvalid = &errno.Errno{
|
||||
Message: "invalid token",
|
||||
}
|
||||
|
||||
var ErrLoggedOut = &errno.Errno{
|
||||
HTTP: http.StatusUnauthorized,
|
||||
Code: errno.ErrorCode(errno.AuthFailureCode, "LoggedOut"),
|
||||
Message: "logged out, please log in",
|
||||
}
|
||||
|
||||
// Authn authenticates a user's access by validating their token.
|
||||
func Authn() gin.HandlerFunc {
|
||||
func Authn(cache core.Cache) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
tk, err := token.ParseRequest(ctx)
|
||||
if err != nil || tk == nil {
|
||||
@ -48,7 +56,20 @@ func Authn() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: check if the key is on logout blacklist.
|
||||
key := fmt.Sprintf("jwt:%s", tk.Identity)
|
||||
|
||||
val, err := cache.Get(ctx, key)
|
||||
if err != nil {
|
||||
log.ErrorLog("cache get token", "err", err)
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
if val != "" {
|
||||
// blacklist
|
||||
core.WriteResponse(ctx, ErrLoggedOut, nil)
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Header(shared.XUserName, tk.Identity)
|
||||
ctx.Next()
|
117
internal/pkg/middleware/authn/authn_test.go
Normal file
117
internal/pkg/middleware/authn/authn_test.go
Normal file
@ -0,0 +1,117 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package authn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/shared"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/test"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/token"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var loggedOutID string
|
||||
|
||||
type testCache struct{}
|
||||
|
||||
func (tc *testCache) Get(ctx context.Context, key string) (string, error) {
|
||||
loggedOutKey := fmt.Sprintf("jwt:%s", loggedOutID)
|
||||
if key == loggedOutKey {
|
||||
return "found", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (c *testCache) Set(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
value interface{},
|
||||
expiration time.Duration,
|
||||
) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *testCache) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestAuthn(t *testing.T) {
|
||||
token.Init("secret", 1*time.Second)
|
||||
tk, _ := token.Sign("user")
|
||||
|
||||
tkParsed, _ := token.Parse(tk)
|
||||
loggedOutID = tkParsed.Identity
|
||||
|
||||
cache := &testCache{}
|
||||
|
||||
t.Run("token found in cache", func(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(Authn(cache))
|
||||
|
||||
r.GET("/example", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
res := test.PerformRequest(
|
||||
t,
|
||||
r,
|
||||
"GET",
|
||||
"/example",
|
||||
nil,
|
||||
test.Header{Key: shared.XUserName, Value: "user"},
|
||||
test.Header{Key: "Authorization", Value: fmt.Sprintf("Bearer %s", tk)},
|
||||
)
|
||||
assert.Equal(t, http.StatusUnauthorized, res.Result().StatusCode, res.Body)
|
||||
|
||||
var err errno.Errno
|
||||
json.NewDecoder(res.Result().Body).Decode(&err)
|
||||
assert.Equal(t, "AuthFailure.LoggedOut", err.Code)
|
||||
})
|
||||
|
||||
t.Run("token not found in cache", func(t *testing.T) {
|
||||
newTk, _ := token.Sign("user2")
|
||||
r := gin.New()
|
||||
r.Use(Authn(cache))
|
||||
|
||||
r.GET("/example", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
res := test.PerformRequest(
|
||||
t,
|
||||
r,
|
||||
"GET",
|
||||
"/example",
|
||||
nil,
|
||||
test.Header{Key: shared.XUserName, Value: "user2"},
|
||||
test.Header{Key: "Authorization", Value: fmt.Sprintf("Bearer %s", newTk)},
|
||||
)
|
||||
assert.Equal(t, http.StatusOK, res.Result().StatusCode, res.Body)
|
||||
})
|
||||
}
|
@ -1,3 +1,25 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package shared
|
||||
|
||||
const (
|
||||
|
@ -43,6 +43,7 @@ type Claims struct {
|
||||
}
|
||||
|
||||
type TokenResp struct {
|
||||
Raw string
|
||||
Identity string
|
||||
Expiry time.Time
|
||||
}
|
||||
@ -91,6 +92,7 @@ func Parse(tokenString string) (*TokenResp, error) {
|
||||
|
||||
if claims, ok := token.Claims.(*Claims); ok {
|
||||
return &TokenResp{
|
||||
tokenString,
|
||||
claims.IdentityKey,
|
||||
claims.ExpiresAt.Time,
|
||||
}, nil
|
||||
|
Reference in New Issue
Block a user