Projekt

Obecné

Profil

« Předchozí | Další » 

Revize f8b23532

Přidáno uživatelem David Friesecký před asi 4 roky(ů)

Re #8471 - Simplification of CRUD functions
- conversion source of certificate repository to one file
- added comments

Zobrazit rozdíly:

src/dao/certificate_repository.py
1
from typing import List, Dict
1
from typing import Dict
2
from sqlite3 import Connection, Cursor, Error
2 3

  
3
from ..db_objects.certificate import Certificate
4
from ..dao.repository import IRepository
5
from db_manager import DBManager
6
from ..constants import *
4
from src.db_objects.certificate import Certificate
5
from src.constants import *
7 6

  
8 7

  
9
class CertificateRepositoryImpl(IRepository):
8
class CertificateRepository:
10 9

  
11
    def create(self, common_name: str, valid_from: str, valid_to: str, pem_data: str,
12
               private_key_id: int, type_id: int, parent_id: int, usages: Dict[int, bool]) -> bool:
10
    def __init__(self, connection: Connection, cursor: Cursor):
13 11
        """
14
        Creates a certificate
15

  
16
        :param common_name: private key of the certificate
17
        :param valid_from: string of date (time) of validation after (from)
18
        :param valid_to: string of date (time) of validation before (to)
19
        :param pem_data: data of certificate in a PEM format
20
        :param private_key_id: ID from PrivateKeys table for specific private key
21
        :param type_id: ID from CertificateTypes table (ROOT_CA_ID=1, INTERMEDIATE_CA_ID=2, CERTIFICATE_ID=3)
22
        :param parent_id: ID from Certificates table for specific parent certificate
23
            for root CA use e.g. -1 (ID will be changed after created certificate)
24
        :param usages: dictionary of usages IDs which certificate use
25
            Dictionary[Integer, Boolean]
26
                - Key = ID (CA_ID=1, SSL_ID=2, SIGNATURE_ID=3, AUTHENTICATION_ID=4)
27
                - Value = used=True/unused=False
12
        Constructor of the CertificateRepository object
28 13

  
29
        :return: the result of whether the creation was successful
14
        :param connection: Instance of the Connection object
15
        :param cursor: Instance of the Cursor object
30 16
        """
31 17

  
32
        sql = (f"INSERT INTO {TAB_CERTIFICATES} ({COL_COMMON_NAME},{COL_VALID_FROM},{COL_VALID_TO},{COL_PEM_DATA},"
33
               f"{COL_PRIVATE_KEY_ID},{COL_TYPE_ID},{COL_PARENT_ID})"
34
               f"VALUES(?,?,?,?,?,?,?)")
35
        result = DBManager.create(sql, [common_name, valid_from, valid_to, pem_data,
36
                                        private_key_id, type_id, parent_id], usages)
37
        return result
18
        self.connection = connection
19
        self.cursor = cursor
38 20

  
39
    def read(self, certificate_id: int = None):
21
    def create(self, certificate: Certificate) -> bool:
40 22
        """
41
        Reads (selects) a certificate or certificates
23
        Creates a certificate.
24
        For root certificate (CA) the parent certificate id is modified to the same id (id == parent_id).
42 25

  
43
        :param certificate_id: ID of specific certificate
26
        :param certificate: Instance of the Certificate object
44 27

  
45
        :return: instance of Certificate class if ID was used otherwise list of this instances
28
        :return: the result of whether the creation was successful
46 29
        """
47 30

  
48
        sql_extend = ""
31
        try:
32
            sql = (f"INSERT INTO {TAB_CERTIFICATES} "
33
                   f"({COL_COMMON_NAME},"
34
                   f"{COL_VALID_FROM},"
35
                   f"{COL_VALID_TO},"
36
                   f"{COL_PEM_DATA},"
37
                   f"{COL_PRIVATE_KEY_ID},"
38
                   f"{COL_TYPE_ID},"
39
                   f"{COL_PARENT_ID})"
40
                   f"VALUES(?,?,?,?,?,?,?)")
41
            values = [certificate.common_name,
42
                      certificate.valid_from,
43
                      certificate.valid_to,
44
                      certificate.pem_data,
45
                      certificate.private_key_id,
46
                      certificate.type_id,
47
                      certificate.parent_id]
48
            self.cursor.execute(sql, values)
49
            self.connection.commit()
50

  
51
            last_id: int = self.cursor.lastrowid
