- Android: Added INTERNET permission and enabled cleartext traffic in AndroidManifest.xml. - Web: Implemented and registered CORSMiddleware in backend to allow cross-origin requests. - Flutter: Updated SettingsProvider to use 10.0.2.2 as default for Android Emulator for easier local testing.
60 lines
1.6 KiB
Go
60 lines
1.6 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"hightube/internal/utils"
|
|
)
|
|
|
|
// AuthMiddleware intercepts requests, validates JWT, and injects user_id into context
|
|
func AuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer {token}"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenStr := parts[1]
|
|
userIDStr, err := utils.ParseToken(tokenStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
userID, _ := strconv.ParseUint(userIDStr, 10, 32)
|
|
c.Set("user_id", uint(userID))
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// CORSMiddleware handles cross-origin requests from web clients
|
|
func CORSMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|