mirror of
https://gitlab.com/foxixus/neomovies-api.git
synced 2025-10-28 01:48:51 +05:00
feat: implement JWT refresh token mechanism and improve auth
This commit is contained in:
@@ -3,8 +3,8 @@ package handlers
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
|
||||
@@ -46,7 +46,14 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
response, err := h.authService.Login(req)
|
||||
// Получаем информацию о клиенте для refresh токена
|
||||
userAgent := r.Header.Get("User-Agent")
|
||||
ipAddress := r.RemoteAddr
|
||||
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
|
||||
ipAddress = forwarded
|
||||
}
|
||||
|
||||
response, err := h.authService.LoginWithTokens(req, userAgent, ipAddress)
|
||||
if err != nil {
|
||||
statusCode := http.StatusBadRequest
|
||||
if err.Error() == "Account not activated. Please verify your email." {
|
||||
@@ -74,7 +81,7 @@ func (h *AuthHandler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
func (h *AuthHandler) GoogleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
state := q.Get("state")
|
||||
code := q.Get("code")
|
||||
code := q.Get("code")
|
||||
preferJSON := q.Get("response") == "json" || strings.Contains(r.Header.Get("Accept"), "application/json")
|
||||
cookie, _ := r.Cookie("oauth_state")
|
||||
if cookie == nil || cookie.Value != state || code == "" {
|
||||
@@ -221,5 +228,82 @@ func (h *AuthHandler) ResendVerificationCode(w http.ResponseWriter, r *http.Requ
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// RefreshToken refreshes an access token using a refresh token
|
||||
func (h *AuthHandler) RefreshToken(w http.ResponseWriter, r *http.Request) {
|
||||
var req models.RefreshTokenRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Получаем информацию о клиенте
|
||||
userAgent := r.Header.Get("User-Agent")
|
||||
ipAddress := r.RemoteAddr
|
||||
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
|
||||
ipAddress = forwarded
|
||||
}
|
||||
|
||||
tokenPair, err := h.authService.RefreshAccessToken(req.RefreshToken, userAgent, ipAddress)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(models.APIResponse{
|
||||
Success: true,
|
||||
Data: tokenPair,
|
||||
Message: "Token refreshed successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// RevokeRefreshToken revokes a specific refresh token
|
||||
func (h *AuthHandler) RevokeRefreshToken(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.GetUserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
http.Error(w, "User ID not found in context", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var req models.RefreshTokenRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.authService.RevokeRefreshToken(userID, req.RefreshToken)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(models.APIResponse{
|
||||
Success: true,
|
||||
Message: "Refresh token revoked successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// RevokeAllRefreshTokens revokes all refresh tokens for the current user
|
||||
func (h *AuthHandler) RevokeAllRefreshTokens(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := middleware.GetUserIDFromContext(r.Context())
|
||||
if !ok {
|
||||
http.Error(w, "User ID not found in context", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.authService.RevokeAllRefreshTokens(userID)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(models.APIResponse{
|
||||
Success: true,
|
||||
Message: "All refresh tokens revoked successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// helpers
|
||||
func generateState() string { return uuidNew() }
|
||||
func generateState() string { return uuidNew() }
|
||||
|
||||
@@ -4,4 +4,4 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func uuidNew() string { return uuid.New().String() }
|
||||
func uuidNew() string { return uuid.New().String() }
|
||||
|
||||
@@ -119,4 +119,4 @@ func generateSlug(name string) string {
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,4 +26,4 @@ func HealthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
var startTime = time.Now()
|
||||
var startTime = time.Now()
|
||||
|
||||
@@ -131,4 +131,4 @@ func (h *ImagesHandler) isValidSize(size string, validSizes []string) bool {
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,8 +189,6 @@ func (h *MovieHandler) GetSimilar(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (h *MovieHandler) GetExternalIDs(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
id, err := strconv.Atoi(vars["id"])
|
||||
@@ -217,11 +215,11 @@ func getIntQuery(r *http.Request, key string, defaultValue int) int {
|
||||
if str == "" {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
|
||||
value, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"neomovies-api/pkg/config"
|
||||
"github.com/gorilla/mux"
|
||||
"neomovies-api/pkg/config"
|
||||
)
|
||||
|
||||
type PlayersHandler struct {
|
||||
@@ -26,29 +26,29 @@ func NewPlayersHandler(cfg *config.Config) *PlayersHandler {
|
||||
|
||||
func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("GetAllohaPlayer called: %s %s", r.Method, r.URL.Path)
|
||||
|
||||
|
||||
vars := mux.Vars(r)
|
||||
log.Printf("Route vars: %+v", vars)
|
||||
|
||||
|
||||
imdbID := vars["imdb_id"]
|
||||
if imdbID == "" {
|
||||
log.Printf("Error: imdb_id is empty")
|
||||
http.Error(w, "imdb_id path param is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
log.Printf("Processing imdb_id: %s", imdbID)
|
||||
|
||||
|
||||
if h.config.AllohaToken == "" {
|
||||
log.Printf("Error: ALLOHA_TOKEN is missing")
|
||||
http.Error(w, "Server misconfiguration: ALLOHA_TOKEN missing", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
idParam := fmt.Sprintf("imdb=%s", url.QueryEscape(imdbID))
|
||||
apiURL := fmt.Sprintf("https://api.alloha.tv/?token=%s&%s", h.config.AllohaToken, idParam)
|
||||
log.Printf("Calling Alloha API: %s", apiURL)
|
||||
|
||||
|
||||
resp, err := http.Get(apiURL)
|
||||
if err != nil {
|
||||
log.Printf("Error calling Alloha API: %v", err)
|
||||
@@ -56,105 +56,105 @@ func (h *PlayersHandler) GetAllohaPlayer(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
log.Printf("Alloha API response status: %d", resp.StatusCode)
|
||||
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
http.Error(w, fmt.Sprintf("Alloha API error: %d", resp.StatusCode), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("Error reading Alloha response: %v", err)
|
||||
http.Error(w, "Failed to read Alloha response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
log.Printf("Alloha API response body: %s", string(body))
|
||||
|
||||
|
||||
var allohaResponse struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
Data struct {
|
||||
Iframe string `json:"iframe"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
|
||||
if err := json.Unmarshal(body, &allohaResponse); err != nil {
|
||||
log.Printf("Error unmarshaling JSON: %v", err)
|
||||
http.Error(w, "Invalid JSON from Alloha", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if allohaResponse.Status != "success" || allohaResponse.Data.Iframe == "" {
|
||||
log.Printf("Video not found or empty iframe")
|
||||
http.Error(w, "Video not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
iframeCode := allohaResponse.Data.Iframe
|
||||
if !strings.Contains(iframeCode, "<") {
|
||||
iframeCode = fmt.Sprintf(`<iframe src="%s" allowfullscreen style="border:none;width:100%%;height:100%%"></iframe>`, iframeCode)
|
||||
}
|
||||
|
||||
|
||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Alloha Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframeCode)
|
||||
|
||||
|
||||
// Авто-исправление экранированных кавычек
|
||||
htmlDoc = strings.ReplaceAll(htmlDoc, `\"`, `"`)
|
||||
htmlDoc = strings.ReplaceAll(htmlDoc, `\'`, `'`)
|
||||
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(htmlDoc))
|
||||
|
||||
|
||||
log.Printf("Successfully served Alloha player for imdb_id: %s", imdbID)
|
||||
}
|
||||
|
||||
func (h *PlayersHandler) GetLumexPlayer(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("GetLumexPlayer called: %s %s", r.Method, r.URL.Path)
|
||||
|
||||
|
||||
vars := mux.Vars(r)
|
||||
log.Printf("Route vars: %+v", vars)
|
||||
|
||||
|
||||
imdbID := vars["imdb_id"]
|
||||
if imdbID == "" {
|
||||
log.Printf("Error: imdb_id is empty")
|
||||
http.Error(w, "imdb_id path param is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
log.Printf("Processing imdb_id: %s", imdbID)
|
||||
|
||||
|
||||
if h.config.LumexURL == "" {
|
||||
log.Printf("Error: LUMEX_URL is missing")
|
||||
http.Error(w, "Server misconfiguration: LUMEX_URL missing", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
url := fmt.Sprintf("%s?imdb_id=%s", h.config.LumexURL, url.QueryEscape(imdbID))
|
||||
log.Printf("Generated Lumex URL: %s", url)
|
||||
|
||||
|
||||
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, url)
|
||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Lumex Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
||||
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(htmlDoc))
|
||||
|
||||
|
||||
log.Printf("Successfully served Lumex player for imdb_id: %s", imdbID)
|
||||
}
|
||||
|
||||
func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("GetVibixPlayer called: %s %s", r.Method, r.URL.Path)
|
||||
|
||||
|
||||
vars := mux.Vars(r)
|
||||
log.Printf("Route vars: %+v", vars)
|
||||
|
||||
|
||||
imdbID := vars["imdb_id"]
|
||||
if imdbID == "" {
|
||||
log.Printf("Error: imdb_id is empty")
|
||||
http.Error(w, "imdb_id path param is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
log.Printf("Processing imdb_id: %s", imdbID)
|
||||
|
||||
if h.config.VibixToken == "" {
|
||||
@@ -162,7 +162,7 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
||||
http.Error(w, "Server misconfiguration: VIBIX_TOKEN missing", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
vibixHost := h.config.VibixHost
|
||||
if vibixHost == "" {
|
||||
vibixHost = "https://vibix.org"
|
||||
@@ -177,7 +177,7 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
||||
http.Error(w, "Failed to create request", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+h.config.VibixToken)
|
||||
req.Header.Set("X-CSRF-TOKEN", "")
|
||||
@@ -205,20 +205,20 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
||||
http.Error(w, "Failed to read Vibix response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
log.Printf("Vibix API response body: %s", string(body))
|
||||
|
||||
var vibixResponse struct {
|
||||
ID interface{} `json:"id"`
|
||||
IframeURL string `json:"iframe_url"`
|
||||
}
|
||||
|
||||
|
||||
if err := json.Unmarshal(body, &vibixResponse); err != nil {
|
||||
log.Printf("Error unmarshaling Vibix JSON: %v", err)
|
||||
http.Error(w, "Invalid JSON from Vibix", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if vibixResponse.ID == nil || vibixResponse.IframeURL == "" {
|
||||
log.Printf("Video not found or empty iframe_url")
|
||||
http.Error(w, "Video not found", http.StatusNotFound)
|
||||
@@ -226,12 +226,12 @@ func (h *PlayersHandler) GetVibixPlayer(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
log.Printf("Generated Vibix iframe URL: %s", vibixResponse.IframeURL)
|
||||
|
||||
|
||||
iframe := fmt.Sprintf(`<iframe src="%s" allowfullscreen loading="lazy" style="border:none;width:100%%;height:100%%;"></iframe>`, vibixResponse.IframeURL)
|
||||
htmlDoc := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset='utf-8'/><title>Vibix Player</title><style>html,body{margin:0;height:100%%;}</style></head><body>%s</body></html>`, iframe)
|
||||
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(htmlDoc))
|
||||
|
||||
|
||||
log.Printf("Successfully served Vibix player for imdb_id: %s", imdbID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,9 @@ func (h *ReactionsHandler) SetReaction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
var request struct{ Type string `json:"type"` }
|
||||
var request struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
@@ -146,4 +148,4 @@ func (h *ReactionsHandler) GetMyReactions(w http.ResponseWriter, r *http.Request
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(models.APIResponse{Success: true, Data: reactions})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,4 +42,4 @@ func (h *SearchHandler) MultiSearch(w http.ResponseWriter, r *http.Request) {
|
||||
Success: true,
|
||||
Data: results,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,12 +123,12 @@ func (h *TorrentsHandler) SearchTorrents(w http.ResponseWriter, r *http.Request)
|
||||
// Группируем сначала по сезонам, затем по качеству внутри каждого сезона
|
||||
seasonGroups := h.torrentService.GroupBySeason(results.Results)
|
||||
finalGroups := make(map[string]map[string][]models.TorrentResult)
|
||||
|
||||
|
||||
for season, torrents := range seasonGroups {
|
||||
qualityGroups := h.torrentService.GroupByQuality(torrents)
|
||||
finalGroups[season] = qualityGroups
|
||||
}
|
||||
|
||||
|
||||
response["grouped"] = true
|
||||
response["groups"] = finalGroups
|
||||
} else if options.GroupByQuality {
|
||||
@@ -364,4 +364,4 @@ func (h *TorrentsHandler) SearchByQuery(w http.ResponseWriter, r *http.Request)
|
||||
Success: true,
|
||||
Data: response,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,4 +203,4 @@ func (h *TVHandler) GetExternalIDs(w http.ResponseWriter, r *http.Request) {
|
||||
Success: true,
|
||||
Data: externalIDs,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user