user.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import dataset
  2. from fastapi import FastAPI,Cookie, Depends, Query, status,File, UploadFile,Request,Response,HTTPException
  3. from first import first
  4. from jose import JWTError, jwt
  5. from fastapi_jwt_auth import AuthJWT
  6. from fastapi_jwt_auth.exceptions import AuthJWTException
  7. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  8. import util.models
  9. from passlib.context import CryptContext
  10. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  11. ALGORITHM = "HS256"
  12. ACCESS_TOKEN_EXPIRE_DAYS = 5
  13. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  14. def get_user_id(token):
  15. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  16. credentials_exception = HTTPException(
  17. status_code=status.HTTP_401_UNAUTHORIZED,
  18. detail="Could not validate credentials",
  19. headers={"WWW-Authenticate": "Bearer"},
  20. )
  21. try:
  22. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  23. username: str = payload.get("sub")
  24. if username is None:
  25. raise credentials_exception
  26. token_data = uitl.models.TokenData(username=username)
  27. except JWTError:
  28. raise credentials_exception
  29. user = get_user(username=token_data.username)
  30. if user is None:
  31. raise credentials_exception
  32. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  33. return user_id
  34. def check_user_exists( username):
  35. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  36. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  37. return True
  38. else:
  39. return False
  40. def get_user( username: str):
  41. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  42. if not check_user_exists(username): # if user don't exist
  43. return False
  44. user_dict = next(
  45. iter(db.query('SELECT * FROM users where username ="'+username+'"')))
  46. user = util.models.User(**user_dict)
  47. return user
  48. def user_register( user):
  49. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  50. table = db['users']
  51. user.password = get_password_hash(user.password)
  52. table.insert(dict(user))
  53. def get_password_hash( password):
  54. return pwd_context.hash(password)
  55. def verify_password( plain_password, hashed_password):
  56. return pwd_context.verify(plain_password, hashed_password)
  57. def authenticate_user( username: str, password: str):
  58. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  59. if not check_user_exists(username): # if user don't exist
  60. return False
  61. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  62. user = util.models.User(**user_dict)
  63. if not verify_password(password, user.password):
  64. return False
  65. return user
  66. def get_user_role(id):
  67. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  68. state = 'SELECT * FROM user_role '\
  69. 'INNER JOIN users on user_role.user_id= users.id '\
  70. 'INNER JOIN role on user_role.role_id = role.id '\
  71. 'WHERE users.id='+str(id)
  72. role_list = []
  73. for row in db.query(state):
  74. role_list.append({'id':row['role_id'],'name':row['name']})
  75. return role_list
  76. def get_avatar_by_role(id):
  77. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  78. state = 'SELECT * FROM (
  79. 'SELECT role_id FROM AI_anchor.user_role '\
  80. 'INNER JOIN users on user_role.user_id= users.id '\
  81. 'INNER JOIN role on user_role.role_id = role.id '\
  82. 'WHERE AI_anchor.users.id=36) a'\
  83. 'INNER JOIN role on a.role_id = role.id'\
  84. 'INNER JOIN avatar on role_avatar.id = avatar.id'\
  85. role_list = []
  86. for row in db.query(state):
  87. role_list.append({'id':row['role_id'],'name':row['name']})
  88. return role_list
  89. #def add_role( username,role_id):
  90. #db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  91. #user_role_table = db['user_role']
  92. #user_role_table.insert({'user_id':,'role_id':role_id})
  93. def get_user_id(token):
  94. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  95. credentials_exception = HTTPException(
  96. status_code=status.HTTP_401_UNAUTHORIZED,
  97. detail="Could not validate credentials",
  98. headers={"WWW-Authenticate": "Bearer"},
  99. )
  100. try:
  101. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  102. username: str = payload.get("sub")
  103. if username is None:
  104. raise credentials_exception
  105. token_data = util.models.TokenData(username=username)
  106. except JWTError:
  107. raise credentials_exception
  108. user = get_user(username=token_data.username)
  109. if user is None:
  110. raise credentials_exception
  111. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  112. return user_id
  113. def get_id_by_email(email):
  114. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  115. user_dict = next(iter(db.query('SELECT * FROM users where email ="'+email+'"')))
  116. return user_dict['id']
  117. def email_veri_pass(name):
  118. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  119. user_dict = next(iter(db.query('SELECT * FROM users where username ="'+name+'"')))
  120. user_obj = first(db.query('SELECT * FROM register_veri_code where user_id ="'+str(user_dict['id'])+'"'))
  121. if user_obj == None:
  122. return True
  123. else:
  124. return False