summaryrefslogtreecommitdiff
path: root/src/jwebmail/read_mails.py
blob: 915567cf78ee24548c9b83ec979d7f9c9ffcd650 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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.getex(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