
    :j0                     &   d Z ddlmZmZmZmZmZmZmZm	Z	 ddl
mZmZ ddlmZ ddlZddlZddlmZ ddlmZ ddlZddlmZ 	  ed	gd
      ZdededefdZ ede      Zej?                  d      d        Z ej?                  dddg      d        Z!ej?                  ddg      d        Z"ej?                  d      d        Z#ej?                  ddg      d        Z$ej?                  d dg      d!        Z%y# e$ r  ed	gd
d	dg      ZY w xY w)"z\
Authentication Routes Blueprint
Contains login, registration, password reset functionality
    )	Blueprintrequestrender_templateredirecturl_forflashjsonifysession)create_enginetext)sessionmakerN)MIMEText)MIMEMultipart)CryptContextbcryptauto)schemes
deprecatedos_crypt)r   r   bcrypt__backendspasswordpassword_hashreturnc                 J   	 t         j                  | |      S # t        $ rw}dt        |      v rd	 ddl}| j                  d      }t        |t              r|j                  d      }n|}|j                  ||      cY d}~S # t        $ r Y Y d}~yw xY w d}~wt        $ r Y yw xY w)zZ
    Verify password against hash with error handling for bcrypt compatibility issues
    	__about__r   Nzutf-8F)	pwd_contextverifyAttributeErrorstrr   encode
isinstancecheckpw	Exception)r   r   er   password_bytes
hash_bytess         8/var/www/bookbeach.app/backend/app/routes/auth_routes.pyverify_passwordr(      s    !!(M:: #a& !)!9mS1!.!5!5g!>J!.J~~njAA 
  s>    	B"BA
A?9B"?	BBBBB"!B"authz	/registerc                  H    ddl m}  t        d| j                  dd            S )zUser registration pager   ADMIN_CONFIGzregister.htmlGOOGLE_MAPS_API_KEYzyour-google-maps-api-key)google_maps_key)configr,   r   getr+   s    r'   registerr1   ;   s)     $?L<L<LMbd~<  A  A    z/loginGETPOST)methodsc                     t         j                  dk(  rddlm}  t         j                  j                  dd      j                         }t         j                  j                  dd      j                         }|r|st        dd       t        d	      S | d
   }t        |      }t        dd|      } |       }	 |j                  t        d      d|i      j                         }|r|j                  rt        ||j                        r^d}|j                   r|j                   j#                         dk(  rd}|j$                  s)|s't        dd       t        d	      |j'                          S t)        |j*                        t,        d<   |j.                  t,        d<   |j0                   d|j2                   t,        d<   |j4                  r|j4                  t,        d<   |t,        d<   t        dd       |r$t7        t9        d            |j'                          S t         j:                  j                  d      }	|	rt7        |	      nt7        t9        d            	 |j'                          S t        dd       np|| d   k(  r\|| d   k(  rTdt,        d <   |t,        d!<   dt,        d<   dt,        d<   t        d"d       t7        t9        d            |j'                          S t        dd       |j'                          t        d	      S t        d	      S # t<        $ r"}
t        d#t)        |
       d       Y d$}
