* feat(spot): first version to test http endpoints * fix(helm): changed nginx path prefix * fix(spots): added missing BUCKET_NAME env var * fix(spots): added services init check * feat(spots): removed geo module * feat(spots): removed uaparser * feat(spots): added more detailed authorization error log * feat(spots): changed the authorization middleware * feat(spots): extended http body size limit to 128kb * feat(spots): added s3 error log * feat(spots): added new handler for uploaded event * feat(backend): small api changes in spot service * feat(backend): rewrote request parameters grabber for getSpot handler * feat(backend): added tenantID to auth struct * feat(backend): added pre-signed download urls for preview, mob et video files * feat(backend): added user's email to spots table, and getSpot responses * feat(backend): returning spotID as a string * feat(spot): added transcoder pipeline * fix(spot): return spotID as a string * feat(spot): added volume mount to spot service * feat(spot): fixed volume mounting * feat(spot): helm fix * feat(spot): helm another fix * fix(spot): correct video.webm path * fix(spot): correct pre-signed url for download original video * feat(spot): added PATCH and DELETE methods to CORS * feat(spot): use string format for spotIDs in delete method * feat(spot): added public key implemented * fix(spot): correct public-key parser * fix(spot): fixed query params issue + user's tenantID * fix(spot): use 1 as a default tenant * feat(spot): added correct total spots calculation * fix(spot): fixed offset calculation * feat(spot): added extra check in auth method * fix(spot): removed / from video file name * fix(spot): devided codec flag into 2 parts * feat(spot): use fixed tenantID = 1 for oss users * feat(spot): return 404 for public key not found issue * feat(spots): added spots folder to minio path rule * feat(spot): added spot video streaming support * fix(spot): fixed an sql request for spot streams * feat(spot): return playlist file in getSpot responce * feat(spot): try to use aac audio codec * feat(spot): added permissions support (oss/ee) * feat(spot): added authorizer method * feat(spot): added license check * feat(spot): added spot preview for get response * fix(spot): fixed a problem with permissions * feat(spot): added crop feature * feat(spot): upload cropped video back to s3 * feat(spot): manage expired modified playlist file * feat(backend): hack with video formats * feat(backend): removed space * feat(spot): req tracing * feat(spot): manual method's name mapping * feat(spot): added a second method to public key auth support * feat(spot): metrics * feat(spot): added rate limiter per user * feat(spot): added ping endpoint for spot jwt token check * feat(spot): getStatus endpoint * feat(spot): added missing import * feat(spot): transcoding issue fix * feat(spot): temp remove tasks * feat(spot): better error log message * feat(spot): set default jwt_secret value * feat(spot): debug auth * feat(spot): 2 diff jwt tokens support * feat(spot): pg tasks with process status * feat(spot): more logs * feat(spot): improved defer for GetTask method * feat(spot): keep only failed tasks * feat(spot): removing temp dir with spot files * feat(spot): added several workers for transcoding module * feat(spot): fixed spot path for temp video files * feat(spot): use custom statusWriter to track response code in middleware * feat(spot): added body and parameter parser for auditrail feature * feat(spot): fixed IsAuth method signature * feat(spot): fixed ee service builder * feat(spot): added import * feat(spot): fix data type for payload and parameters jsonb fields * feat(spot): typo fix * feat(spot): moved out consts * feat(spot): new table's name * feat(spot): added missing imports in go.mod * feat(spot): added a check for the number of comments (20 by default)
205 lines
6.1 KiB
Go
205 lines
6.1 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"openreplay/backend/pkg/spot"
|
|
"openreplay/backend/pkg/spot/auth"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/docker/distribution/context"
|
|
"github.com/gorilla/mux"
|
|
|
|
spotConfig "openreplay/backend/internal/config/spot"
|
|
"openreplay/backend/internal/http/util"
|
|
"openreplay/backend/pkg/logger"
|
|
)
|
|
|
|
type Router struct {
|
|
log logger.Logger
|
|
cfg *spotConfig.Config
|
|
router *mux.Router
|
|
mutex *sync.RWMutex
|
|
services *spot.ServicesBuilder
|
|
limiter *UserRateLimiter
|
|
}
|
|
|
|
func NewRouter(cfg *spotConfig.Config, log logger.Logger, services *spot.ServicesBuilder) (*Router, error) {
|
|
switch {
|
|
case cfg == nil:
|
|
return nil, fmt.Errorf("config is empty")
|
|
case services == nil:
|
|
return nil, fmt.Errorf("services is empty")
|
|
case log == nil:
|
|
return nil, fmt.Errorf("logger is empty")
|
|
}
|
|
e := &Router{
|
|
log: log,
|
|
cfg: cfg,
|
|
mutex: &sync.RWMutex{},
|
|
services: services,
|
|
limiter: NewUserRateLimiter(10, 30, 1*time.Minute, 5*time.Minute),
|
|
}
|
|
e.init()
|
|
return e, nil
|
|
}
|
|
|
|
func (e *Router) init() {
|
|
e.router = mux.NewRouter()
|
|
|
|
// Root route
|
|
e.router.HandleFunc("/", e.root)
|
|
|
|
// Spot routes
|
|
e.router.HandleFunc("/v1/spots", e.createSpot).Methods("POST", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}", e.getSpot).Methods("GET", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}", e.updateSpot).Methods("PATCH", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots", e.getSpots).Methods("GET", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots", e.deleteSpots).Methods("DELETE", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}/comment", e.addComment).Methods("POST", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}/uploaded", e.uploadedSpot).Methods("POST", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}/video", e.getSpotVideo).Methods("GET", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}/public-key", e.getPublicKey).Methods("GET", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}/public-key", e.updatePublicKey).Methods("PATCH", "OPTIONS")
|
|
e.router.HandleFunc("/v1/spots/{id}/status", e.spotStatus).Methods("GET", "OPTIONS")
|
|
e.router.HandleFunc("/v1/ping", e.ping).Methods("GET", "OPTIONS")
|
|
|
|
// CORS middleware
|
|
e.router.Use(e.corsMiddleware)
|
|
e.router.Use(e.authMiddleware)
|
|
e.router.Use(e.rateLimitMiddleware)
|
|
e.router.Use(e.actionMiddleware)
|
|
}
|
|
|
|
func (e *Router) root(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (e *Router) ping(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (e *Router) corsMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if e.cfg.UseAccessControlHeaders {
|
|
// Prepare headers for preflight requests
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "POST,GET,PATCH,DELETE")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization,Content-Encoding")
|
|
}
|
|
if r.Method == http.MethodOptions {
|
|
w.Header().Set("Cache-Control", "max-age=86400")
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
r = r.WithContext(context.WithValues(r.Context(), map[string]interface{}{"httpMethod": r.Method, "url": util.SafeString(r.URL.Path)}))
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (e *Router) authMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/" {
|
|
next.ServeHTTP(w, r)
|
|
}
|
|
isExtension := false
|
|
pathTemplate, err := mux.CurrentRoute(r).GetPathTemplate()
|
|
if err != nil {
|
|
e.log.Error(r.Context(), "failed to get path template: %s", err)
|
|
} else {
|
|
if pathTemplate == "/v1/ping" ||
|
|
(pathTemplate == "/v1/spots" && r.Method == "POST") ||
|
|
(pathTemplate == "/v1/spots/{id}/uploaded" && r.Method == "POST") {
|
|
isExtension = true
|
|
}
|
|
}
|
|
|
|
// Check if the request is authorized
|
|
user, err := e.services.Auth.IsAuthorized(r.Header.Get("Authorization"), getPermissions(r.URL.Path), isExtension)
|
|
if err != nil {
|
|
e.log.Warn(r.Context(), "Unauthorized request: %s", err)
|
|
if !isSpotWithKeyRequest(r) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
user, err = e.services.Keys.IsValid(r.URL.Query().Get("key"))
|
|
if err != nil {
|
|
e.log.Warn(r.Context(), "Wrong public key: %s", err)
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
}
|
|
|
|
r = r.WithContext(context.WithValues(r.Context(), map[string]interface{}{"userData": user}))
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func isSpotWithKeyRequest(r *http.Request) bool {
|
|
pathTemplate, err := mux.CurrentRoute(r).GetPathTemplate()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
getSpotPrefix := "/v1/spots/{id}" // GET
|
|
addCommentPrefix := "/v1/spots/{id}/comment" // POST
|
|
if (pathTemplate == getSpotPrefix && r.Method == "GET") || (pathTemplate == addCommentPrefix && r.Method == "POST") {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (e *Router) rateLimitMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
user := r.Context().Value("userData").(*auth.User)
|
|
rl := e.limiter.GetRateLimiter(user.ID)
|
|
|
|
if !rl.Allow() {
|
|
http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
type statusWriter struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
func (w *statusWriter) WriteHeader(statusCode int) {
|
|
w.statusCode = statusCode
|
|
w.ResponseWriter.WriteHeader(statusCode)
|
|
}
|
|
|
|
func (w *statusWriter) Write(b []byte) (int, error) {
|
|
if w.statusCode == 0 {
|
|
w.statusCode = http.StatusOK // Default status code is 200
|
|
}
|
|
return w.ResponseWriter.Write(b)
|
|
}
|
|
|
|
func (e *Router) actionMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Read body and restore the io.ReadCloser to its original state
|
|
bodyBytes, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "can't read body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
|
// Use custom response writer to get the status code
|
|
sw := &statusWriter{ResponseWriter: w}
|
|
// Serve the request
|
|
next.ServeHTTP(sw, r)
|
|
e.logRequest(r, bodyBytes, sw.statusCode)
|
|
})
|
|
}
|
|
|
|
func (e *Router) GetHandler() http.Handler {
|
|
return e.router
|
|
}
|