52

  
53
            if certificate.usages[ROOT_CA_ID - 1]:
54
                certificate.parent_id = last_id
55
                return self.update(last_id, certificate)
56
            else:
57
                for usage_id, usage_value in certificate.usages:
58
                    if usage_value:
59
                        sql = (f"INSERT INTO {TAB_CERTIFICATE_USAGES} "
60
                               f"({COL_CERTIFICATE_ID},"
61
                               f"{COL_USAGE_TYPE_ID}) "
62
                               f"VALUES (?,?)")
63
                        values = [last_id, usage_id]
64
                        self.cursor.execute(sql, values)
65
                        self.connection.commit()
66
        except Error as e:
67
            print(e)
68
            return False
69

  
70
        return True
71

  
72
    def read(self, certificate_id: int) -> Certificate:
73
        """
74
        Reads (selects) a certificate.
49 75

  
50
        if certificate_id is not None:
51
            sql_extend = f" WHERE {COL_ID} = ?"
76
        :param certificate_id: ID of specific certificate
52 77

  
53
        sql = f"SELECT * FROM {TAB_CERTIFICATES}{sql_extend}"
54
        certificate_rows = DBManager.read(sql, certificate_id)
78
        :return: instance of the Certificate object
79
        """
55 80

  
56
        certificates: list = []
81
        try:
82
            sql = (f"SELECT * FROM {TAB_CERTIFICATES} "
83
                   f"WHERE {COL_ID} = ?")
84
            values = [certificate_id]
85
            self.cursor.execute(sql, values)
86
            certificate_row = self.cursor.fetchall()
57 87

  
58
        for certificate_row in certificate_rows:
59
            sql = f"SELECT * FROM {TAB_CERTIFICATE_USAGES} WHERE {COL_CERTIFICATE_ID} = ?"
60
            usage_rows = DBManager.read(sql, certificate_row[0])
88
            sql = (f"SELECT * FROM {TAB_CERTIFICATE_USAGES} "
89
                   f"WHERE {COL_CERTIFICATE_ID} = ?")
90
            self.cursor.execute(sql, values)
91
            usage_rows = self.cursor.fetchall()
61 92

  
62 93
            usage_dict: Dict[int, bool] = {}
63 94
            for usage_row in usage_rows:
64
                usage_dict[usage_row[1]] = True
65

  
66
            certificates.append(Certificate(certificate_row[0],
67
                                            certificate_row[1],
68
                                            certificate_row[2],
69
                                            certificate_row[3],
70
                                            certificate_row[4],
71
                                            certificate_row[5],
72
                                            certificate_row[6],
73
                                            certificate_row[7],
74
                                            usage_dict))
75

  
76
        if certificate_id is not None:
77
            return certificates[0]
78

  
79
        return certificates
80

  
81
    def update(self, certificate_id: int, common_name: str = None, valid_from: str = None, valid_to: str = None,
82
               pem_data: str = None, private_key_id: int = None, type_id: int = None, parent_id: int = None,
83
               usages: Dict[int, bool] = None) -> bool:
95
                usage_dict[usage_row[2]] = True
96

  
97
            certificate: Certificate = Certificate(certificate_row[0],
98
                                                   certificate_row[1],
99
                                                   certificate_row[2],
100
                                                   certificate_row[3],
101
                                                   certificate_row[4],
102
                                                   certificate_row[5],
103
                                                   certificate_row[6],
104
                                                   certificate_row[7],
105
                                                   usage_dict)
106
        except Error as e:
107
            print(e)
108
            return None
109

  
110
        return certificate
111

  
112
    def update(self, certificate_id: int, certificate: Certificate) -> bool:
84 113
        """
85
        Updates a certificate
114
        Updates a certificate.
115
        If the parameter of certificate (Certificate object) is not to be changed,
116
        the same value must be specified.
86 117

  
87 118
        :param certificate_id: ID of specific certificate
88
        :param common_name: private key of the certificate
89
        :param valid_from: string of date (time) of validation after (from)
90
        :param valid_to: string of date (time) of validation before (to)
91
        :param pem_data: data of certificate in a PEM format
92
        :param private_key_id: ID from PrivateKeys table for specific private key
93
        :param type_id: ID from CertificateTypes table (ROOT_CA_ID=1, INTERMEDIATE_CA_ID=2, CERTIFICATE_ID=3)
94
        :param parent_id: ID from Certificates table for specific parent certificate
95
            for root CA use e.g. -1 (ID will be changed after created certificate)
96
        :param usages: dictionary of usages IDs which certificate use
97
            Dictionary[Integer, Boolean]
98
                - Key = ID (CA_ID=1, SSL_ID=2, SIGNATURE_ID=3, AUTHENTICATION_ID=4)
99
                - Value = used=True/unused=False
119
        :param certificate: Instance of the Certificate object
100 120

  
101 121
        :return: the result of whether the updation was successful
102 122
        """
