123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
-
- 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.session["fc"] = 0
- 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.
- self.session["fc"] = 0
- return True
-
- #introduce an authentication fail delay
- time.sleep(self.session["fc"] * 2)
- self.session["fc"] += 1
- 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()
|