import hashlib, time 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.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.session["id"] = id self.session["email"] = email 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.session["id"]) result = connection.execute(query).fetchone() if result: return True return False def do_logout(self): self.delAuth()