218 lines
7.4 KiB
Go
218 lines
7.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
configcore "bitrix_balancer_api/core/config"
|
|
dbcore "bitrix_balancer_api/core/db/methods"
|
|
redismodule "bitrix_balancer_api/core/lib/internally/redis"
|
|
"bitrix_balancer_api/core/securecore"
|
|
"bitrix_balancer_api/core/typescore"
|
|
"bitrix_balancer_api/core/utilscore"
|
|
"bitrix_balancer_api/core/variables"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func BasicAuthMiddleware(username, password string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
user, pass, ok := r.BasicAuth()
|
|
if !ok || !validateCredentials(user, pass, username, password) {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func validateCredentials(username, password, validUsername, validPassword string) bool {
|
|
return username == validUsername && password == validPassword
|
|
}
|
|
|
|
// JWTVerifier middleware для проверки JWT токена и соответствия IP
|
|
func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *redismodule.ModuleRedis) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if cfg.Secrets.AuthJWT.AdminSecret == "" {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
deviceID := r.Header.Get("x-device-id")
|
|
if deviceID == "" {
|
|
http.Error(w, "Unauthorized device", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if redisModule == nil {
|
|
http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
http.Error(w, "Invalid authorization header", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
tokenString := parts[1]
|
|
|
|
_, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret)
|
|
if err != nil {
|
|
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64)
|
|
if !ok {
|
|
http.Error(w, "Invalid token: missing user_id", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
userID := uint64(userIDFloat)
|
|
|
|
adminList, _, errW := adminDB.GetAdminsListDB(typescore.ListDbOptions{
|
|
Filtering: &typescore.Admin{
|
|
ID: &userID,
|
|
IsBlocked: utilscore.PointerToBool(false),
|
|
},
|
|
})
|
|
if errW != nil || len(adminList) == 0 {
|
|
http.Error(w, "Admin not found or blocked", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked {
|
|
http.Error(w, "Forbidden: account is blocked", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), securecore.IDContextKey, userID)
|
|
|
|
sessionJSON, err := redisModule.Get(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, userID))
|
|
if err != nil || sessionJSON == "" {
|
|
http.Error(w, "User session not found. Please authorize again", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
var session typescore.UsersSessions
|
|
if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil {
|
|
http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) {
|
|
http.Error(w, "Unauthorized device", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
// AccessCodeVerifier middleware для проверки Access Code для валидного фронта
|
|
func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
authHeader := r.Header.Get("ApiKey")
|
|
timestampStr := r.Header.Get("X-Timestamp")
|
|
|
|
if authHeader == "" || timestampStr == "" {
|
|
http.Error(w, "Unauthorized client", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Парсим timestamp как Unix timestamp
|
|
timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64)
|
|
if err != nil {
|
|
http.Error(w, "Invalid timestamp", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Конвертируем Unix timestamp в time.Time
|
|
// Unix timestamp всегда представляет время в UTC
|
|
timestampTime := time.Unix(timestampUnix, 0).UTC()
|
|
now := time.Now().UTC()
|
|
|
|
// Округляем время до минут, игнорируя секунды и миллисекунды
|
|
// Используем time.Date для явного обнуления секунд и наносекунд
|
|
timestampTimeRounded := time.Date(
|
|
timestampTime.Year(), timestampTime.Month(), timestampTime.Day(),
|
|
timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC,
|
|
)
|
|
nowRounded := time.Date(
|
|
now.Year(), now.Month(), now.Day(),
|
|
now.Hour(), now.Minute(), 0, 0, time.UTC,
|
|
)
|
|
|
|
// Проверяем, что timestamp не старше 3 минут и не в будущем
|
|
// Используем Before/After для более точной проверки времени
|
|
threeMinutesAgo := nowRounded.Add(-3 * time.Minute)
|
|
|
|
// Проверяем, что timestamp не не старше 3 минут
|
|
if timestampTimeRounded.Before(threeMinutesAgo) {
|
|
log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v",
|
|
timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo)
|
|
http.Error(w, "Timestamp expired", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Проверяем, что timestamp не в будущем
|
|
if timestampTimeRounded.After(nowRounded) {
|
|
log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)",
|
|
timestampTime, timestampTimeRounded, now, nowRounded)
|
|
http.Error(w, "Timestamp in future", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Генерируем ожидаемую подпись
|
|
expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicAdmin, timestampStr, cfg.Secrets.ApiPrivateAdmin)
|
|
|
|
// Сравниваем безопасно
|
|
if !utilscore.HmacEquals(expectedSignature, authHeader) {
|
|
http.Error(w, "Unauthorized client", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), securecore.AccessContextKey, authHeader)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
// GetIDFromContext извлекает user id из контекста
|
|
func GetIDFromContext(ctx context.Context) (uint64, error) {
|
|
address, ok := ctx.Value(securecore.IDContextKey).(uint64)
|
|
if !ok {
|
|
return 0, errors.New("no id found in context")
|
|
}
|
|
return address, nil
|
|
}
|
|
|
|
// GetIPFromContext извлекает user ip из контекста
|
|
func GetIPFromContext(ctx context.Context) (string, error) {
|
|
address, ok := ctx.Value(securecore.IpContextKey).(string)
|
|
if !ok {
|
|
return "", errors.New("no ip found in context")
|
|
}
|
|
return address, nil
|
|
}
|