12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
-
- import hashlib, time, json
- from cryptography.fernet import Fernet
- from connect import connection, engine, metadata
- import sqlalchemy as db
-
- def hash_pass(password):
- return hashlib.sha256(password.encode()).hexdigest()
-
- class Auth:
- def __init__(self, session, expire=0):
- self.session = session
- self.id = None
- self.email = None
- self.fernet = Fernet(b'3UH3USxvBcFITpnVa2gvTUIMO5jbc8jqU_Q1O6SNBLs=')
-
- if session.get("id"):
- value = json.loads(self.fernet.decrypt(session["id"]))
- self.id = value["id"]
- self.email = value["email"]
- # Remember to always change
- self.expire=expire
-
- def checkAuth(self):
- if self.expire and time.time() - self.session["tiempo"] > self.expire:
- self.delAuth()
- else:
- self.session["tiempo"] = time.time()
-
- return self.session.get("gallitosccom")
-
- def setAuth(self, id, email):
- self.session["gallitosccom"] = True
- self.id = id
- self.email = email
- self.session["id"] = self.fernet.encrypt(json.dumps({"id": id, "email": email}).encode())
- if self.expire:
- self.session["tiempo"] = time.time()
-
- def delAuth(self):
- if self.session.get("gallitosccom"):
- self.session.pop("gallitosccom", None)
- self.session.pop("id", None)
- # self.session.pop("email", None)
-
- def do_login(self, username, password):
- password = hash_pass(password)
- usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
- query = db.select([usuarios])
- if username.find("@") > 1:
- print("email")
- query = query.select_from(usuarios).where(usuarios.columns.email == username)
- else:
- print("username")
- query = query.select_from(usuarios).where(usuarios.columns.username == username)
-
- result = connection.execute(query).fetchone()
- if result and password == result["password"]:
- print(result)
- self.setAuth(result["id"], result["email"])
- # Añadir feature de last login.
- return True
-
- return False
-
- def checkRole(self, tipo):
- tables = {"admin": "administracion", "madre": "madres", "enfermera":"enfermeras", "facultad": "facultad", "estudiante": "estudiantes"}
- if tipo in tables:
- table = tables[tipo]
- else:
- return False
-
- usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
- role = db.Table(table, metadata, autoload=True, autoload_with=engine)
- query = db.select([usuarios, role])
- query = query.select_from(usuarios.join(role, usuarios.columns.id == role.columns.user_id)).where(role.columns.user_id == self.id)
- result = connection.execute(query).fetchone()
-
- if result:
- return True
-
- return False
-
- def do_logout(self):
- self.delAuth()
|