user.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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_user_role(id):
  77. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  78. state = 'SELECT * FROM user_role '\
  79. 'INNER JOIN users on user_role.user_id= users.id '\
  80. 'INNER JOIN role on user_role.role_id = role.id '\
  81. 'WHERE username="ming"'
  82. role_list = []
  83. for row in db.query(state):
  84. role_list.append({'id':row['role_id'],'name':row['name']})
  85. return role_list
  86. #def add_role( username,role_id):
  87. #db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  88. #user_role_table = db['user_role']
  89. #user_role_table.insert({'user_id':,'role_id':role_id})
  90. def get_user_id(token):
  91. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  92. credentials_exception = HTTPException(
  93. status_code=status.HTTP_401_UNAUTHORIZED,
  94. detail="Could not validate credentials",
  95. headers={"WWW-Authenticate": "Bearer"},
  96. )
  97. try:
  98. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  99. username: str = payload.get("sub")
  100. if username is None:
  101. raise credentials_exception
  102. token_data = util.models.TokenData(username=username)
  103. except JWTError:
  104. raise credentials_exception
  105. user = get_user(username=token_data.username)
  106. if user is None:
  107. raise credentials_exception
  108. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  109. return user_id
  110. def get_id_by_email(email):
  111. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  112. user_dict = next(iter(db.query('SELECT * FROM users where email ="'+email+'"')))
  113. return user_dict['id']
  114. def email_veri_pass(name):
  115. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  116. user_dict = next(iter(db.query('SELECT * FROM users where username ="'+name+'"')))
  117. user_obj = first(db.query('SELECT * FROM register_veri_code where user_id ="'+str(user_dict['id'])+'"'))
  118. if user_obj == None:
  119. return True
  120. else:
  121. return False