import redis from flask import current_app, g from flask_login import UserMixin, current_user from .model.read_mails import QMailAuthuser EXPIRATION_SEC = 60 * 60 * 25 class JWebmailUser(UserMixin): def __init__(self, mail_addr, password): self.id = mail_addr self.password = password def build_qma(username, password): authenticator = current_app.config["JWEBMAIL"]["READ_MAILS"]["AUTHENTICATOR"] backend = current_app.config["JWEBMAIL"]["READ_MAILS"]["BACKEND"] mailbox = current_app.config["JWEBMAIL"]["READ_MAILS"]["MAILBOX"] mailbox_user = current_app.config["JWEBMAIL"]["READ_MAILS"]["MAILBOX_USER"] return QMailAuthuser( username, password, backend, mailbox, mailbox_user, authenticator ) def login(username, password): return build_qma(username, password).verify_user() def add_user(user: JWebmailUser): passwd = current_app.config["JWEBMAIL"]["READ_MAILS"]["SESSION_STORE_PASSWD"] r = redis.Redis( host="localhost", port=6379, decode_responses=True, protocol=3, username="jwebmail", password=passwd, ) r.setex(f"jwm:user:{user.get_id()}", EXPIRATION_SEC, user.password) def load_user(username: str) -> JWebmailUser: passwd = current_app.config["JWEBMAIL"]["READ_MAILS"]["SESSION_STORE_PASSWD"] r = redis.Redis( host="localhost", port=6379, decode_responses=True, protocol=3, username="jwebmail", password=passwd, ) passwd = r.get(f"jwm:user:{username}") # EXPIRATION_SEC if passwd is None: return None return JWebmailUser(username, passwd) def get_read_mails_logged_in(): if "read_mails" in g: return g.read_mails passwd = current_app.config["JWEBMAIL"]["READ_MAILS"]["SESSION_STORE_PASSWD"] r = redis.Redis( host="localhost", port=6379, decode_responses=True, protocol=3, username="jwebmail", password=passwd, ) passwd = r.get(f"jwm:user:{current_user.get_id()}") if passwd is None: raise KeyError(current_user.get_id()) qma = build_qma(current_user.get_id(), passwd) g.read_mails = qma return qma