U
    \j                     @   s   d 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
 ddlmZ e
dgd	d
ZdZeedddZeeedddZeedddZeee dddZedddZdS )uC   安全工具：密码哈希、JWT 签发/校验、API Key 生成。    N)Optional)JWTErrorjwt)CryptContext   )settingsZbcryptauto)Zschemes
deprecatedZpica_)plainreturnc                 C   s
   t | S N)pwd_contexthash)r
    r   "/root/pica-gateway/app/security.pyhash_password   s    r   )r
   hashedr   c                 C   s   t | |S r   )r   verify)r
   r   r   r   r   verify_password   s    r   )user_idr   c                 C   s<   t j }t| ||t jtjd d}tj|tj	tj
dS )uL   签发会话 JWT。短期、用于调用本服务的受保护页面接口。)seconds)subZiatexp)	algorithm)dtdatetimeutcnowstr	timedeltar   jwt_expires_secondsr   encode
jwt_secretjwt_algorithm)r   nowpayloadr   r   r   create_access_token   s    
r%   )tokenr   c              
   C   sX   z6t j| tjtjgd}|d}|dk	r2t|ndW S  ttt	fk
rR   Y dS X dS )u'   校验 JWT，返回 user_id 或 None。)Z
algorithmsr   N)
r   decoder   r!   r"   getintr   
ValueError	TypeError)r&   r$   r   r   r   r   decode_access_token#   s      
r,   )r   c                   C   s   t td S )u3   生成一个随机 API Key 明文。32 字节熵。    )API_KEY_PREFIXsecretstoken_urlsafer   r   r   r   generate_api_key/   s    r1   )__doc__r/   r   r   typingr   Zjoser   r   Zpasslib.contextr   configr   r   r.   r   r   boolr   r)   r%   r,   r1   r   r   r   r   <module>   s   