refactor: introduce DTOs for claims, session, and request handling

feat: add token validation service method
refactor: update middleware to use structured DTOs
feat: implement session info propagation through context
refactor: replace ad-hoc structs with DTOs in middleware
chore: organize auth-related data structures
This commit is contained in:
2025-07-15 20:54:12 +03:00
parent ee6cff4104
commit b3a405016e
8 changed files with 249 additions and 52 deletions

View File

@@ -0,0 +1,32 @@
// Copyright (c) 2025 Nikolai Papin
//
// This file is part of Easywish
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package dto
import (
"easywish/internal/utils/enums"
"github.com/golang-jwt/jwt/v5"
)
type UserClaims struct {
Username string `json:"username"`
Role enums.Role `json:"role"`
Type enums.JwtTokenType `json:"type"`
Session string `json:"session"`
jwt.RegisteredClaims
}

View File

@@ -0,0 +1,23 @@
// Copyright (c) 2025 Nikolai Papin
//
// This file is part of Easywish
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package dto
type Request[T any] struct {
User ClientInfo
Body T
}

View File

@@ -0,0 +1,27 @@
// Copyright (c) 2025 Nikolai Papin
//
// This file is part of Easywish
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package dto
import "easywish/internal/utils/enums"
type SessionInfo struct {
Username string
Session string
Role enums.Role
}

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2025 Nikolai Papin
//
// This file is part of Easywish
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package dto
type ClientInfo struct {
SessionInfo
IP string
UserAgent string
}

View File

@@ -21,6 +21,7 @@ import (
"context" "context"
"easywish/config" "easywish/config"
"easywish/internal/database" "easywish/internal/database"
"easywish/internal/dto"
"easywish/internal/utils/enums" "easywish/internal/utils/enums"
"errors" "errors"
"fmt" "fmt"
@@ -34,14 +35,6 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
) )
type Claims struct {
Username string `json:"username"`
Role enums.Role `json:"role"`
Type enums.JwtTokenType `json:"type"`
Session string `json:"session"`
jwt.RegisteredClaims
}
// XXX: cluttered; move cache & database check to auth service // XXX: cluttered; move cache & database check to auth service
func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redis.Client) gin.HandlerFunc { func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redis.Client) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
@@ -49,8 +42,12 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
authHeader := c.GetHeader("Authorization") authHeader := c.GetHeader("Authorization")
if authHeader == "" { if authHeader == "" {
c.Set("username", nil)
c.Set("role", enums.GuestRole) c.Set("session_info", dto.SessionInfo{
Username: "",
Session: "",
Role: enums.GuestRole},
)
c.Next() c.Next()
return return
} }
@@ -59,7 +56,7 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
token, err := jwt.ParseWithClaims( token, err := jwt.ParseWithClaims(
tokenString, tokenString,
&Claims{}, &dto.UserClaims{},
func(token *jwt.Token) (any, error) { func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
@@ -77,7 +74,7 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
return return
} }
if claims, ok := token.Claims.(*Claims); ok && token.Valid { if claims, ok := token.Claims.(*dto.UserClaims); ok && token.Valid {
if claims.Type != enums.JwtAccessTokenType { if claims.Type != enums.JwtAccessTokenType {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Not an access token"}) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Not an access token"})
@@ -142,8 +139,12 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
return return
} }
c.Set("username", claims.Username) c.Set("session_info", dto.SessionInfo{
c.Set("role", claims.Role) Username: claims.Username,
Session: claims.Session,
Role: claims.Role,
})
c.Next() c.Next()
} else { } else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"}) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"})

View File

