U
    sc                     @   sj   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZmZ ddlmZ G d	d
 d
ZdS )zS
we use middlewares in this project and this file store classes of our middlewares
    N)settings)timezonestatus)UserJWT)APIKeyInstituteJWT)
MyResponsec                   @   s&   e Zd Zd	ddZdd Zdd ZdS )
AuthorizatorMiddlewareFc                 C   s"   || _ || _|| _|| _|| _d S N)get_responseaccept_user_tokenaccept_server_tokenaccept_server_api_keyoptional_authentication)selfr   r   r   r   r    r   3/var/www/wikiazma_server/authenticate/middleware.py__init__   s
    zAuthorizatorMiddleware.__init__c                 C   s   |  |}|S r   )r   )r   requestresponser   r   r   __call__   s    
zAuthorizatorMiddleware.__call__c                 C   s4  |j dkr$|jd}|jd}n|jd}|jd}|rZ|rZt|dddtjdS d}d	}| jrz`tj	|t
jt
jt
jd
gd z*tjj|t d}	|	|_|	j|_d}W n   d}d}Y nX W n   d}d}Y nX |rd S | jrhzdtj	|t
jt
jt
jd
gd z.tjj|t d}
|
j|_|
jj|_d}W n   d}d}Y nX W n   d}d}Y nX |rrd S | jrz`tj	|t
jt
jt
jd
gd z*tjj|t d}||_|j|_d}W n   d}d}Y nX W n   d}d}Y nX |rd S | jst|d|dtjdS d |_d |_d |_d |_d S )NPOSTtokenapi_keyerrorz'you can not send both token and api_key)r   messager   FzAuthorization failed.HS256)issueraudience
algorithms)r   expire_at__gtTzEAuthorization failed. Cannot find a user corresponding to the token*.z/Authorization failed. Cannot decode the token*.zDAuthorization failed. Cannot find a user corresponding to the token.z.Authorization failed. Cannot decode the token.)r   r!   z3Authorization failed. Cannot find an APIKey record.z0Authorization failed. Cannot decode the api_key.)methoddatagetGETr	   r   HTTP_400_BAD_REQUESTr   jwtdecoder   
SECRET_KEY
JWT_ISSUERJWT_AUDIENCEr   objectsr   nowmiddleware_token_recordusermiddleware_userr   r   r   Zmiddleware_api_key	instituteZmiddleware_instituter   r   r   HTTP_401_UNAUTHORIZED)r   r   	view_func	view_argsview_kwargsr   r   successr   Zuserjwt_recordZinstitute_jwt_recordZapi_key_recordr   r   r   process_view!   s    
  
  

  
z#AuthorizatorMiddleware.process_viewN)FFFF)__name__
__module____qualname__r   r   r7   r   r   r   r   r
      s       
	r
   )__doc__r'   django.confr   django.utilsr   rest_frameworkr   authenticate.modelsr   institute.modelsr   r   utils.myresponser	   r
   r   r   r   r   <module>   s   