]>
Commit | Line | Data |
---|---|---|
8c4f590c MR |
1 | # -*- coding: utf-8 -*- |
2 | ||
3 | # Copyright (c) 2018 Michael Rasmussen <mir@datanom.net> | |
4 | ||
5 | # This file is part of SecureMail. | |
6 | ||
7 | # SecureMail is free software: you can redistribute it and/or modify | |
8 | # it under the terms of the GNU General Public License as published by | |
9 | # the Free Software Foundation, either version 3 of the License, or | |
10 | # (at your option) any later version. | |
11 | # | |
12 | # SecureMail is distributed in the hope that it will be useful, | |
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | # GNU General Public License for more details. | |
16 | # | |
17 | # You should have received a copy of the GNU General Public License | |
18 | # along with SecureMail. If not, see <https://www.gnu.org/licenses/>. | |
19 | ||
20 | from config import DBTYPE, DBHOST, DBPORT, DBUID, DBPWD, DBNAME | |
21 | ||
22 | class Singleton: | |
23 | def __init__(self, klass): | |
24 | self.klass = klass | |
25 | self.instance = None | |
26 | ||
27 | def __call__(self, *args, **kwargs): | |
28 | if self.instance == None: | |
29 | self.instance = self.klass(*args, **kwargs) | |
30 | return self.instance | |
31 | ||
32 | @Singleton | |
33 | class DB: | |
34 | conn = None | |
35 | ||
36 | def get_connection(self): | |
37 | if self.conn is None: | |
38 | if DBTYPE == 'mysql': | |
39 | import mysql.connector | |
40 | self.conn = mysql.connector.connect(host=DBHOST, port=DBPORT, user=DBUID, password=DBPWD, database=DBNAME) | |
41 | elif DBTYPE == 'postgresql': | |
42 | import psycopg2 | |
43 | self.conn = psycopg2.connect(host=DBHOST, port=DBPORT, user=DBUID, password=DBPWD, dbname=DBNAME) | |
44 | return self.conn | |
45 | ||
46 | def __del__(self): | |
47 | if self.conn is not None: | |
48 | self.conn.close() | |
49 | ||
50 | class DBInterface: | |
51 | @staticmethod | |
52 | def load_user(key): | |
53 | conn = DB().get_connection() | |
54 | cursor = conn.cursor() | |
55 | cursor.execute("select a.cipher from account a where id = '{0}'".format(key)) | |
56 | row = cursor.fetchone() | |
57 | if row is None: | |
58 | obj = None | |
59 | else: | |
60 | obj = row[0].tobytes() | |
61 | cursor.close() | |
62 | ||
63 | return obj | |
64 | ||
65 | @staticmethod | |
66 | def store_user(key, cipher): | |
67 | conn = DB().get_connection() | |
68 | cursor = conn.cursor() | |
69 | cursor.execute("insert into account(id, cipher) values(%s, %s)", (key, cipher)) | |
70 | conn.commit() | |
71 | cursor.close() |