~
Ld$}
~
ww xY w# |j'                          w xY w)%z"User login page and authenticationr4   r   r+   email r   z Email and password are required.errorz
login.htmlDATABASE_URLF
autocommit	autoflushbinda{  
                SELECT u.user_id, u.password_hash, u.first_name, u.last_name, u.email, u.is_email_verified, u.profile_photo_path,
                       ur.role_name
                FROM users u
                LEFT JOIN user_roles ur ON u.role_id = ur.role_id
                WHERE (u.email = :email OR u.first_name = :email)
                AND u.is_active = true
            adminTz3Please verify your email address before logging in.warninguser_id
user_email 	user_name
user_photois_adminzLogin successful!successzadmin.admin_dashboardnext
main.indexzInvalid email or password.ADMIN_USERNAMEADMIN_PASSWORDadmin_logged_inadmin_usernamezAdmin login successful!z An error occurred during login: N)r   methodr/   r,   formr0   stripr   r   r   r   executer   fetchoner   r(   	role_nameloweris_email_verifiedcloser   rA   r
   r7   
first_name	last_nameprofile_photo_pathr   r   argsr#   )r,   r7   r   r:   engineSessionLocaldbuser_resultrF   	next_pager$   s              r'   loginr`   A   s    ~~'   "-335<<##J399; H4g>"<00 $N3|,#uFS^<	**T + & E"$ %-HJ  {88"8[-F-FG$H",,1F1F1L1L1NRY1Y#'&88SU^_.|<N HHJI *-[-@-@)AGI&,7,=,=GL).9.D.D-EQ{G\G\F]+^GK("550;0N0N- +3GJ'-y9  '0G(HI, HHJ' !( 0 0 8I2;8I.'R^J_A``$ HHJ! 6@ L)9::x<XhKi?i15G-.05G,-)0GI&*.GJ'3Y?#G,C$DE HHJ 6@
 HHJ<((?<((  	H4SVH=wGG	H HHJsE   8B#L ,BL ?L (A L L 	L6L1,L9 1L66L9 9Mz/forgot-passwordc                      t        d      S )zForgot password pagezforgot-password.html)r    r2   r'   forgot_passwordrc      s     122r2   z/logoutc                  j    t        j                          t        dd       t        t	        d            S )zUser logoutzYou have been logged out.inforI   )r
   clearr   r   r   rb   r2   r'   logoutrg      s(     MMO	
%v.GL)**r2   z/api/send-verificationc                  `   	 ddl m} m} t        j                         }|j                  d      }|st        ddd      dfS | d   }t        |      }t        dd|	      } |       }	 |j                  t        d
      d|i      j                         }|s t        ddd      df|j                          S |j                  r t        ddd      df|j                          S t        j                  d      }	|j                  t        d      |	|d       |j!                          t        j"                   d|	 }
d}d|j$                   d|
 d} ||||      }|rt        ddd      |j                          S t        ddd      df|j                          S # t&        $ rF}|j)                          t        ddt+        |       d      dfcY d}~|j                          S d}~ww xY w# |j                          w xY w# t&        $ r&}t        ddt+        |       d      dfcY d}~S d}~ww xY w)zSend email verificationr   )r,   
send_emailr7   FzEmail is requiredrG   message  r:   r;   z
                SELECT user_id, first_name, email, is_email_verified
                FROM users 
                WHERE email = :email
            zEmail not foundi  zEmail is already verified    z
                UPDATE users 
                SET verification_token = :token, verification_token_expires = NOW() + INTERVAL '24 hours'
                WHERE email = :email
            )tokenr7   zapi/verify-email?token=zVerify Your Email Addressz
            Hello za,
            
            Please click the link below to verify your email address:
            z
            
            This link will expire in 24 hours.
            
            If you didn't create an account, please ignore this email.
            
            Best regards,
            The BookBeach Team
            Tz$Verification email sent successfullyz!Failed to send verification email  Database error: NServer error: )r/   r,   ri   r   get_jsonr0   r	   r   r   rQ   r   rR   rV   rU   secretstoken_urlsafecommithost_urlrW   r#   rollbackr   )r,   ri   datar7   r:   r[   r\   r]   r^   verification_tokenverification_urlsubjectbodyrG   r$   s                  r'   send_verificationr}      sW   IV3!!u9LMNPSSS $N3|,#uFS^6	**T + & E"	$ %-HJ	  5=NOPRUUZ HHJW ,,5=XYZ\__T HHJO ")!6!6r!: JJt   /?	A
 IIK #*"2"2!33JK]J^_1G))* +  	D !6G4<bcd HHJ 5=`abdgg HHJ	  	\KKMu;KCPQF89TUVX[[[HHJ		\ HHJ V5~c!fX5NOPRUUUVs   >G> %G> '<F #G> 4F G>  BF &G> 7F G> 	G& +G!G&G) G> !G&&G) )G;;G> >	H-H("H-(H-z/api/verify-emailc                  p   	 ddl m}  t        j                         }|j	                  d      }|st        ddd      dfS | d   }t        |      }t        dd|	      } |       }	 |j                  t        d
      d|i      j                         }|s t        ddd      df|j                          S |j                  t        d      d|j                  i       |j                          t        dd|j                  |j                  dd      |j                          S # t         $ rF}|j#                          t        ddt%        |       d      dfcY d}~|j                          S d}~ww xY w# |j                          w xY w# t         $ r&}t        ddt%        |       d      dfcY d}~S d}~ww xY w)zVerify email addressr   r+   rn   FzVerification token is requiredrj   rl   r:   r;   z
                SELECT user_id, email, first_name
                FROM users 
                WHERE verification_token = :token 
                AND verification_token_expires > NOW()
                AND is_email_verified = false
            z%Invalid or expired verification tokenz
                UPDATE users 
                SET is_email_verified = true, verification_token = NULL, verification_token_expires = NULL
                WHERE user_id = :user_id
            rA   TzEmail verified successfully)r7   rW   )rG   rk   userrp   ro   Nrq   )r/   r,   r   rr   r0   r	   r   r   rQ   r   rR   rV   rA   ru   r7   rW   r#   rw   r   )	r,   rx   rn   r:   r[   r\   r]   r^   r$   s	            r'   verify_emailr      s   5V'!!u9YZ[]``` $N3|,#uFS^"	**T + & E"$ %-HJ  5=defhkk. HHJ) JJt   k112	4
 IIK8(.."-"8"8  HHJ	  	\KKMu;KCPQF89TUVX[[[HHJ		\ HHJ V5~c!fX5NOPRUUUVsq   <F %F %<D !F 2AD F 	E.(+E)E.E1 F )E..E1 1FF 	F5F0*F50F5)&__doc__flaskr   r   r   r   r   r   r	   r
   
sqlalchemyr   r   sqlalchemy.ormr   rs   smtplibemail.mime.textr   email.mime.multipartr   ospasslib.contextr   r   r#   r   boolr(   __name__auth_bprouter1   r`   rc   rg   r}   r   rb   r2   r'   <module>r      sn   b a a * '   $ . 	 )GzfEKc # $ > FH
%{A A
 	x%1T) 2T)l 	!E733 43 	y+ + 	'&:KV ;KVZ 	"VH57V 67V}  Gzf08*/EGKGs   C: :DD