Passed
Pull Request — master (#209)
by
unknown
02:10
created

CertificateHandler.get_user()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
from asyncua.crypto import uacrypto
2
import sys
3
import logging
4
from asyncua.server.users import UserRole, User
5
sys.path.append('..')
6
7
8
class CertificateHandler:
9
    def __init__(self):
10
        self._trusted_certificates = {}
11
12
    async def trust_certificate(self, certificate_path: str, format: str = None, label: str = None, user_role=UserRole.User):
13
        certificate = await uacrypto.load_certificate(certificate_path, format)
14
        if label is None:
15
            label = certificate_path
16
        user = User(role=user_role, name=label)
17
        if label in self._trusted_certificates:
18
            logging.warning(f"certificate with label {label} "
19
                            f"attempted to be added multiple times, only the last version will be kept.")
20
        self._trusted_certificates[label] = {'certificate': uacrypto.der_from_x509(certificate), 'user':user}
21
22
    def __contains__(self, certificate):
23
        return any(certificate == prospective_cert['certificate']
24
                   for prospective_cert
25
                   in self._trusted_certificates.values())
26
27
    def get_user(self, certificate):
28
        correct_users = [prospective_certificate['user'] for prospective_certificate in self._trusted_certificates.values()
29
                         if certificate == prospective_certificate['certificate']]
30
        if len(correct_users) == 0:
31
            return None
32
        else:
33
            return correct_users[0]
34