Geen omschrijving

authlib.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import hashlib, time
  2. from connect import connection, engine, metadata
  3. import sqlalchemy as db
  4. def hash_pass(password):
  5. return hashlib.sha256(password.encode()).hexdigest()
  6. class Auth:
  7. def __init__(self, session, expire=0):
  8. self.session = session
  9. self.expire=expire
  10. def checkAuth(self):
  11. if self.expire and time.time() - self.session["tiempo"] > self.expire:
  12. self.delAuth()
  13. else:
  14. self.session["tiempo"] = time.time()
  15. return self.session.get("gallitosccom")
  16. def setAuth(self, id, email):
  17. self.session["gallitosccom"] = True
  18. self.session["id"] = id
  19. self.session["email"] = email
  20. if self.expire:
  21. self.session["tiempo"] = time.time()
  22. def delAuth(self):
  23. if self.session.get("gallitosccom"):
  24. self.session.pop("gallitosccom", None)
  25. self.session.pop("id", None)
  26. self.session.pop("email", None)
  27. def do_login(self, username, password):
  28. password = hash_pass(password)
  29. usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
  30. query = db.select([usuarios])
  31. if username.find("@") > 1:
  32. print("email")
  33. query = query.select_from(usuarios).where(usuarios.columns.email == username)
  34. else:
  35. print("username")
  36. query = query.select_from(usuarios).where(usuarios.columns.username == username)
  37. result = connection.execute(query).fetchone()
  38. if result and password == result["password"]:
  39. print(result)
  40. self.setAuth(result["id"], result["email"])
  41. # Añadir feature de last login.
  42. return True
  43. return False
  44. def checkRole(self, tipo):
  45. tables = {"admin": "administracion", "madre": "madres", "enfermera":"enfermeras", "facultad": "facultad", "estudiante": "estudiantes"}
  46. if tipo in tables:
  47. table = tables[tipo]
  48. else:
  49. return False
  50. usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
  51. role = db.Table(table, metadata, autoload=True, autoload_with=engine)
  52. query = db.select([usuarios, role])
  53. query = query.select_from(usuarios.join(role, usuarios.columns.id == role.columns.user_id)).where(role.columns.user_id == self.session["id"])
  54. result = connection.execute(query).fetchone()
  55. if result:
  56. return True
  57. return False
  58. def do_logout(self):
  59. self.delAuth()