103 123

  
104
        updated_list = []
105
        values = []
106
        if common_name is not None:
107
            updated_list.append(f"{COL_COMMON_NAME} = ?")
108
            values.append(common_name)
109
        if valid_from is not None:
110
            updated_list.append(f"{COL_VALID_FROM} = ?")
111
            values.append(valid_from)
112
        if valid_to is not None:
113
            updated_list.append(f"{COL_VALID_TO} = ?")
114
            values.append(valid_to)
115
        if pem_data is not None:
116
            updated_list.append(f"{COL_PEM_DATA} = ?")
117
            values.append(pem_data)
118
        if private_key_id is not None:
119
            updated_list.append(f"{COL_PRIVATE_KEY_ID} = ?")
120
            values.append(private_key_id)
121
        if type_id is not None:
122
            updated_list.append(f"{COL_TYPE_ID} = ?")
123
            values.append(type_id)
124
        if parent_id is not None:
125
            updated_list.append(f"{COL_PARENT_ID} = ?")
126
            values.append(parent_id)
127

  
128
        updated_str = ", ".join(updated_list)
129
        sql = f"UPDATE {TAB_CERTIFICATES} SET {updated_str} WHERE {COL_ID} = ?"
130
        result = DBManager.update(sql, certificate_id, values, usages)
131
        return result
124
        try:
125
            sql = (f"UPDATE {TAB_CERTIFICATES} "
126
                   f"SET {COL_COMMON_NAME} = ?, "
127
                   f"{COL_VALID_FROM} = ?, "
128
                   f"{COL_VALID_TO} = ?, "
129
                   f"{COL_PEM_DATA} = ?, "
130
                   f"{COL_PRIVATE_KEY_ID} = ?, "
131
                   f"{COL_TYPE_ID} = ?, "
132
                   f"{COL_PARENT_ID} = ? "
133
                   f"WHERE {COL_ID} = ?")
134
            values = [certificate.common_name,
135
                      certificate.valid_from,
136
                      certificate.valid_to,
137
                      certificate.pem_data,
138
                      certificate.private_key_id,
139
                      certificate.type_id,
140
                      certificate.parent_id]
141
            self.cursor.execute(sql, values)
142
            self.connection.commit()
143

  
144
            sql = (f"DELETE FROM {TAB_CERTIFICATE_USAGES} "
145
                   f"WHERE {COL_CERTIFICATE_ID} = ?")
146
            values = [certificate_id]
147
            self.cursor.execute(sql, values)
148
            self.connection.commit()
149

  
150
            for usage_id, usage_value in certificate.usages:
151
                if usage_value:
152
                    sql = (f"INSERT INTO {TAB_CERTIFICATE_USAGES} "
153
                           f"({COL_CERTIFICATE_ID},"
154
                           f"{COL_USAGE_TYPE_ID}) "
155
                           f"VALUES (?,?)")
156
                    values = [certificate_id, usage_id]
157
                    self.cursor.execute(sql, values)
158
                    self.connection.commit()
159
        except Error as e:
160
            print(e)
161
            return False
162

  
163
        return True
132 164

  
133 165
    def delete(self, certificate_id: int) -> bool:
134 166
        """
......
139 171
        :return: the result of whether the deletion was successful
140 172
        """
141 173

  
142
        sql = f"DELETE FROM {TAB_CERTIFICATES} WHERE {COL_ID} = ?"
143
        result = DBManager.delete(sql, certificate_id, True)
144
        return result
174
        try:
175
            sql = (f"DELETE FROM {TAB_CERTIFICATES} "
176
                   f"WHERE {COL_ID} = ?")
177
            values = [certificate_id]
178
            self.cursor.execute(sql, values)
179
            self.connection.commit()
180
        except Error as e:
181
            print(e)
182
            return False
183

  
184
        return True

Také k dispozici: Unified diff