
    Xjw                     (   d Z ddlZddlZddlZddlmZ ddlmZmZ ddl	m
Z
  ej                  e      Zej                  j                  ej                  j!                  e      dd      Z ee       defd	Zd
ZdedefdZdedefdZdedefdZy)uV  
Authentication helper for the Scheduler service.

Supports two auth strategies (checked in order):
1. JWT Bearer token — validated with the same HS256 secret as Laravel.
2. X-Token header  — looked up in the MYL_MASTER.users table (mirrors
   PHP AuthHelper::verifyAuth).

If neither header is present, the request is rejected with 401.
    N)load_dotenv)RequestHTTPException)get_master_connectionz..z.envreturnc                  J    t        j                  d      } | st        d      | S )z
    Resolve the JWT secret following a secure multi-tiered approach:
    environment variable -> .env file value (already loaded).
    
JWT_SECRETzTJWT_SECRET is not configured. Set it in the .env file or as an environment variable.)osgetenvRuntimeError)secrets    //var/www/html/myl_app/scheduler-service/auth.py_get_jwt_secretr      s/    
 YY|$FE
 	
 M    HS256tokenc                     t               }	 t        j                  | |t        gdg di      }|S # t        j                  $ r t        dd      t        j                  $ r}t        dd|       d}~ww xY w)	z9Decode and verify a JWT token.  Returns the payload dict.require)expiatsub)
algorithmsoptions  zToken has expired.status_codedetailzInvalid token: N)r   jwtdecodeJWT_ALGORITHMExpiredSignatureErrorr   InvalidTokenError)r   r   payloadexcs       r   _verify_jwtr%   ,   s    F
**%0	
 $$ J4HII   
ocU$;
 	

s   #0 2A7"A22A7c                     t               5 }|j                         5 }|j                  d| f       |j                         }ddd       ddd       st	        dd      |S # 1 sw Y   "xY w# 1 sw Y   &xY w)z?Look up the token in MYL_MASTER.users (mirrors PHP AuthHelper).z,SELECT * FROM users WHERE token = %s LIMIT 1Nr   z%Invalid token. Authentication failed.r   )r   cursorexecutefetchoner   )r   conncurusers       r   _verify_x_tokenr-   A   s    		  "D[[] 	"cKK> <<>D	"" $K
 	
 K	" 	"" "s"   A-$A! A-!A*	&A--A6requestc                     | j                   j                  dd      }|j                  d      r|dd }t        |      S | j                   j                  dd      }|rt	        |      S t        dd	      )
z
    Authenticate the incoming request.

    Returns a dict representing the authenticated user/payload.
    Raises HTTPException(401) on failure.
    Authorization zBearer    NzX-Tokenr   zHAuthentication required. Provide Authorization Bearer or X-Token header.r   )headersget
startswithr%   r-   r   )r.   auth_header	jwt_tokenx_tokens       r   authenticater9   R   sw     //%%or:Ki(O	9%% oo!!)R0Gw''
Y r   )__doc__r
   loggingr   dotenvr   fastapir   r   dbr   	getLogger__name__loggerpathjoindirname__file__	_ENV_PATHstrr   r    dictr%   r-   r9    r   r   <module>rJ      s   	 
  
  * $			8	$GGLL2D&A	 I   
s 
t 
*3 4 "' d r   