Compare commits

7 Commits

Author SHA1 Message Date
8b558eaf5f feat: fully implemented Refresh method;
fix: Improve error handling in Refresh method for token validation;
fix: Update Refresh route to use correct request model;
fix: Correct request model for password reset complete route;
fix: Redis pipeline error handling in AuthService constructor;
fix: Refresh method wanted access token;
refactor: Enhance error handling for unexpected token validation errors;
refactor: Simplify claims extraction in ValidateToken method;
fix: Ensure session termination state is correctly dereferenced;
refactor: Return structured session info in ValidateToken method;
feat: New util method to check if an error is one of multiple given ones;
2025-07-15 23:32:25 +03:00
e465da6854 refactor: Simplify AuthMiddleware;
refactor: Move token validation logic to AuthService;
refactor: Remove Redis cache checks from middleware;
fix: Improve error handling for token validation;
refactor: Update Refresh method to use new validation logic;
chore: Clean up unused imports and comments
2025-07-15 22:37:41 +03:00
a582b75c82 feat: new ValidateToken method for AuthService, based on code from the monolithic implementation of auth middleware;
feat: add detailed authentication error types;
2025-07-15 21:59:05 +03:00
b3a405016e 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
2025-07-15 20:54:12 +03:00
ee6cff4104 feat: add registration attempt rate limiting with Redis
feat: prevent email enumeration by caching registration state
fix: correct Redis key formatting for session termination cache
refactor: improve registration flow with Redis cooldown checks
chore: add Redis caching for registration in-progress state
2025-07-15 02:55:26 +03:00
d8ea9f79c6 feat: add session expiration tracking and validation
feat: implement Redis caching for terminated sessions
feat: add new session GUID queries for validation
refactor: extend Session model with last_refresh_exp_time
refactor: update token generation to include role and session
refactor: modify auth middleware to validate session status
refactor: replace GetUserSessions with GetValidUserSessions
chore: add uuid/v5 dependency
fix: update router to pass dependencies to auth middleware
chore: update SQL schema and queries for new expiration field
2025-07-14 20:44:30 +03:00
24cb8ecb6e feat: implemented controller methods for passwordresetcomplete, refresh in auth controller 2025-07-13 20:58:36 +03:00
19 changed files with 594 additions and 154 deletions

View File

@@ -34,6 +34,7 @@ require (
github.com/go-redis/redis/v8 v8.11.5 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/gofrs/uuid/v5 v5.3.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect

View File

@@ -49,6 +49,8 @@ github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIx
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/gofrs/uuid/v5 v5.3.2 h1:2jfO8j3XgSwlz/wHqemAEugfnTlikAYHhnqQ8Xh4fE0=
github.com/gofrs/uuid/v5 v5.3.2/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=

View File

@@ -77,7 +77,6 @@ func (a *authControllerImpl) Login(c *gin.Context) {
}
c.JSON(http.StatusOK, response)
return
}
// @Summary Request password reset email
@@ -106,7 +105,6 @@ func (a *authControllerImpl) PasswordResetBegin(c *gin.Context) {
}
c.JSON(http.StatusOK, response)
return
}
// @Summary Complete password reset via email code
@@ -118,7 +116,24 @@ func (a *authControllerImpl) PasswordResetBegin(c *gin.Context) {
// @Success 200 {object} models.PasswordResetCompleteResponse " "
// @Success 403 "Wrong verification code or username"
func (a *authControllerImpl) PasswordResetComplete(c *gin.Context) {
c.Status(http.StatusNotImplemented)
request, ok := utils.GetRequest[models.PasswordResetCompleteRequest](c)
if !ok {
c.Status(http.StatusBadRequest)
return
}
response, err := a.auth.PasswordResetComplete(request.Body)
if err != nil {
if errors.Is(err, errs.ErrForbidden) {
c.Status(http.StatusForbidden)
} else {
c.Status(http.StatusInternalServerError)
}
return
}
c.JSON(http.StatusOK, response)
}
@@ -131,7 +146,32 @@ func (a *authControllerImpl) PasswordResetComplete(c *gin.Context) {
// @Success 200 {object} models.RefreshResponse " "
// @Failure 401 "Invalid refresh token"
func (a *authControllerImpl) Refresh(c *gin.Context) {
c.Status(http.StatusNotImplemented)
request, ok := utils.GetRequest[models.RefreshRequest](c)
if !ok {
c.Status(http.StatusBadRequest)
return
}
response, err := a.auth.Refresh(request.Body)
if err != nil {
if errors.Is(err, errs.ErrTokenExpired) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is expired"})
} else if errors.Is(err, errs.ErrTokenInvalid) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is invalid"})
} else if errors.Is(err, errs.ErrWrongTokenType) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token type"})
} else if errors.Is(err, errs.ErrSessionNotFound) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Could not find session in database"})
} else if errors.Is(err, errs.ErrSessionTerminated) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Session is terminated"})
} else {
c.Status(http.StatusInternalServerError)
}
return
}
c.JSON(http.StatusOK, response)
}
// @Summary Register an account
@@ -201,7 +241,7 @@ func (a *authControllerImpl) RegisterRoutes(group *gin.RouterGroup) {
group.POST("/registrationBegin", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.GuestRole), a.RegistrationBegin)
group.POST("/registrationComplete", middleware.RequestMiddleware[models.RegistrationCompleteRequest](enums.GuestRole), a.RegistrationComplete)
group.POST("/login", middleware.RequestMiddleware[models.LoginRequest](enums.GuestRole), a.Login)
group.POST("/refresh", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.UserRole), a.Refresh)
group.POST("/refresh", middleware.RequestMiddleware[models.RefreshRequest](enums.GuestRole), a.Refresh)
group.POST("/passwordResetBegin", middleware.RequestMiddleware[models.PasswordResetBeginRequest](enums.GuestRole), a.PasswordResetBegin)
group.POST("/passwordResetComplete", middleware.RequestMiddleware[models.RegistrationBeginRequest](enums.GuestRole), a.PasswordResetComplete)
group.POST("/passwordResetComplete", middleware.RequestMiddleware[models.PasswordResetCompleteRequest](enums.GuestRole), a.PasswordResetComplete)
}

