| Total Complexity | 8 |
| Total Lines | 38 |
| Duplicated Lines | 0 % |
| Changes | 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, |
||
| 13 | user_role=UserRole.User): |
||
| 14 | certificate = await uacrypto.load_certificate(certificate_path, format) |
||
| 15 | if label is None: |
||
| 16 | label = certificate_path |
||
| 17 | user = User(role=user_role, name=label) |
||
| 18 | if label in self._trusted_certificates: |
||
| 19 | logging.warning(f"certificate with label {label} " |
||
| 20 | f"attempted to be added multiple times, only the last version will be kept.") |
||
| 21 | self._trusted_certificates[label] = {'certificate': uacrypto.der_from_x509(certificate), 'user':user} |
||
| 22 | |||
| 23 | def __contains__(self, certificate): |
||
| 24 | return any(certificate == prospective_cert['certificate'] |
||
| 25 | for prospective_cert |
||
| 26 | in self._trusted_certificates.values()) |
||
| 27 | |||
| 28 | def check_certificate(self, certificate): |
||
| 29 | return certificate in self |
||
| 30 | |||
| 31 | def get_user(self, certificate): |
||
| 32 | correct_users = [prospective_certificate['user'] for prospective_certificate in self._trusted_certificates.values() |
||
| 33 | if certificate == prospective_certificate['certificate']] |
||
| 34 | if len(correct_users) == 0: |
||
| 35 | return None |
||
| 36 | else: |
||
| 37 | return correct_users[0] |
||
| 38 |