users.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. from fastapi import APIRouter, Form, Depends, HTTPException, Body
  2. from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
  3. from app.models.models import User, UserPydantic
  4. from app.api import deps
  5. from sqlalchemy.orm import Session
  6. from typing import Any, Dict, Optional
  7. import secrets
  8. from fastapi_login.exceptions import InvalidCredentialsException
  9. from fastapi_login import LoginManager
  10. from datetime import timedelta,datetime
  11. from app.config import settings
  12. from pathlib import Path
  13. from jose import jwt
  14. import emails
  15. from emails.template import JinjaTemplate
  16. import logging
  17. import bcrypt
  18. from app.crud import crud_users
  19. import smtplib
  20. from email.mime.text import MIMEText
  21. from google.oauth2 import id_token
  22. from google.auth.transport import requests
  23. from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
  24. from fastapi.security.utils import get_authorization_scheme_param
  25. import rpyc
  26. users = APIRouter()
  27. SECRET: str = secrets.token_urlsafe(32)
  28. manager = LoginManager(SECRET, '/login',default_expiry=timedelta(hours=72))
  29. async def check_token(access_token: str):
  30. result = await User.filter(token=access_token).first()
  31. if not result:
  32. print("no access")
  33. return None
  34. user_id = result.id
  35. return user_id
  36. @manager.user_loader()
  37. async def query_user(user_id: str):
  38. """
  39. Get a user from the db
  40. :param user_id: E-Mail of the user
  41. :return: None or the user object
  42. """
  43. # result = await User.filter(email=user_id,is_active=1).first()
  44. result = await User.filter(email=user_id).first()
  45. if not result:
  46. print('無此筆資料')
  47. return None
  48. return result
  49. #@manager.user_loader()
  50. async def query_user_username(user_id: str):
  51. """
  52. Get a user from the db
  53. :param user_id: E-Mail of the user
  54. :return: None or the user object
  55. """
  56. result = await User.filter(username=user_id).first()
  57. if not result:
  58. print('無此筆資料')
  59. return None
  60. return result
  61. @users.post("/login")
  62. async def login(data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(deps.get_db), position: str=Form(default='')):
  63. email = data.username
  64. password = data.password
  65. user = await query_user(email)
  66. user_pydantic = UserPydantic.from_orm(user)
  67. user_dict = user_pydantic.dict(exclude_unset=True)
  68. access_token = manager.create_access_token(
  69. data={'sub': email}
  70. )
  71. if not user:
  72. # you can return any response or error of your choice
  73. return {"message":"查無此人"}
  74. # elif password != user.password:
  75. # raise InvalidCredentialsException
  76. else:
  77. user_dict.update({"token":access_token})
  78. token_update = user.update_from_dict(user_dict)
  79. await user.save()
  80. stored_hashed_password = user.password.encode('utf-8')
  81. if bcrypt.checkpw(password.encode('utf-8'),stored_hashed_password):
  82. return {'msg':'登入成功','code':'200','access_token': access_token,'username':user.username,'email':user.email,'points':user.points}
  83. else:
  84. return {"message": "Invalid username or password"}
  85. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="https://oauth2.googleapis.com/token")
  86. CLIENT_ID = settings.CLIENT_ID
  87. @users.post("/login/google/access-token")
  88. async def login(username: str = Form(default=''), password: str = Form(default=''), email: str = Form(default=''), position: str = Form(default=''),
  89. ) -> Any:
  90. """
  91. OAuth2 compatible token login, get an access token for future requests
  92. """
  93. access_token = manager.create_access_token(
  94. data={'sub': username}
  95. )
  96. user = await User.filter(email=email).first() # 確認信箱是否已存在
  97. if not user:
  98. u = await User.create(username=username, password=password, email=email,token=access_token, is_superuser=0, points=0,is_active =1)
  99. create_user = u
  100. # if user:
  101. # print('已用相同信箱註冊過,再開一個GMAIL帳號')
  102. # u = await User.create(username=username, password=password,email=email)
  103. user_pydantic = UserPydantic.from_orm(user)
  104. user_dict = user_pydantic.dict(exclude_unset=True)
  105. user_dict.update({"token": access_token})
  106. token_update = user.update_from_dict(user_dict)
  107. await user.save()
  108. return_msg = {
  109. "access_token": access_token,
  110. "token_type": "bearer",
  111. 'code':'200',
  112. }
  113. return return_msg
  114. # if add_time_code:
  115. # available_ser_no = crud.serial_number.available(db, ser_no=add_time_code)
  116. # print(available_ser_no)
  117. # if available_ser_no:
  118. # user_in = schemas.UserUpdate(available_time=user.available_time + available_ser_no.time)
  119. # crud.user.update(db, db_obj=user, obj_in=user_in)
  120. #
  121. # ser_no_in = schemas.SerialNumberUpdate(code=available_ser_no.code, is_used=True,
  122. # used_datetime=str(datetime.now()), owner_id=user.id)
  123. # crud.serial_number.update(db, db_obj=available_ser_no, obj_in=ser_no_in)
  124. # print(available_ser_no.time, type(available_ser_no.time))
  125. # return_msg['time_added'] = available_ser_no.time
  126. # else:
  127. # return_msg['time_added'] = -1
  128. # return return_msg
  129. @users.post("/logout")
  130. async def logout():
  131. return {"msg":"logout success","code":200}
  132. @users.post("/add") # 寄認證信
  133. async def add(username: str = Form(default=''), password: str = Form(default=''), email: str = Form(default=''), re_password: str = Form(default='')):
  134. if username and password and email:
  135. user_email = await query_user(email)
  136. user_username = await query_user_username(username)
  137. if user_email or user_username:
  138. return {"msg":"該信箱或使用者名稱已存在","code":403}
  139. # elif user_username:
  140. # return {"msg":"該使用者名稱已存在","code":403}
  141. else:
  142. if password == re_password:
  143. # access_token = manager.create_access_token(
  144. # data={'sub': email}
  145. # )
  146. print('前',settings.SECRET_KEY)
  147. expiration_time = datetime.utcnow() + timedelta(hours=0.5)
  148. access_token = jwt.encode({'email':email,'exp':expiration_time}, settings.SECRET_KEY, algorithm="HS256")
  149. hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  150. u = await User.create(username=username, password=hashed_password, email=email,is_superuser=0,token=access_token,points=0,is_active=0)
  151. if u:
  152. # message = '註冊認證'
  153. message = f"請點擊以下連結完成註冊流程:\n\nhttps://cmm.ai:8088/api/verify?token={access_token}"
  154. subject = '註冊信'
  155. print(message)
  156. send_email(email,access_token,subject,message)
  157. return {"msg": "已寄送註冊信", "code": 200}
  158. else:
  159. return {"msg": "未寄出註冊信", "code":403}
  160. else:
  161. return {"msg":"確認密碼錯誤","code":403}
  162. return {"msg": "create user failed", "code": 403}
  163. @users.get("/verify") # 註冊認證確認
  164. async def verify_email(token:str):
  165. try:
  166. print(token)
  167. print('後',settings.SECRET_KEY)
  168. payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
  169. print('解密結果',payload)
  170. email = payload["email"]
  171. # is_active True
  172. user = await User.filter(email=email,is_active=0).first()
  173. if user:
  174. user_pydantic = UserPydantic.from_orm(user)
  175. user_dict = user_pydantic.dict(exclude_unset=True)
  176. user_dict.update({"is_active": 1})
  177. is_active_update = user.update_from_dict(user_dict)
  178. await user.save()
  179. result = '信箱驗證成功'
  180. else:
  181. result = '信箱驗證失敗'
  182. return {"message": result}
  183. except:
  184. raise HTTPException(status_code=400)
  185. # except jwt.ExpiredSignatureError:
  186. # raise HTTPException(status_code=400, detail="token已失效")
  187. # except jwt.DecodeError:
  188. # raise HTTPException(status_code=400, detail="無效token")
  189. def generate_password_reset_token(email: str) -> str:
  190. delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
  191. now = datetime.utcnow()
  192. expires = now + delta
  193. exp = expires.timestamp()
  194. encoded_jwt = jwt.encode(
  195. {"exp": exp, "nbf": now, "sub": email}, settings.SECRET_KEY, algorithm="HS256",)
  196. print(encoded_jwt)
  197. return encoded_jwt
  198. def verify_password_reset_token(token: str):
  199. try:
  200. decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
  201. print(decoded_token)
  202. return decoded_token["sub"]
  203. except jwt.JWTError:
  204. return None
  205. def send_email(
  206. email_to: str,
  207. token: str,
  208. subject_template: str = "",
  209. html_template: str = "",
  210. environment: Dict[str, Any] = {},
  211. ):
  212. # message = emails.Message(
  213. # subject=JinjaTemplate(subject_template),
  214. # html=JinjaTemplate(html_template),
  215. # mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
  216. # )
  217. subject=subject_template
  218. html=html_template
  219. mailobj={}
  220. mailobj['toaddr']=email_to
  221. mailobj['title']=subject
  222. mailobj['totext']=html
  223. conn = rpyc.connect("192.168.192.80", 12345)
  224. conn.root.mailto(mailobj)
  225. return {"message":f"send email"}
  226. #message = emails.Message(
  227. # subject=JinjaTemplate(subject_template),
  228. # html=JinjaTemplate(html_template),
  229. # mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
  230. #)
  231. #smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
  232. #if settings.SMTP_TLS:
  233. # smtp_options["tls"] = True
  234. #if settings.SMTP_USER:
  235. # smtp_options["user"] = settings.SMTP_USER
  236. #if settings.SMTP_PASSWORD:
  237. # smtp_options["password"] = settings.SMTP_PASSWORD
  238. #response = message.send(to=email_to, render=environment, smtp=smtp_options)
  239. #print('RResponse',response)
  240. #return {"message":f"send email result: {response}"}
  241. # logging.info(f"send email result: {response}")
  242. # email_content = MIMEText(message)
  243. # email_content["Subject"] = subject
  244. # email_content["From"] = 'zooey@choozmo.com'
  245. # email_content["To"] = email_to
  246. # try:
  247. # print('測試成功')
  248. # # Connect to the SMTP server
  249. # smtp_server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT)
  250. # smtp_server.starttls()
  251. #
  252. # # Login to the email account
  253. # smtp_server.login(settings.SMTP_HOST, settings.SMTP_PASSWORD)
  254. #
  255. # # Send the email
  256. # smtp_server.sendmail(settings.SMTP_HOST, email_to, email_content.as_string())
  257. #
  258. # # Close the connection
  259. # smtp_server.quit()
  260. #
  261. # return {"message": "Email sent successfully."}
  262. # except Exception as e:
  263. # print('測試失敗')
  264. def create_singup_url():
  265. url=''
  266. return url
  267. def send_reset_password_email(email_to: str, email: str, token: str) -> None:
  268. subject = f"Password recovery for user {email}"
  269. with open(Path(settings.EMAIL_TEMPLATES_DIR) / "reset_password.html") as f:
  270. template_str = f.read()
  271. server_host = settings.SERVER_HOST
  272. link = f"{server_host}/reset-password?token={token}"
  273. message = '重新設定密碼'
  274. send_email(
  275. email_to=email_to,
  276. subject_template=subject,
  277. html_template=template_str,
  278. environment={
  279. "project_name": settings.PROJECT_NAME,
  280. "username": email,
  281. "email": email_to,
  282. "valid_hours": settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS,
  283. "link": link,
  284. },
  285. )
  286. @users.post("/password-recovery/{email}")
  287. async def recover_password(email:str):
  288. user = await User.filter(email=email).first()
  289. if not user:
  290. raise HTTPException(
  291. status_code=404,
  292. detail="The user with this username does not exist in the system.",
  293. )
  294. password_reset_token = generate_password_reset_token(email=email)
  295. send_reset_password_email(
  296. email_to=user.email, email=email, token=password_reset_token
  297. )
  298. return {"msg": "Password recovery email sent"}
  299. from pydantic import BaseModel
  300. class Msg(BaseModel):
  301. msg: str
  302. @users.post("/reset-password/", response_model=Msg)
  303. async def reset_password(
  304. token: str = Body(...),
  305. new_password: str = Body(...),
  306. db: Session = Depends(deps.get_db),
  307. ) -> Any:
  308. """
  309. Reset password
  310. """
  311. email = verify_password_reset_token(token)
  312. print(email)
  313. if not email:
  314. raise HTTPException(status_code=400, detail="Invalid token")
  315. # user = await query_user(email)
  316. user = await User.filter(email=email).first()
  317. if not user:
  318. raise HTTPException(
  319. status_code=404,
  320. detail="The user with this username does not exist in the system.",
  321. )
  322. # elif not crud.user.is_active(user):
  323. # raise HTTPException(status_code=400, detail="Inactive user")
  324. hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
  325. user.password = hashed_password
  326. # db.add(user)
  327. db.commit()
  328. print(user.password)
  329. db.close()
  330. return {"msg": "Password updated successfully"}
  331. @users.get("/delete_user/{id}")
  332. async def delete(
  333. id: int,
  334. user_id = Depends(check_token)
  335. ):
  336. if not user_id :
  337. return {"msg": "no exit", "code": 200}
  338. user = await User.get(id=user_id)
  339. if user.is_superuser != 2:
  340. return {"msg": "no access", "code": 200}
  341. if id:
  342. await User.filter(id=id).delete()
  343. return {"msg": "success", "code": 200}
  344. return {"msg": "failed", "code": 400}
  345. @users.get("/information")
  346. async def get_information(token:str):
  347. result = await User.filter(token=token).first()
  348. return {"msg":result, "code":200}
  349. @users.get("/protect")
  350. def protected_route(user=Depends(manager)):
  351. if user is None:
  352. return {'message': "no access"}
  353. return {'user': user}
  354. @users.get("/check_user")
  355. async def check_user(
  356. user_id = Depends(check_token)
  357. ):
  358. user = await User.get(id=user_id)
  359. return {"msg": "success", "code": 200,"is_super":user.is_superuser}