View File

@@ -63,15 +63,16 @@ type ProfileSetting struct {
}
type Session struct {
ID int64
UserID int64
Guid pgtype.UUID
Name *string
Platform *string
LatestIp *string
LoginTime pgtype.Timestamp
LastSeenDate pgtype.Timestamp
Terminated *bool
ID int64
UserID int64
Guid pgtype.UUID
Name *string
Platform *string
LatestIp *string
LoginTime pgtype.Timestamp
LastRefreshExpTime pgtype.Timestamp
LastSeenDate pgtype.Timestamp
Terminated *bool
}
type User struct {

View File

@@ -201,7 +201,7 @@ func (q *Queries) CreateProfileSettings(ctx context.Context, profileID int64) (P
const createSession = `-- name: CreateSession :one
INSERT INTO sessions(user_id, name, platform, latest_ip)
VALUES ($1, $2, $3, $4) RETURNING id, user_id, guid, name, platform, latest_ip, login_time, last_seen_date, terminated
VALUES ($1, $2, $3, $4) RETURNING id, user_id, guid, name, platform, latest_ip, login_time, last_refresh_exp_time, last_seen_date, terminated
`
type CreateSessionParams struct {
@@ -227,6 +227,7 @@ func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (S
&i.Platform,
&i.LatestIp,
&i.LoginTime,
&i.LastRefreshExpTime,
&i.LastSeenDate,
&i.Terminated,
)
@@ -484,6 +485,56 @@ func (q *Queries) GetProfilesRestricted(ctx context.Context, arg GetProfilesRest
return items, nil
}
const getSessionByGuid = `-- name: GetSessionByGuid :one
SELECT id, user_id, guid, name, platform, latest_ip, login_time, last_refresh_exp_time, last_seen_date, terminated FROM sessions
WHERE guid = ($1::text)::uuid
`
func (q *Queries) GetSessionByGuid(ctx context.Context, guid string) (Session, error) {
row := q.db.QueryRow(ctx, getSessionByGuid, guid)
var i Session
err := row.Scan(
&i.ID,
&i.UserID,
&i.Guid,
&i.Name,
&i.Platform,
&i.LatestIp,
&i.LoginTime,
&i.LastRefreshExpTime,
&i.LastSeenDate,
&i.Terminated,
)
return i, err
}
const getUnexpiredTerminatedSessionsGuids = `-- name: GetUnexpiredTerminatedSessionsGuids :many
SELECT guid FROM sessions
WHERE
terminated IS TRUE AND
last_refresh_exp_time > CURRENT_TIMESTAMP
`
func (q *Queries) GetUnexpiredTerminatedSessionsGuids(ctx context.Context) ([]pgtype.UUID, error) {
rows, err := q.db.Query(ctx, getUnexpiredTerminatedSessionsGuids)
if err != nil {
return nil, err
}
defer rows.Close()
var items []pgtype.UUID
for rows.Next() {
var guid pgtype.UUID
if err := rows.Scan(&guid); err != nil {
return nil, err
}
items = append(items, guid)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getUser = `-- name: GetUser :one
SELECT id, username, verified, registration_date, deleted FROM users
WHERE id = $1
@@ -608,41 +659,6 @@ func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User,
return i, err
}
const getUserSessions = `-- name: GetUserSessions :many
SELECT id, user_id, guid, name, platform, latest_ip, login_time, last_seen_date, terminated FROM sessions
WHERE user_id = $1 AND terminated IS FALSE
`
func (q *Queries) GetUserSessions(ctx context.Context, userID int64) ([]Session, error) {
rows, err := q.db.Query(ctx, getUserSessions, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Session
for rows.Next() {
var i Session
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Guid,
&i.Name,
&i.Platform,
&i.LatestIp,
&i.LoginTime,
&i.LastSeenDate,
&i.Terminated,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getValidConfirmationCodeByCode = `-- name: GetValidConfirmationCodeByCode :one
SELECT id, user_id, code_type, code_hash, expires_at, used, deleted FROM confirmation_codes
WHERE
@@ -778,6 +794,44 @@ func (q *Queries) GetValidUserByLoginCredentials(ctx context.Context, arg GetVal
return i, err
}
const getValidUserSessions = `-- name: GetValidUserSessions :many
SELECT id, user_id, guid, name, platform, latest_ip, login_time, last_refresh_exp_time, last_seen_date, terminated FROM sessions
WHERE
user_id = $1 AND terminated IS FALSE AND
last_refresh_exp_time > CURRENT_TIMESTAMP
`
func (q *Queries) GetValidUserSessions(ctx context.Context, userID int64) ([]Session, error) {
rows, err := q.db.Query(ctx, getValidUserSessions, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Session
for rows.Next() {
var i Session
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Guid,
&i.Name,
&i.Platform,
&i.LatestIp,
&i.LoginTime,
&i.LastRefreshExpTime,
&i.LastSeenDate,
&i.Terminated,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const pruneExpiredConfirmationCodes = `-- name: PruneExpiredConfirmationCodes :exec
DELETE FROM confirmation_codes
WHERE expires_at < CURRENT_TIMESTAMP
@@ -975,19 +1029,21 @@ SET
platform = COALESCE($3, platform),
latest_ip = COALESCE($4, latest_ip),
login_time = COALESCE($5, login_time),
last_seen_date = COALESCE($6, last_seen_date),
terminated = COALESCE($7, terminated)
last_refresh_exp_time = COALESCE($6, last_refresh_exp_time),
last_seen_date = COALESCE($7, last_seen_date),
terminated = COALESCE($8, terminated)
WHERE id = $1
`
type UpdateSessionParams struct {
ID int64
Name *string
Platform *string
LatestIp *string
LoginTime pgtype.Timestamp
LastSeenDate pgtype.Timestamp
Terminated *bool
ID int64
Name *string
Platform *string
LatestIp *string
LoginTime pgtype.Timestamp
LastRefreshExpTime pgtype.Timestamp
LastSeenDate pgtype.Timestamp
Terminated *bool
}
func (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) error {
@@ -997,6 +1053,7 @@ func (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) er
arg.Platform,
arg.LatestIp,
arg.LoginTime,
arg.LastRefreshExpTime,
arg.LastSeenDate,
arg.Terminated,
)

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

@@ -29,4 +29,10 @@ var (
ErrInvalidCredentials = errors.New("Invalid username, password or TOTP code")
ErrInvalidToken = errors.New("Token is invalid or expired")
ErrServerError = errors.New("Internal server error")
ErrTokenExpired = errors.New("Token is expired")
ErrTokenInvalid = errors.New("Token is invalid")
ErrWrongTokenType = errors.New("Invalid token type")
ErrSessionNotFound = errors.New("Could not find session in database")
ErrSessionTerminated = errors.New("Session is terminated")
)

View File

@@ -18,64 +18,53 @@
package middleware
import (
"easywish/config"
"easywish/internal/dto"
"easywish/internal/services"
"easywish/internal/utils/enums"
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"go.uber.org/zap"
errs "easywish/internal/errors"
)
type Claims struct {
Username string `json:"username"`
Role enums.Role `json:"role"`
jwt.RegisteredClaims
}
// TODO: validate token type
// TODO: validate session guid
func AuthMiddleware() gin.HandlerFunc {
func AuthMiddleware(log *zap.Logger, auth services.AuthService) gin.HandlerFunc {
return func(c *gin.Context) {
cfg := config.GetConfig()
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.Set("username", nil)
c.Set("role", enums.GuestRole)
c.Set("session_info", dto.SessionInfo{
Username: "",
Session: "",
Role: enums.GuestRole},
)
c.Next()
return
}
tokenString := authHeader
token, err := jwt.ParseWithClaims(
tokenString,
&Claims{},
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(cfg.JwtSecret), nil
},
)
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"})
if sessionInfo, err := auth.ValidateToken(tokenString, enums.JwtAccessTokenType); err != nil {
if errors.Is(err, errs.ErrTokenExpired) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is expired"})
} else if errors.Is(err, errs.ErrTokenInvalid) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is invalid"})
} else if errors.Is(err, errs.ErrWrongTokenType) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token type"})
} else if errors.Is(err, errs.ErrSessionNotFound) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Could not find session in database"})
} else if errors.Is(err, errs.ErrSessionTerminated) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Session is terminated"})
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
}
return
} else {
c.Set("session_info", sessionInfo)
c.Next()
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
c.Set("username", claims.Username)
c.Set("role", claims.Role)
c.Next()
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"})
}
return
}
}

View File

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

View File

@@ -20,13 +20,15 @@ package routes
import (
"easywish/internal/controllers"
"easywish/internal/middleware"
"easywish/internal/services"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func NewRouter(engine *gin.Engine, groups []RouteGroup) *gin.Engine {
func NewRouter(engine *gin.Engine, log *zap.Logger, auth services.AuthService, groups []RouteGroup) *gin.Engine {
apiGroup := engine.Group("/api")
apiGroup.Use(middleware.AuthMiddleware())
apiGroup.Use(middleware.AuthMiddleware(log, auth))
for _, group := range groups {
subgroup := apiGroup.Group(group.BasePath)
subgroup.Use(group.Middleware...)

View File

@@ -21,6 +21,7 @@ import (
"context"
"easywish/config"
"easywish/internal/database"
"easywish/internal/dto"
errs "easywish/internal/errors"
"easywish/internal/models"
"easywish/internal/utils"
@@ -30,6 +31,7 @@ import (
"time"
"github.com/go-redis/redis/v8"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
@@ -43,6 +45,7 @@ type AuthService interface {
Refresh(request models.RefreshRequest) (*models.RefreshResponse, error)
PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error)
PasswordResetComplete(request models.PasswordResetCompleteRequest) (*models.PasswordResetCompleteResponse, error)
ValidateToken(token string, tokenType enums.JwtTokenType) (*dto.SessionInfo, error)
}
type authServiceImpl struct {
@@ -53,7 +56,27 @@ type authServiceImpl struct {
}
func NewAuthService(_log *zap.Logger, _dbctx database.DbContext, _redis *redis.Client, _smtp SmtpService) AuthService {
return &authServiceImpl{log: _log, dbctx: _dbctx, redis: _redis, smtp: _smtp}
authService := &authServiceImpl{log: _log, dbctx: _dbctx, redis: _redis, smtp: _smtp}
// Cache terminated sessions
// FIXME: review possible RAM overflow
db := database.NewDbHelper(_dbctx)
guids, err := db.Queries.GetUnexpiredTerminatedSessionsGuids(db.CTX)
if err != nil {
panic("Failed to load terminated sessions' GUIDs")
}
ctx := context.TODO()
// FIXME: review possible problems due to a large pipeline request
pipe := _redis.Pipeline()
for _, guid := range guids {
if err := pipe.Set(ctx, fmt.Sprintf("session::%s::is_terminated", guid), true, 0).Err(); err != nil {
panic("Failed to cache terminated session: " + err.Error())
}
}
_log.Info("Cached terminated sessions' GUIDs in Redis", zap.Int("amount", len(guids)))
return authService
}
func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequest) (bool, error) {
@@ -75,7 +98,25 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ
defer helper.RollbackOnError(err)
// TODO: check occupation with redis
if isInProgress, err := a.redis.Get(
context.TODO(),
fmt.Sprintf("email::%s::registration_in_progress",
request.Email),
).Bool(); err != nil {
if err != redis.Nil {
a.log.Error(
"Failed to look up cached registration_in_progress state of email as part of registration procedure",
zap.String("email", request.Email),
zap.Error(err))
return false, errs.ErrServerError
}
isInProgress = false
} else if isInProgress {
a.log.Warn(
"Attempted to begin registration on email that is in progress of registration or on cooldown",
zap.String("email", request.Email))
return false, errs.ErrTooManyRequests
}
if occupationStatus, err = db.TXQueries.CheckUserRegistrationAvailability(db.CTX, database.CheckUserRegistrationAvailabilityParams{
Email: request.Email,
@@ -98,7 +139,19 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ
} else if occupationStatus.EmailBusy {
// Falsely confirm in order to avoid disclosing registered email addresses
// TODO: save this email into redis
if err := a.redis.Set(
context.TODO(),
fmt.Sprintf("email::%s::registration_in_progress", request.Email),
true,
time.Duration(10 * time.Minute), // XXX: magic number
).Err(); err != nil {
a.log.Error(
"Failed to falsely set cache registration_in_progress state for email as a measure to prevent email enumeration",
zap.String("email", request.Email),
zap.Error(err))
return false, errs.ErrServerError
}
a.log.Warn(
"Attempted registration for a taken email",
zap.String("email", request.Email),
@@ -191,6 +244,19 @@ func (a *authServiceImpl) RegistrationBegin(request models.RegistrationBeginRequ
zap.String("code", generatedCode))
}
if err := a.redis.Set(
context.TODO(),
fmt.Sprintf("email::%s::registration_in_progress", request.Email),
true,
time.Duration(10 * time.Minute), // XXX: magic number
).Err(); err != nil {
a.log.Error(
"Failed to cache registration_in_progress state for email",
zap.String("email", request.Email),
zap.Error(err))
return false, errs.ErrServerError
}
if err = helper.Commit(); err != nil {
a.log.Error(
"Failed to commit transaction",
@@ -324,7 +390,8 @@ func (a *authServiceImpl) RegistrationComplete(request models.RegistrationComple
return nil, errs.ErrServerError
}
accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String())
// TODO: get user role
accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String(), enums.UserRole)
if err != nil {
a.log.Error(
@@ -415,7 +482,8 @@ func (a *authServiceImpl) Login(request models.LoginRequest) (*models.LoginRespo
return nil, errs.ErrServerError
}
accessToken, refreshToken, err := utils.GenerateTokens(userRow.Username, session.Guid.String())
// TODO: get user role
accessToken, refreshToken, err := utils.GenerateTokens(userRow.Username, session.Guid.String(), enums.UserRole)
if err != nil {
a.log.Error(
"Failed to generate tokens for a new login",
@@ -440,7 +508,136 @@ func (a *authServiceImpl) Login(request models.LoginRequest) (*models.LoginRespo
}
func (a *authServiceImpl) Refresh(request models.RefreshRequest) (*models.RefreshResponse, error) {
return nil, errs.ErrNotImplemented
sessionInfo, err := a.ValidateToken(request.RefreshToken, enums.JwtRefreshTokenType); if err != nil {
if utils.ErrorIsOneOf(
err,
errs.ErrInvalidToken,
errs.ErrTokenExpired,
errs.ErrWrongTokenType,
errs.ErrSessionNotFound,
errs.ErrSessionTerminated,
) {
return nil, err
} else {
a.log.Error(
"Encountered an unexpected error while validating token",
zap.Error(err))
return nil, errs.ErrServerError
}
}
accessToken, refreshToken, err := utils.GenerateTokens(
sessionInfo.Username,
sessionInfo.Session,
sessionInfo.Role,
); if err != nil {
a.log.Error(
"Failed to generate tokens for user during refresh",
zap.String("username", sessionInfo.Username),
zap.String("session", sessionInfo.Session),
zap.Error(err))
return nil, errs.ErrServerError
}
response := models.RefreshResponse{
Tokens: models.Tokens{
AccessToken: accessToken,
RefreshToken: refreshToken,
},
}
return &response, nil
}
func (a *authServiceImpl) ValidateToken(jwtToken string, tokenType enums.JwtTokenType) (*dto.SessionInfo, error) {
var err error
token, err := jwt.ParseWithClaims(
jwtToken,
&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) {
return nil, errs.ErrTokenExpired
}
return nil, errs.ErrInvalidToken
}
claims, ok := token.Claims.(*dto.UserClaims); if ok && token.Valid {
if claims.Type != tokenType {
return nil, errs.ErrWrongTokenType
}
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))
return nil, redisErr
}
// 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))
return nil, errs.ErrSessionNotFound
}
a.log.Error(
"Failed to lookup session in database",
zap.String("session", claims.Session),
zap.Error(err))
return nil, err
}
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, err
}
isTerminated = *session.Terminated
}
if isTerminated {
return nil, errs.ErrSessionTerminated
}
}
sessionInfo := dto.SessionInfo{
Username: claims.Username,
Session: claims.Session,
Role: claims.Role,
}
return &sessionInfo, nil
}
func (a *authServiceImpl) PasswordResetBegin(request models.PasswordResetBeginRequest) (bool, error) {
@@ -654,7 +851,8 @@ func (a *authServiceImpl) PasswordResetComplete(request models.PasswordResetComp
zap.Error(err))
}
if accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String()); err != nil {
// TODO: get user role
if accessToken, refreshToken, err = utils.GenerateTokens(user.Username, session.Guid.String(), enums.UserRole); err != nil {
a.log.Error(
"Failed to generate tokens as part of user password reset",
zap.String("email", request.Email),

View File

@@ -0,0 +1,29 @@
// 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 utils
import "errors"
func ErrorIsOneOf(err error, ignoreErrors ...error) bool {
for _, ignore := range ignoreErrors {
if errors.Is(err, ignore) {
return false
}
}
return true
}

View File

@@ -25,22 +25,24 @@ import (
"github.com/golang-jwt/jwt/v5"
)
func GenerateTokens(username string, sessionGuid string) (accessToken, refreshToken string, err error) {
func GenerateTokens(username string, sessionGuid string, role enums.Role) (accessToken, refreshToken string, err error) {
cfg := config.GetConfig()
accessClaims := jwt.MapClaims{
"username": username,
"guid": sessionGuid,
"role": role,
"session": sessionGuid,
"type": enums.JwtAccessTokenType,
"exp": time.Now().Add(time.Minute * time.Duration(cfg.JwtExpAccess)).Unix(),
"exp": time.Now().Add(time.Minute * time.Duration(cfg.JwtExpAccess)).Unix(),
}
accessToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString([]byte(cfg.JwtSecret))
refreshClaims := jwt.MapClaims{
"username": username,
"guid": sessionGuid,
"role": role,
"session": sessionGuid,
"type": enums.JwtRefreshTokenType,
"exp": time.Now().Add(time.Hour * time.Duration(cfg.JwtExpRefresh)).Unix(),
"exp": time.Now().Add(time.Hour * time.Duration(cfg.JwtExpRefresh)).Unix(),
}
refreshToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString([]byte(cfg.JwtSecret))

View File

@@ -1,32 +1,31 @@
// 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 utils
import (
"easywish/internal/middleware"
"easywish/internal/dto"
"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")
request := req.(middleware.Request[T])
request := req.(dto.Request[T])
if !ok {
return nil, false
}

View File

@@ -238,13 +238,26 @@ SET
platform = COALESCE($3, platform),
latest_ip = COALESCE($4, latest_ip),
login_time = COALESCE($5, login_time),
last_seen_date = COALESCE($6, last_seen_date),
terminated = COALESCE($7, terminated)
last_refresh_exp_time = COALESCE($6, last_refresh_exp_time),
last_seen_date = COALESCE($7, last_seen_date),
terminated = COALESCE($8, terminated)
WHERE id = $1;
;-- name: GetUserSessions :many
;-- name: GetSessionByGuid :one
SELECT * FROM sessions
WHERE user_id = $1 AND terminated IS FALSE;
WHERE guid = (@guid::text)::uuid;
;-- name: GetValidUserSessions :many
SELECT * FROM sessions
WHERE
user_id = $1 AND terminated IS FALSE AND
last_refresh_exp_time > CURRENT_TIMESTAMP;
;-- name: GetUnexpiredTerminatedSessionsGuids :many
SELECT guid FROM sessions
WHERE
terminated IS TRUE AND
last_refresh_exp_time > CURRENT_TIMESTAMP;
;-- name: TerminateAllSessionsForUserByUsername :exec
UPDATE sessions

View File

@@ -66,6 +66,7 @@ CREATE TABLE IF NOT EXISTS "sessions" (
platform VARCHAR(32),
latest_ip VARCHAR(16),
login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_refresh_exp_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + INTERVAL '10080 seconds',
last_seen_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
terminated BOOLEAN DEFAULT FALSE
);