chore: update session and challenge repo -- using Redis for caching session and challenge verifying -- added api handler docs

This commit is contained in:
2025-09-09 13:31:41 +03:30
parent dee9ce2f64
commit 6bf6a8ffc2
20 changed files with 1077 additions and 193 deletions
-1
View File
@@ -13,7 +13,6 @@ type ChallengeResponse struct {
type AuthenticateRequest struct {
PubKey string `json:"pubKey" validate:"required,eth_pubkey"`
Signature string `json:"signature" validate:"required,eth_signature"`
Message string `json:"message" validate:"required,uuid"`
}
type AuthenticateResponse struct {
+24 -20
View File
@@ -2,12 +2,9 @@ package http
import (
"backend/internal/api/dto"
"backend/internal/domain"
"backend/internal/usecase"
"time"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
type AuthHandler struct {
@@ -20,6 +17,17 @@ func NewAuthHandler(authService *usecase.AuthService) *AuthHandler {
}
}
// GenerateChallenge generates a challenge for authentication
// @Summary Generate authentication challenge
// @Description Generate a challenge message for wallet authentication
// @Tags auth
// @Accept json
// @Produce json
// @Param request body dto.ChallengeRequest true "Challenge Request"
// @Success 200 {object} dto.ChallengeResponse
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /auth/challenge [post]
func (h *AuthHandler) GenerateChallenge(c *fiber.Ctx) error {
var req dto.ChallengeRequest
if err := c.BodyParser(&req); err != nil {
@@ -30,18 +38,29 @@ func (h *AuthHandler) GenerateChallenge(c *fiber.Ctx) error {
challenge, err := h.authService.GenerateChallenge(c.Context(), req.PubKey)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to generate challenge",
"error": err.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(
dto.ChallengeResponse{
Message: challenge.Message.String(),
Message: challenge.Message,
TimeStamp: challenge.TimeStamp.String(),
ExpiresAt: challenge.ExpiresAt.String(),
},
)
}
// Authenticate authenticates a user with signed challenge
// @Summary Authenticate user
// @Description Authenticate user with wallet signature
// @Tags auth
// @Accept json
// @Produce json
// @Param request body dto.AuthenticateRequest true "Authentication Request"
// @Success 200 {object} dto.AuthenticateResponse
// @Failure 400 {object} map[string]string
// @Failure 401 {object} map[string]string
// @Router /auth/authenticate [post]
func (h *AuthHandler) Authenticate(c *fiber.Ctx) error {
var req dto.AuthenticateRequest
if err := c.BodyParser(&req); err != nil {
@@ -50,25 +69,10 @@ func (h *AuthHandler) Authenticate(c *fiber.Ctx) error {
})
}
messageUUID, err := uuid.Parse(req.Message)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "invalid message format",
})
}
challenge := &domain.Challenge{
Message: messageUUID,
//TODO: fetch from cache
TimeStamp: time.Now().UTC(),
ExpiresAt: time.Now().Add(5 * time.Minute),
}
userToken, err := h.authService.Authenticate(
c.Context(),
req.PubKey,
req.Signature,
challenge,
// add chainID to cfg
1,
c.IP(),
+21 -7
View File
@@ -2,26 +2,40 @@ package http
import (
"backend/config"
"backend/docs"
httpHandlers "backend/internal/api/http/handlers"
"backend/internal/app"
"fmt"
"log"
"github.com/gofiber/adaptor/v2"
"github.com/gofiber/fiber/v2"
httpSwagger "github.com/swaggo/http-swagger"
)
func Run(cfg config.Server, app *app.AppContainer) {
fiberApp := fiber.New()
api := fiberApp.Group("/api")
// register routes here
router := fiber.New()
api := router.Group("/api")
registerPublicRoutes(api, app)
log.Fatal(fiberApp.Listen(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)))
docs.SwaggerInfo.Host = ""
docs.SwaggerInfo.Schemes = []string{}
docs.SwaggerInfo.BasePath = "/api"
router.Get("/swagger/*", adaptor.HTTPHandler(httpSwagger.Handler()))
log.Fatal(router.Listen(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)))
}
func registerPublicRoutes(router fiber.Router, app *app.AppContainer) {
authgroup := router.Group("/auth")
//TODO: implement handlers
authgroup.Post("/challenge")
authgroup.Post("/authenticate")
authService := app.AuthService()
authHandler := httpHandlers.NewAuthHandler(&authService)
// Register auth routes
authgroup.Post("/challenge", authHandler.GenerateChallenge)
authgroup.Post("/authenticate", authHandler.Authenticate)
}
+65
View File
@@ -2,7 +2,13 @@ package app
import (
"backend/config"
"backend/internal/repository/cache"
"backend/internal/repository/storage"
"backend/internal/usecase"
cachePackage "backend/pkg/cache"
"backend/pkg/postgres"
"fmt"
"log"
"gorm.io/gorm"
)
@@ -10,5 +16,64 @@ import (
type AppContainer struct {
cfg config.Config
dbConn *gorm.DB
redis *cachePackage.Redis
authService usecase.AuthService
}
func NewAppContainer(cfg config.Config) (*AppContainer, error) {
dbOptions := postgres.DBConnOptions{
User: cfg.DB.User,
Pass: cfg.DB.Pass,
Host: cfg.DB.Host,
Port: uint(cfg.DB.Port),
DBName: cfg.DB.DBName,
}
dbConn, err := postgres.NewPsqlGormConnection(dbOptions)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
redis, err := cachePackage.NewRedis(cfg.Redis)
if err != nil {
return nil, fmt.Errorf("failed to connect to Redis: %w", err)
}
userRepo := storage.NewUserRepository(dbConn)
sessionRepo := cache.NewSessionRepository(redis)
challengeRepo := cache.NewChallengeRepository(redis)
authService := usecase.NewAuthService(
userRepo,
sessionRepo,
challengeRepo,
30,
cfg.JWT,
)
return &AppContainer{
cfg: cfg,
dbConn: dbConn,
redis: redis,
authService: authService,
}, nil
}
func (app *AppContainer) AuthService() usecase.AuthService {
return app.authService
}
func (app *AppContainer) Close() {
if app.redis != nil {
if err := app.redis.Close(); err != nil {
log.Printf("Error closing Redis connection: %v", err)
}
}
if app.dbConn != nil {
if sqlDB, err := app.dbConn.DB(); err == nil {
if err := sqlDB.Close(); err != nil {
log.Printf("Error closing database connection: %v", err)
}
}
}
}
+8 -2
View File
@@ -32,6 +32,12 @@ type UserRepo interface {
Delete(ctx context.Context, id uuid.UUID) error
}
type ChallengeRepo interface {
Create(ctx context.Context, pubKey string, challenge *Challenge) error
GetByPubKey(ctx context.Context, pubKey string) (*Challenge, error)
Delete(ctx context.Context, pubKey string) error
}
type User struct {
ID uuid.UUID
PubKey string
@@ -51,7 +57,7 @@ type User struct {
// TODO: move to another file?
type Challenge struct {
Message uuid.UUID
Message string
TimeStamp time.Time
ExpiresAt time.Time
}
@@ -70,7 +76,7 @@ func (c *Challenge) Verify(address string, signedMsg string) (bool, error) {
return false, fmt.Errorf("decode signature: %w", err)
}
challengeBytes := []byte(c.Message.String())
challengeBytes := []byte(c.Message)
return c.VerifySignedBytes(address, challengeBytes, signature)
}
View File
+80
View File
@@ -0,0 +1,80 @@
package cache
import (
"backend/internal/domain"
"backend/pkg/cache"
"context"
"encoding/json"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
type ChallengeRepository struct {
redis *cache.Redis
}
func NewChallengeRepository(redis *cache.Redis) domain.ChallengeRepo {
return &ChallengeRepository{
redis: redis,
}
}
func (r *ChallengeRepository) Create(ctx context.Context, pubKey string, challenge *domain.Challenge) error {
key := r.getChallengeKey(pubKey)
challengeData, err := json.Marshal(challenge)
if err != nil {
return fmt.Errorf("failed to marshal challenge: %w", err)
}
ttl := time.Until(challenge.ExpiresAt)
if ttl <= 0 {
return fmt.Errorf("challenge already expired")
}
if err := r.redis.Client().Set(ctx, key, challengeData, ttl).Err(); err != nil {
return fmt.Errorf("failed to store challenge in Redis: %w", err)
}
return nil
}
func (r *ChallengeRepository) GetByPubKey(ctx context.Context, pubKey string) (*domain.Challenge, error) {
key := r.getChallengeKey(pubKey)
result, err := r.redis.Client().Get(ctx, key).Result()
if err != nil {
if err == redis.Nil {
return nil, fmt.Errorf("challenge not found")
}
return nil, fmt.Errorf("failed to get challenge from Redis: %w", err)
}
var challenge domain.Challenge
if err := json.Unmarshal([]byte(result), &challenge); err != nil {
return nil, fmt.Errorf("failed to unmarshal challenge: %w", err)
}
if challenge.IsExpired() {
r.Delete(ctx, pubKey)
return nil, fmt.Errorf("challenge expired")
}
return &challenge, nil
}
func (r *ChallengeRepository) Delete(ctx context.Context, pubKey string) error {
key := r.getChallengeKey(pubKey)
if err := r.redis.Client().Del(ctx, key).Err(); err != nil {
return fmt.Errorf("failed to delete challenge from Redis: %w", err)
}
return nil
}
func (r *ChallengeRepository) getChallengeKey(pubKey string) string {
return fmt.Sprintf("challenge:%s", pubKey)
}
+135
View File
@@ -0,0 +1,135 @@
package cache
import (
"backend/internal/domain"
"backend/pkg/cache"
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
type SessionRepository struct {
redis *cache.Redis
}
func NewSessionRepository(redis *cache.Redis) domain.SessionRepo {
return &SessionRepository{
redis: redis,
}
}
func (r *SessionRepository) Create(ctx context.Context, session *domain.UserSession) error {
key := r.getSessionKey(session.ID)
sessionData, err := json.Marshal(session)
if err != nil {
return fmt.Errorf("failed to marshal session: %w", err)
}
ttl := time.Until(session.ExpiresAt)
if ttl <= 0 {
return fmt.Errorf("session already expired")
}
if err := r.redis.Client().Set(ctx, key, sessionData, ttl).Err(); err != nil {
return fmt.Errorf("failed to store session in Redis: %w", err)
}
userSessionsKey := r.getUserSessionsKey(session.UserID)
if err := r.redis.Client().SAdd(ctx, userSessionsKey, session.ID.String()).Err(); err != nil {
return fmt.Errorf("failed to add session to user sessions set: %w", err)
}
if err := r.redis.Client().Expire(ctx, userSessionsKey, ttl).Err(); err != nil {
return fmt.Errorf("failed to set TTL for user sessions set: %w", err)
}
return nil
}
func (r *SessionRepository) GetByID(ctx context.Context, id uuid.UUID) (*domain.UserSession, error) {
key := r.getSessionKey(id)
result, err := r.redis.Client().Get(ctx, key).Result()
if err != nil {
if err == redis.Nil {
return nil, fmt.Errorf("session not found")
}
return nil, fmt.Errorf("failed to get session from Redis: %w", err)
}
var session domain.UserSession
if err := json.Unmarshal([]byte(result), &session); err != nil {
return nil, fmt.Errorf("failed to unmarshal session: %w", err)
}
if time.Now().After(session.ExpiresAt) {
r.Delete(ctx, id)
return nil, fmt.Errorf("session expired")
}
return &session, nil
}
func (r *SessionRepository) Delete(ctx context.Context, id uuid.UUID) error {
key := r.getSessionKey(id)
session, err := r.GetByID(ctx, id)
if err != nil {
return nil
}
if err := r.redis.Client().Del(ctx, key).Err(); err != nil {
return fmt.Errorf("failed to delete session from Redis: %w", err)
}
userSessionsKey := r.getUserSessionsKey(session.UserID)
if err := r.redis.Client().SRem(ctx, userSessionsKey, id.String()).Err(); err != nil {
return fmt.Errorf("failed to remove session from user sessions set: %w", err)
}
return nil
}
func (r *SessionRepository) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]domain.UserSession, error) {
userSessionsKey := r.getUserSessionsKey(userID)
sessionIDs, err := r.redis.Client().SMembers(ctx, userSessionsKey).Result()
if err != nil {
if err == redis.Nil {
return []domain.UserSession{}, nil
}
return nil, fmt.Errorf("failed to get user sessions from Redis: %w", err)
}
var sessions []domain.UserSession
for _, sessionIDStr := range sessionIDs {
sessionID, err := uuid.Parse(sessionIDStr)
if err != nil {
r.redis.Client().SRem(ctx, userSessionsKey, sessionIDStr)
continue
}
session, err := r.GetByID(ctx, sessionID)
if err != nil {
r.redis.Client().SRem(ctx, userSessionsKey, sessionIDStr)
continue
}
sessions = append(sessions, *session)
}
return sessions, nil
}
func (r *SessionRepository) getSessionKey(sessionID uuid.UUID) string {
return fmt.Sprintf("session:%s", sessionID.String())
}
func (r *SessionRepository) getUserSessionsKey(userID uuid.UUID) string {
return fmt.Sprintf("user_sessions:%s", userID.String())
}
@@ -1,56 +0,0 @@
package storage
import (
"backend/internal/domain"
"backend/internal/repository/storage/types"
"context"
"github.com/google/uuid"
"gorm.io/gorm"
)
type SessionRepository struct {
db *gorm.DB
}
func NewSessionRepository(db *gorm.DB) domain.SessionRepo {
return &SessionRepository{
db: db,
}
}
func (r *SessionRepository) Create(ctx context.Context, session *domain.UserSession) error {
model := types.CastSessionToStorage(*session)
return r.db.WithContext(ctx).Create(&model).Error
}
func (r *SessionRepository) GetByID(ctx context.Context, id uuid.UUID) (*domain.UserSession, error) {
var session types.UserSession
if err := r.db.WithContext(ctx).Preload("User").First(&session, "id = ?", id).Error; err != nil {
return nil, err
}
return types.CastSessionToDomain(session), nil
}
func (r *SessionRepository) Delete(ctx context.Context, id uuid.UUID) error {
var session types.UserSession
if err := r.db.WithContext(ctx).First(&session, "id = ?", id).Error; err != nil {
return err
}
return r.db.WithContext(ctx).Delete(&session).Error
}
func (r *SessionRepository) GetUserSessions(ctx context.Context, userID uuid.UUID) ([]domain.UserSession, error) {
var sessions []types.UserSession
if err := r.db.WithContext(ctx).Preload("User").Find(&sessions, "user_id = ?", userID).Error; err != nil {
return nil, err
}
result := make([]domain.UserSession, len(sessions))
for i, session := range sessions {
result[i] = *types.CastSessionToDomain(session)
}
return result, nil
}
@@ -1,44 +0,0 @@
package types
import (
"backend/internal/domain"
"time"
"github.com/google/uuid"
)
type UserSession struct {
Base
UserID uuid.UUID
User *User
WalletID string
ExpireAt time.Time
}
func CastSessionToStorage(s domain.UserSession) *UserSession {
return &UserSession{
Base: Base{
ID: s.ID,
CreatedAt: s.CreatedAt,
UpdatedAt: s.UpdatedAt,
DeletedAt: s.DeletedAt,
},
UserID: s.UserID,
User: CastUserToStorage(s.User),
WalletID: s.WalletID,
ExpireAt: s.ExpiresAt,
}
}
func CastSessionToDomain(s UserSession) *domain.UserSession {
return &domain.UserSession{
ID: s.ID,
UserID: s.UserID,
User: *CastUserToDomain(*s.User),
WalletID: s.WalletID,
ExpiresAt: s.ExpireAt,
CreatedAt: s.CreatedAt,
UpdatedAt: s.UpdatedAt,
DeletedAt: s.DeletedAt,
}
}
+34 -11
View File
@@ -17,14 +17,15 @@ import (
type AuthService interface {
GenerateChallenge(ctx context.Context, pubKey string) (*domain.Challenge, error)
Authenticate(ctx context.Context, pubKey string, signature string, challenge *domain.Challenge, chainID uint, ipAddress, userAgent string) (*UserToken, error)
Authenticate(ctx context.Context, pubKey string, signature string, chainID uint, ipAddress, userAgent string) (*UserToken, error)
}
type authService struct {
userRepo domain.UserRepo
sessionRepo domain.SessionRepo
challengeExp uint
cfg config.JWT
userRepo domain.UserRepo
sessionRepo domain.SessionRepo
challengeRepo domain.ChallengeRepo
challengeExp uint
cfg config.JWT
}
type UserToken struct {
@@ -36,14 +37,16 @@ type UserToken struct {
func NewAuthService(
userRepo domain.UserRepo,
sessionRepo domain.SessionRepo,
challengeRepo domain.ChallengeRepo,
challengeExp uint,
cfg config.JWT,
) AuthService {
return &authService{
userRepo: userRepo,
sessionRepo: sessionRepo,
challengeExp: challengeExp,
cfg: cfg,
userRepo: userRepo,
sessionRepo: sessionRepo,
challengeRepo: challengeRepo,
challengeExp: challengeExp,
cfg: cfg,
}
}
@@ -54,19 +57,32 @@ func (s *authService) GenerateChallenge(ctx context.Context, pubKey string) (*do
}
challenge := &domain.Challenge{
Message: uuid.New(),
Message: uuid.New().String(),
TimeStamp: time.Now().UTC(),
ExpiresAt: time.Now().Add(time.Duration(s.challengeExp) * time.Minute),
}
// Save challenge to Redis
err = s.challengeRepo.Create(ctx, pubKey, challenge)
if err != nil {
return nil, fmt.Errorf("failed to save challenge: %w", err)
}
return challenge, nil
}
func (s *authService) Authenticate(ctx context.Context, pubKey string, signature string, challenge *domain.Challenge, chainID uint, ipAddress, userAgent string) (*UserToken, error) {
func (s *authService) Authenticate(ctx context.Context, pubKey string, signature string, chainID uint, ipAddress, userAgent string) (*UserToken, error) {
_, err := common.IsValidPublicKey(pubKey)
if err != nil {
return nil, fmt.Errorf("invalid public key: %w", err)
}
// Retrieve challenge from Redis
challenge, err := s.challengeRepo.GetByPubKey(ctx, pubKey)
if err != nil {
return nil, fmt.Errorf("failed to retrieve challenge: %w", err)
}
isValid, err := challenge.Verify(pubKey, signature)
if err != nil {
return nil, fmt.Errorf("signature verification failed: %w", err)
@@ -75,6 +91,13 @@ func (s *authService) Authenticate(ctx context.Context, pubKey string, signature
if !isValid {
return nil, errors.New("invalid signature")
}
// Delete the challenge after successful verification to prevent replay attacks
err = s.challengeRepo.Delete(ctx, pubKey)
if err != nil {
return nil, fmt.Errorf("failed to delete challenge: %w", err)
}
user, err := s.userRepo.GetByPubKey(ctx, pubKey)
if err != nil {
return nil, err