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
This commit is contained in:
2026-02-27 21:21:18 +08:00
parent 6947577377
commit d49090a2ab
2 changed files with 17 additions and 12 deletions
+11 -3
View File
@@ -19,9 +19,9 @@ type TokenInfo struct {
} }
var ( var (
tokenMap = make(map[int]*TokenInfo) tokenMap = make(map[int]*TokenInfo)
tokenMux sync.RWMutex tokenMux sync.RWMutex
tokenTTL = time.Hour tokenTTL = time.Hour
) )
func GenerateToken(userID int) (string, error) { func GenerateToken(userID int) (string, error) {
@@ -168,3 +168,11 @@ func isValidPassword(password string) bool {
return hasUpper && hasLower && hasDigit && hasSpecial 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
}
+6 -9
View File
@@ -54,9 +54,8 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
currentTime := time.Now().UnixMilli() if err := ValidateTimeStamp(req.TimeStamp); err != nil {
if !globalConfig.Debug && (currentTime-req.TimeStamp > 3000 || req.TimeStamp-currentTime > 3000) { SendErrorResponse(w, http.StatusBadRequest, err.Error())
SendErrorResponse(w, http.StatusBadRequest, "timestamp out of valid range")
return return
} }
@@ -128,9 +127,8 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
currentTime := time.Now().UnixMilli() if err := ValidateTimeStamp(req.TimeStamp); err != nil {
if !globalConfig.Debug && (currentTime-req.TimeStamp > 3000 || req.TimeStamp-currentTime > 3000) { SendErrorResponse(w, http.StatusBadRequest, err.Error())
SendErrorResponse(w, http.StatusBadRequest, "timestamp out of valid range")
return return
} }
@@ -227,9 +225,8 @@ func ValidateRequestWithBody(w http.ResponseWriter, r *http.Request, body []byte
return 0, "", errors.New("timeStamp is required") return 0, "", errors.New("timeStamp is required")
} }
currentTime := time.Now().UnixMilli() if err := ValidateTimeStamp(int64(timeStamp)); err != nil {
if !globalConfig.Debug && (currentTime-int64(timeStamp) > 3000 || int64(timeStamp)-currentTime > 3000) { return 0, "", err
return 0, "", errors.New("timestamp out of valid range")
} }
userID, err := extractUserIDFromToken(token) userID, err := extractUserIDFromToken(token)