* 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)
146 lines
4.2 KiB
Go
146 lines
4.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/rs/xid"
|
|
"openreplay/backend/pkg/spot/auth"
|
|
"time"
|
|
|
|
"openreplay/backend/pkg/db/postgres/pool"
|
|
"openreplay/backend/pkg/logger"
|
|
)
|
|
|
|
type Key struct {
|
|
SpotID uint64 `json:"-"`
|
|
UserID uint64 `json:"-"` // to track who generated the key
|
|
TenantID uint64 `json:"-"` // to check availability
|
|
Value string `json:"value"`
|
|
Expiration uint64 `json:"expiration"` // in seconds
|
|
ExpiredAt time.Time `json:"-"`
|
|
}
|
|
|
|
type Keys interface {
|
|
Set(spotID, expiration uint64, user *auth.User) (*Key, error)
|
|
Get(spotID uint64, user *auth.User) (*Key, error)
|
|
IsValid(key string) (*auth.User, error)
|
|
}
|
|
|
|
type keysImpl struct {
|
|
log logger.Logger
|
|
conn pool.Pool
|
|
}
|
|
|
|
func (k *keysImpl) Set(spotID, expiration uint64, user *auth.User) (*Key, error) {
|
|
switch {
|
|
case spotID == 0:
|
|
return nil, fmt.Errorf("spotID is required")
|
|
case expiration > 604800:
|
|
return nil, fmt.Errorf("expiration should be less than 7 days")
|
|
case user == nil:
|
|
return nil, fmt.Errorf("user is required")
|
|
}
|
|
now := time.Now()
|
|
if expiration == 0 {
|
|
sql := `UPDATE spots_keys SET expired_at = $1, expiration = 0 WHERE spot_id = $2`
|
|
if err := k.conn.Exec(sql, now, spotID); err != nil {
|
|
k.log.Error(context.Background(), "failed to set key: %v", err)
|
|
return nil, fmt.Errorf("key not updated")
|
|
}
|
|
return nil, nil
|
|
}
|
|
newKey := xid.New().String()
|
|
expiredAt := now.Add(time.Duration(expiration) * time.Second)
|
|
sql := `
|
|
WITH updated AS (
|
|
UPDATE spots_keys
|
|
SET
|
|
spot_key = CASE
|
|
WHEN expired_at < $1 THEN $2
|
|
ELSE spot_key
|
|
END,
|
|
user_id = $3,
|
|
expiration = $4,
|
|
expired_at = $5,
|
|
updated_at = $1
|
|
WHERE spot_id = $6
|
|
RETURNING spot_key, expiration, expired_at
|
|
),
|
|
|
|
inserted AS (
|
|
INSERT INTO spots_keys (spot_key, spot_id, user_id, tenant_id, expiration, created_at, expired_at)
|
|
SELECT $2, $6, $3, $7, $4, $1, $5
|
|
WHERE NOT EXISTS (SELECT 1 FROM updated)
|
|
RETURNING spot_key, expiration, expired_at
|
|
)
|
|
|
|
SELECT spot_key, expiration, expired_at FROM updated
|
|
UNION ALL
|
|
SELECT spot_key, expiration, expired_at FROM inserted;
|
|
`
|
|
key := &Key{}
|
|
if err := k.conn.QueryRow(sql, now, newKey, user.ID, expiration, expiredAt, spotID, user.TenantID).
|
|
Scan(&key.Value, &key.Expiration, &key.ExpiredAt); err != nil {
|
|
k.log.Error(context.Background(), "failed to set key: %v", err)
|
|
return nil, fmt.Errorf("key not updated")
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
func (k *keysImpl) Get(spotID uint64, user *auth.User) (*Key, error) {
|
|
switch {
|
|
case spotID == 0:
|
|
return nil, fmt.Errorf("spotID is required")
|
|
case user == nil:
|
|
return nil, fmt.Errorf("user is required")
|
|
}
|
|
//
|
|
key := &Key{}
|
|
sql := `SELECT spot_key, expiration, expired_at FROM spots_keys WHERE spot_id = $1 AND tenant_id = $2`
|
|
if err := k.conn.QueryRow(sql, spotID, user.TenantID).Scan(&key.Value, &key.Expiration, &key.ExpiredAt); err != nil {
|
|
k.log.Error(context.Background(), "failed to get key: %v", err)
|
|
return nil, fmt.Errorf("key not found")
|
|
}
|
|
now := time.Now()
|
|
if key.ExpiredAt.Before(now) {
|
|
return nil, fmt.Errorf("key is expired")
|
|
}
|
|
key.Expiration = uint64(key.ExpiredAt.Sub(now).Seconds())
|
|
return key, nil
|
|
}
|
|
|
|
func (k *keysImpl) IsValid(key string) (*auth.User, error) {
|
|
if key == "" {
|
|
return nil, fmt.Errorf("key is required")
|
|
}
|
|
var (
|
|
userID uint64
|
|
expiredAt time.Time
|
|
)
|
|
// Get userID if key is valid
|
|
sql := `SELECT user_id, expired_at FROM spots_keys WHERE spot_key = $1`
|
|
if err := k.conn.QueryRow(sql, key).Scan(&userID, &expiredAt); err != nil {
|
|
k.log.Error(context.Background(), "failed to get key: %v", err)
|
|
return nil, fmt.Errorf("key not found")
|
|
}
|
|
now := time.Now()
|
|
if expiredAt.Before(now) {
|
|
return nil, fmt.Errorf("key is expired")
|
|
}
|
|
// Get user info by userID
|
|
user := &auth.User{ID: userID, AuthMethod: "public-key"}
|
|
// We don't need tenantID here
|
|
sql = `SELECT 1, name, email FROM public.users WHERE user_id = $1 AND deleted_at IS NULL LIMIT 1`
|
|
if err := k.conn.QueryRow(sql, userID).Scan(&user.TenantID, &user.Name, &user.Email); err != nil {
|
|
k.log.Error(context.Background(), "failed to get user: %v", err)
|
|
return nil, fmt.Errorf("user not found")
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
func NewKeys(log logger.Logger, conn pool.Pool) Keys {
|
|
return &keysImpl{
|
|
log: log,
|
|
conn: conn,
|
|
}
|
|
}
|