From d49090a2ab0f26df31235b79e24da85d4fdf1f57 Mon Sep 17 00:00:00 2001 From: NanamiAdmin Date: Fri, 27 Feb 2026 21:21:18 +0800 Subject: [PATCH] refactor(auth): extract timestamp validation to separate function Move timestamp validation logic from handlers to ValidateTimeStamp function in auth.go to avoid code duplication and improve maintainability --- auth.go | 14 +++++++++++--- handlers.go | 15 ++++++--------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/auth.go b/auth.go index 8b04fde..37ca10f 100644 --- a/auth.go +++ b/auth.go @@ -19,9 +19,9 @@ type TokenInfo struct { } var ( - tokenMap = make(map[int]*TokenInfo) - tokenMux sync.RWMutex - tokenTTL = time.Hour + tokenMap = make(map[int]*TokenInfo) + tokenMux sync.RWMutex + tokenTTL = time.Hour ) func GenerateToken(userID int) (string, error) { @@ -168,3 +168,11 @@ func isValidPassword(password string) bool { return hasUpper && hasLower && hasDigit && hasSpecial } + +func ValidateTimeStamp(timeStamp int64) error { + currentTime := time.Now().UnixMilli() + if !globalConfig.Debug && (currentTime-timeStamp > 3000 || timeStamp-currentTime > 3000) { + return errors.New("timestamp out of valid range") + } + return nil +} diff --git a/handlers.go b/handlers.go index 6f65c58..6f7a800 100644 --- a/handlers.go +++ b/handlers.go @@ -54,9 +54,8 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) { return } - currentTime := time.Now().UnixMilli() - if !globalConfig.Debug && (currentTime-req.TimeStamp > 3000 || req.TimeStamp-currentTime > 3000) { - SendErrorResponse(w, http.StatusBadRequest, "timestamp out of valid range") + if err := ValidateTimeStamp(req.TimeStamp); err != nil { + SendErrorResponse(w, http.StatusBadRequest, err.Error()) return } @@ -128,9 +127,8 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) { return } - currentTime := time.Now().UnixMilli() - if !globalConfig.Debug && (currentTime-req.TimeStamp > 3000 || req.TimeStamp-currentTime > 3000) { - SendErrorResponse(w, http.StatusBadRequest, "timestamp out of valid range") + if err := ValidateTimeStamp(req.TimeStamp); err != nil { + SendErrorResponse(w, http.StatusBadRequest, err.Error()) return } @@ -227,9 +225,8 @@ func ValidateRequestWithBody(w http.ResponseWriter, r *http.Request, body []byte return 0, "", errors.New("timeStamp is required") } - currentTime := time.Now().UnixMilli() - if !globalConfig.Debug && (currentTime-int64(timeStamp) > 3000 || int64(timeStamp)-currentTime > 3000) { - return 0, "", errors.New("timestamp out of valid range") + if err := ValidateTimeStamp(int64(timeStamp)); err != nil { + return 0, "", err } userID, err := extractUserIDFromToken(token)