users.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import time
  2. import uuid
  3. from typing import List
  4. from app import models, schemas
  5. from sqlalchemy.orm import Session
  6. from werkzeug.security import check_password_hash, generate_password_hash
  7. from configs.globals import g
  8. from itsdangerous import BadSignature, SignatureExpired
  9. from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
  10. from app.utils.utils import decode_base64
  11. from constants.constants import SECRET_KEY
  12. def verify_password(password_hash, password):
  13. return check_password_hash(password_hash, password)
  14. # 生成新的user_token
  15. def generate_user_token(user: models.Users, expiration=3600 * 5):
  16. s = Serializer(SECRET_KEY, expires_in=expiration)
  17. return s.dumps({'user_id': user.id,'password':user.password}).decode('utf-8')
  18. # 验证Token方法
  19. def verify_user_token(db: Session, token: str):
  20. s = Serializer(SECRET_KEY)
  21. try:
  22. data = s.loads(token)
  23. except SignatureExpired:
  24. raise Exception("user_token验证失败")
  25. except BadSignature:
  26. raise Exception("user_token验证失败")
  27. user: models.Users = db.query(models.Users).filter(models.Users.id == data['user_id']).first()
  28. if not user:
  29. raise Exception("不存在此用户")
  30. if not user.password == data['password']:
  31. raise Exception("密码已被修改,请重新登陆")
  32. return user
  33. def create_users(db: Session, item: schemas.UsersCreate):
  34. check_1 = db.query(models.Users).filter(models.Users.name == item.name).first()
  35. if check_1:
  36. raise Exception('该用户已存在')
  37. check_2 = db.query(models.Users).filter(models.Users.username == item.username).first()
  38. if check_2:
  39. raise Exception('该账号已存在')
  40. item.password = decode_base64(item.password)
  41. user_code = str(uuid.uuid1()).replace('-','')
  42. db_item = models.Users(**{
  43. 'name': item.name,
  44. 'code': user_code,
  45. 'username': item.username,
  46. 'password': generate_password_hash(bytes(item.password.encode('utf-8'))),
  47. 'create_time': int(time.time()),
  48. })
  49. db.add(db_item)
  50. db.commit()
  51. db.refresh(db_item)
  52. return db_item
  53. def login(db: Session, item: schemas.LoginBase):
  54. user: models.Users = db.query(models.Users).filter(models.Users.username == item.username).first()
  55. if not user:
  56. raise Exception('不存在此账号')
  57. item.password = decode_base64(item.password)
  58. if not verify_password(user.password,item.password):
  59. raise Exception('密码错误')
  60. auth_token = generate_user_token(user)
  61. user.user_token = auth_token
  62. db.commit()
  63. db.flush()
  64. db.refresh(user)
  65. res = user.to_dict()
  66. res.update({'auth_token':auth_token})
  67. return res
  68. def get_users_by_project(db: Session, project_id: int):
  69. relation: List[models.ProjectUserRelation] = db.query(models.ProjectUserRelation)\
  70. .filter(models.ProjectUserRelation.project_id == project_id).all()
  71. user_role = { r.user_id:r.role_id for r in relation}
  72. user_ids = list(user_role.keys())
  73. roles: List[models.Roles] = db.query(models.Roles).all()
  74. id_role = { r.id:r for r in roles}
  75. users: List[models.Users] = db.query(models.Users)\
  76. .filter(models.Users.id.in_(user_ids)).all()
  77. res = []
  78. for user in users:
  79. if user.id == 1: continue
  80. item = user.to_dict()
  81. item.update({'role_name':id_role[user_role[user.id]].name})
  82. res.append(item)
  83. return res
  84. def retrieve_users_by_project(db: Session, project_id: int):
  85. relation: List[models.ProjectUserRelation] = db.query(models.ProjectUserRelation)\
  86. .filter(models.ProjectUserRelation.project_id == project_id).all()
  87. now_user_ids = [ r.user_id for r in relation ]
  88. users: List[models.Users] = db.query(models.Users)\
  89. .filter(models.Users.id.notin_(now_user_ids)).all()
  90. return users
  91. def add_users_to_project(db: Session, user_ids: List[int], project_id: int):
  92. project: models.Project = db.query(models.Project).filter(models.Project.id == project_id).first()
  93. if not project:
  94. raise Exception('项目不存在')
  95. exist_users = []
  96. for user_id in user_ids:
  97. check_user = db.query(models.Users).filter(models.Users.id == user_id).first()
  98. if not check_user:
  99. raise Exception('用户不存在')
  100. realtion = db.query(models.ProjectUserRelation)\
  101. .filter(models.ProjectUserRelation.project_id == project_id)\
  102. .filter(models.ProjectUserRelation.user_id == user_id).first()
  103. if realtion:
  104. raise Exception('用户已加入项目,不可二次加入')
  105. exist_users.append(user_id)
  106. for user_id in exist_users:
  107. db_item = models.ProjectUserRelation(**{
  108. 'user_id': user_id,
  109. 'project_id': project_id,
  110. 'role_id': 3 if project.type == 0 else 5
  111. })
  112. db.add(db_item)
  113. db.commit()
  114. db.refresh(db_item)
  115. def remove_project_users(db: Session, user_id: int, project_id: int):
  116. project: models.Project = db.query(models.Project).filter(models.Project.id == project_id).first()
  117. if not project:
  118. raise Exception('项目不存在')
  119. check_user = db.query(models.Users).filter(models.Users.id == user_id).first()
  120. if not check_user:
  121. raise Exception('用户不存在')
  122. realtion: models.ProjectUserRelation = db.query(models.ProjectUserRelation)\
  123. .filter(models.ProjectUserRelation.project_id == project_id)\
  124. .filter(models.ProjectUserRelation.user_id == user_id).first()
  125. if not realtion:
  126. raise Exception('用户未加入此项目,不可移除')
  127. if realtion.user_id == g.user_id:
  128. raise Exception('用户不能移除自己')
  129. if realtion.role_id in [2,4]:
  130. raise Exception('该用户为项目管理员,不可直接移除')
  131. db.query(models.ProjectUserRelation)\
  132. .filter(models.ProjectUserRelation.project_id == project_id)\
  133. .filter(models.ProjectUserRelation.user_id == user_id).delete()
  134. db.commit()
  135. db.flush()
  136. def set_user_to_admin(db: Session,user_id: int,project_id: int):
  137. project: models.Project = db.query(models.Project).filter(models.Project.id == project_id).first()
  138. if not project:
  139. raise Exception('项目不存在')
  140. check_user = db.query(models.Users).filter(models.Users.id == user_id).first()
  141. if not check_user:
  142. raise Exception('用户不存在')
  143. realtion: models.ProjectUserRelation = db.query(models.ProjectUserRelation)\
  144. .filter(models.ProjectUserRelation.project_id == project_id)\
  145. .filter(models.ProjectUserRelation.user_id == user_id).first()
  146. if not realtion:
  147. raise Exception('用户未加入项目,不可设为管理员')
  148. admin_role_id = 2 if project.type == 0 else 4
  149. admin_realtion: models.ProjectUserRelation = db.query(models.ProjectUserRelation)\
  150. .filter(models.ProjectUserRelation.project_id == project_id)\
  151. .filter(models.ProjectUserRelation.role_id == admin_role_id).first()
  152. if admin_realtion:
  153. raise Exception('项目已存在管理员,请先移除原先管理员在设置新的管理员')
  154. realtion.role_id = admin_role_id
  155. db.commit()
  156. db.flush()
  157. db.refresh(realtion)
  158. return realtion
  159. def remove_user_to_admin(db: Session,user_id: int,project_id: int):
  160. project: models.Project = db.query(models.Project).filter(models.Project.id == project_id).first()
  161. if not project:
  162. raise Exception('项目不存在')
  163. check_user = db.query(models.Users).filter(models.Users.id == user_id).first()
  164. if not check_user:
  165. raise Exception('用户不存在')
  166. realtion: models.ProjectUserRelation = db.query(models.ProjectUserRelation)\
  167. .filter(models.ProjectUserRelation.project_id == project_id)\
  168. .filter(models.ProjectUserRelation.user_id == user_id).first()
  169. if not realtion:
  170. raise Exception('用户未加入项目')
  171. admin_role_id = 3 if project.type == 0 else 5
  172. realtion.role_id = admin_role_id
  173. db.commit()
  174. db.flush()
  175. db.refresh(realtion)
  176. return realtion