o
    Fý¤hH  ã                   @   s¤   d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZmZ edeƒZd	ed
efdd„Ze d¡defdd„ƒZdS )aê  
media_routes.py

Purpose:
  Serve user-owned images through signed URLs instead of exposing /static/User-photos directly.
  Requires the user to be authenticated and to own the camera the image belongs to.

Routes:
  - GET /media/<token>

Security:
  - Token is an HMAC of the normalized relative path under User-photos using SECRET_KEY
  - No expiry to remain stable; access still requires session auth + ownership check
  - Prevents enumeration of /static/User-photos and direct linking
é    N)Ú	BlueprintÚabortÚ	send_fileÚsessionÚcurrent_appé   )Úget_db)ÚSTATIC_PATH)Úparse_ts_from_anyÚnormalize_to_static_user_photosÚresolve_share_tokenÚmedia_routesÚdataÚreturnc                 C   s    dt | ƒ d  }t | | ¡S )Nú=é   )ÚlenÚbase64Úurlsafe_b64decode)r   Úpadding© r   ú)/var/www/html/app_modules/media_routes.pyÚ_b64url_decode   s   r   z/media/<path:token>Útokenc                 C   sþ  d }d}|   d¡dkr*t| ƒ}|stdƒ |\}}dd l}| ¡ |kr'tdƒ d}nlt d¡}|s5td	ƒ d| vr=td
ƒ |  dd¡\}}z	t|ƒ d¡}W n t	y[   td
ƒ Y nw t
|ƒ}tj d¡pgd d¡}	t |	| d¡tj¡ ¡ }
zt|ƒ}W n t	y‹   td
ƒ Y nw t |
|¡s–tdƒ t|ƒ\}}|s¢tdƒ tƒ }|sÐ| dtd |f¡ ¡ }|sÐ| dtd f¡ ¡ }|rÌt|d pÈdƒdkrÐtdƒ tj t|¡}tj |¡}| tj t¡¡sêtd
ƒ tj |¡sôtdƒ t |ƒ}d|j!d< |S )NFú.é   i“  r   iš  TÚuser_idi‘  i  r   zutf-8Ú
SECRET_KEYÚ i”  z5SELECT 1 FROM cameras WHERE user_id=? AND camera_id=?z%SELECT is_admin FROM users WHERE id=?Úis_adminzprivate, max-age=300zCache-Control)"Úcountr   r   Útimer   ÚgetÚsplitr   ÚdecodeÚ	Exceptionr   r   ÚconfigÚencodeÚhmacÚnewÚhashlibÚsha256ÚdigestÚcompare_digestr
   r   ÚexecuteÚfetchoneÚintÚosÚpathÚjoinr	   ÚrealpathÚ
startswithÚexistsr   Úheaders)r   ÚrelÚ	is_publicÚresolvedÚexpÚ_tr   Úb64_relÚb64_macÚsecretÚexpectedÚprovidedÚ_ÚcamÚdbÚownerÚrowÚabs_pathÚreal_absÚrespr   r   r   Ú	media_get#   sf   
ÿÿ
rJ   )Ú__doc__r1   r   r(   r*   Úflaskr   r   r   r   r   rD   r   Úpathsr	   Úhelpersr
   r   r   Ú__name__ÚbpÚstrÚbytesr   ÚrouterJ   r   r   r   r   Ú<module>   s    