@@ -18,6 +18,7 @@
package middleware package middleware
import ( import (
"easywish/internal/dto"
"easywish/internal/utils/enums" "easywish/internal/utils/enums"
"easywish/internal/validation" "easywish/internal/validation"
"fmt" "fmt"
@@ -27,58 +28,51 @@ import (
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
) )
type UserInfo struct {
Username string
Role enums.Role
}
type Request[T any] struct {
User UserInfo
Body T
}
const requestKey = "request" const requestKey = "request"
func UserInfoFromContext(c *gin.Context) (*UserInfo, bool) { func ClientInfoFromContext(c *gin.Context) (*dto.ClientInfo, bool) {
var username any
var role any
var ok bool var ok bool
username, ok = c.Get("username") ; if !ok { ip := c.ClientIP()
return &UserInfo{Username: "", Role: enums.GuestRole}, true userAgent := c.Request.UserAgent()
}
role, ok = c.Get("role"); if !ok { sessionInfoFromCtx, ok := c.Get("session_info"); if !ok {
return nil, false return nil, false
} }
if username == nil { sessionInfo := sessionInfoFromCtx.(dto.SessionInfo)
return &UserInfo{Username: "", Role: enums.GuestRole}, true
if sessionInfo.Username == "" {
return &dto.ClientInfo{
SessionInfo: sessionInfo,
IP: ip,
UserAgent: userAgent,
}, true
} }
if role == nil { return &dto.ClientInfo{
return nil, false SessionInfo: sessionInfo,
} IP: ip,
UserAgent: userAgent,
return &UserInfo{Username: username.(string), Role: role.(enums.Role)}, true }, true
} }
func RequestFromContext[T any](c *gin.Context) Request[T] { func RequestFromContext[T any](c *gin.Context) dto.Request[T] {
return c.Value(requestKey).(Request[T]) return c.Value(requestKey).(dto.Request[T])
} }
func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc { func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) { return gin.HandlerFunc(func(c *gin.Context) {
userInfo, ok := UserInfoFromContext(c) clientInfo, ok := ClientInfoFromContext(c)
if !ok { if !ok {
c.Status(http.StatusUnauthorized) c.Status(http.StatusUnauthorized)
return return
} }
if userInfo.Role < role { if clientInfo.Role < role {
c.Status(http.StatusForbidden) c.Status(http.StatusForbidden)
return return
} }
@@ -99,8 +93,8 @@ func RequestMiddleware[T any](role enums.Role) gin.HandlerFunc {
return return
} }
request := Request[T]{ request := dto.Request[T]{
User: *userInfo, User: *clientInfo,
Body: body, Body: body,
} }

View File

@@ -21,6 +21,7 @@ import (
"context" "context"
"easywish/config" "easywish/config"
"easywish/internal/database" "easywish/internal/database"
"easywish/internal/dto"
errs "easywish/internal/errors" errs "easywish/internal/errors"
"easywish/internal/models" "easywish/internal/models"
"easywish/internal/utils" "easywish/internal/utils"
@@ -30,6 +31,7 @@ import (
"time" "time"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgerrcode" "github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
@@ -43,6 +45,7 @@ type AuthService interface {
Refresh(request models.RefreshRequest) (*models.RefreshResponse, error) Refresh(request models.RefreshRequest) (*models.RefreshResponse, error)
PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error) PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error)
PasswordResetComplete(request models.PasswordResetCompleteRequest) (*models.PasswordResetCompleteResponse, error) PasswordResetComplete(request models.PasswordResetCompleteRequest) (*models.PasswordResetCompleteResponse, error)
ValidateToken(token string, tokenType enums.JwtTokenType) (*dto.SessionInfo, error)
} }
type authServiceImpl struct { type authServiceImpl struct {
@@ -505,6 +508,100 @@ func (a *authServiceImpl) Login(request models.LoginRequest) (*models.LoginRespo
} }
func (a *authServiceImpl) Refresh(request models.RefreshRequest) (*models.RefreshResponse, error) { func (a *authServiceImpl) Refresh(request models.RefreshRequest) (*models.RefreshResponse, error) {
var err error
token, err := jwt.ParseWithClaims(
request.RefreshToken,
&dto.UserClaims{},
func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(config.GetConfig().JwtSecret), nil
},
)
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
// AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"})
} else {
// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
}
return nil, errs.ErrUnauthorized
}
if claims, ok := token.Claims.(*dto.UserClaims); ok && token.Valid {
if claims.Type != enums.JwtAccessTokenType {
// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Not an access token"})
return nil, errs.ErrUnauthorized
}
ctx := context.TODO()
isTerminated, redisErr := a.redis.Get(ctx, fmt.Sprintf("session::%s::is_terminated", claims.Session)).Bool()
if redisErr != nil && redisErr != redis.Nil {
a.log.Error(
"Failed to lookup cache to check whether session is not terminated",
zap.Error(redisErr))
// c.AbortWithStatus(http.StatusInternalServerError)
return nil, errs.ErrServerError
}
// Cache if nil
if redisErr == redis.Nil {
db := database.NewDbHelper(a.dbctx)
session, err := db.Queries.GetSessionByGuid(db.CTX, claims.Session)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
a.log.Warn(
"Session does not exist or was deleted",
zap.String("session", claims.Session))
// c.AbortWithStatus(http.StatusUnauthorized)
return nil, errs.ErrUnauthorized
}
a.log.Error(
"Failed to lookup session in database",
zap.String("session", claims.Session),
zap.Error(err))
// c.AbortWithStatus(http.StatusInternalServerError)
return nil, errs.ErrServerError
}
if err := a.redis.Set(
ctx,
fmt.Sprintf("session::%s::is_terminated", claims.Session),
session.Terminated,
time.Duration(8 * time.Hour), // XXX: magic number
).Err(); err != nil {
a.log.Error(
"Failed to cache session's is_terminated state",
zap.String("session", claims.Session),
zap.Error(err))
// c.AbortWithStatus(http.StatusInternalServerError)
return nil, errs.ErrServerError
}
isTerminated = *session.Terminated
}
if isTerminated {
a.log.Warn(
"Attempt to access resource from a terminated session",
zap.String("session", claims.Session))
// c.AbortWithStatus(http.StatusUnauthorized)
return nil, errs.ErrUnauthorized
}
}
// TODO: generate some tokens
return nil, errs.ErrNotImplemented
}
func (a *authServiceImpl) ValidateToken(token string, tokenType enums.JwtTokenType) (*dto.SessionInfo, error) {
return nil, errs.ErrNotImplemented return nil, errs.ErrNotImplemented
} }

View File

@@ -1,32 +1,31 @@
// Copyright (c) 2025 Nikolai Papin // Copyright (c) 2025 Nikolai Papin
// //
// This file is part of Easywish // This file is part of Easywish
// //
// This program is free software: you can redistribute it and/or modify // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by // it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. // (at your option) any later version.
// //
// This program is distributed in the hope that it will be useful, // This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details. // the GNU General Public License for more details.
// //
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
package utils package utils
import ( import (
"easywish/internal/middleware" "easywish/internal/dto"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func GetRequest[T any](c *gin.Context) (*middleware.Request[T], bool) { func GetRequest[T any](c *gin.Context) (*dto.Request[T], bool) {
req, ok := c.Get("request") req, ok := c.Get("request")
request := req.(middleware.Request[T]) request := req.(dto.Request[T])
if !ok { if !ok {
return nil, false return nil, false
} }