Files
backend/handlers.go

119 lines
2.7 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"super-frpc/postLog"
"time"
)
type Response struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Data interface{} `json:"data,omitempty"`
}
func SendErrorResponse(w http.ResponseWriter, statusCode int, message string, data ...interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
resp := Response{
Success: false,
Message: message,
}
if len(data) > 0 {
resp.Data = data[0]
}
jsonResp, err := json.Marshal(resp)
if err != nil {
postLog.Error(fmt.Sprintf("Failed to marshal error response: %v", err))
return
}
w.Write(jsonResp)
}
func SendSuccessResponse(w http.ResponseWriter, message string, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
resp := Response{
Success: true,
Message: message,
Data: data,
}
jsonResp, err := json.Marshal(resp)
if err != nil {
postLog.Error(fmt.Sprintf("Failed to marshal success response: %v", err))
return
}
w.Write(jsonResp)
}
func Auth(w http.ResponseWriter, r *http.Request, targetMethod string, allowedUserLevels ...string) (int, error) {
if r.Method != targetMethod {
return 0, fmt.Errorf("Method not allowed: %s", targetMethod)
}
if !isDebug && !ValidateTimeStamp(r.Header) {
return 0, fmt.Errorf("Invalid or missing X-Timestamp in header")
}
userID, err := extractUserIDFromToken(r.Header.Get("X-Token"))
if err != nil {
return 0, fmt.Errorf("Invalid token format: %w", err)
}
if err := ValidateToken(userID, r.Header.Get("X-Token")); err != nil {
return 0, fmt.Errorf("Token validation failed: %w", err)
}
if len(allowedUserLevels) > 0 {
currentUser, err := DBQuerySpecificUser(userID)
if err != nil {
return 0, fmt.Errorf("Failed to query user: %w", err)
}
allowed := false
for _, level := range allowedUserLevels {
if currentUser.Type == level {
allowed = true
break
}
}
if !allowed {
return 0, fmt.Errorf("User level not allowed: required one of %v, got %s", allowedUserLevels, currentUser.Type)
}
}
return userID, nil
}
func GetUserType(userID int) (string, error) {
user, err := GetUserByID(userID)
if err != nil {
return "", fmt.Errorf("Failed to get user type: %w", err)
}
return user.Type, nil
}
func GetClientIP(r *http.Request) string {
forwarded := r.Header.Get("X-Forwarded-For")
if forwarded != "" {
return forwarded
}
return r.RemoteAddr
}
func LogRequest(r *http.Request, userID int) {
postLog.Info(fmt.Sprintf("[%s] %s %s - UserID: %d - IP: %s",
time.Now().Format("2006-01-02 15:04:05"),
r.Method,
r.URL.Path,
userID,
GetClientIP(r),
))
}
func IntToString(i int) string {
return strconv.Itoa(i)
}