Projekt

Obecné

Profil

Stáhnout (6.03 KB) Statistiky
| Větev: | Tag: | Revize:
1
import os
2

    
3
from flask import Flask, redirect, request
4
from flask_injector import FlaskInjector
5
from injector import Injector
6
from werkzeug.exceptions import HTTPException
7

    
8
from src.config import configuration
9
from src.config.configuration import Configuration
10
from src.config.connection_provider import ConnectionProvider
11
from src.controllers.certificates_controller import CertController
12
from src.controllers.crl_ocsp_controller import CrlOcspController
13
from src.controllers.exception_handlers import handle_cryptography_exception, handle_database_exception, \
14
    handle_generic_exception
15
from src.exceptions.database_exception import DatabaseException
16
from src.services.cryptography import CryptographyService, CryptographyException
17
from src.utils import logger
18
from src.utils.logger import Logger
19

    
20
app = Flask(__name__)
21

    
22

    
23
@app.route('/')
24
def index():
25
    return redirect("/static/index.html")
26

    
27

    
28
@app.route('/api/certificates', methods=["POST"])
29
def create_certificate(certificate_controller: CertController):
30
    return certificate_controller.create_certificate()
31

    
32

    
33
@app.route('/api/certificates', methods=["GET"])
34
def get_cert_list(certificate_controller: CertController):
35
    return certificate_controller.get_certificate_list()
36

    
37

    
38
@app.route('/api/certificates/<id>', methods=["GET"])
39
def get_cert(id, certificate_controller: CertController):
40
    return certificate_controller.get_certificate_by_id(id)
41

    
42

    
43
@app.route('/api/certificates/<id>', methods=["PATCH"])
44
def set_certificate_status(id, certificate_controller: CertController):
45
    return certificate_controller.set_certificate_status(id)
46

    
47

    
48
@app.route('/api/certificates/<id>', methods=["DELETE"])
49
def delete_certificate(id, certificate_controller: CertController):
50
    return certificate_controller.delete_certificate(id)
51

    
52

    
53
@app.route('/api/certificates/<id>/details', methods=["GET"])
54
def get_cert_details(id, certificate_controller: CertController):
55
    return certificate_controller.get_certificate_details_by_id(id)
56

    
57

    
58
@app.route('/api/certificates/<id>/root', methods=["GET"])
59
def get_cert_root(id, certificate_controller: CertController):
60
    return certificate_controller.get_certificate_root_by_id(id)
61

    
62

    
63
@app.route('/api/certificates/<id>/chain', methods=["GET"])
64
def get_cert_chain(id, certificate_controller: CertController):
65
    return certificate_controller.get_certificate_trust_chain_by_id(id)
66

    
67

    
68
@app.route('/api/certificates/<id>/privatekey', methods=["GET"])
69
def get_private_key_of_a_certificate(id, certificate_controller: CertController):
70
    return certificate_controller.get_private_key_of_a_certificate(id)
71

    
72

    
73
@app.route('/api/certificates/<id>/publickey', methods=["GET"])
74
def get_public_key_of_a_certificate(id, certificate_controller: CertController):
75
    return certificate_controller.get_public_key_of_a_certificate(id)
76

    
77

    
78
@app.route('/api/crl/<id>', methods=["GET"])
79
def get_crl_of_issuer(id, crl_ocsp_controller: CrlOcspController):
80
    return crl_ocsp_controller.get_crl(id)
81

    
82

    
83
@app.route('/api/ocsp/<id>/<path:ocsp_request>', methods=["GET"])
84
def get_ocsp_of_issuer_get(id, ocsp_request, crl_ocsp_controller: CrlOcspController):
85
    return crl_ocsp_controller.get_ocsp_from_base64(id, ocsp_request)
86

    
87

    
88
@app.route('/api/ocsp/<id>', methods=["POST"])
89
def get_ocsp_of_issuer_post(id, crl_ocsp_controller: CrlOcspController):
90
    return crl_ocsp_controller.get_ocsp_from_der(id, request.data)
91

    
92

    
93
@app.route('/api/certificates/<id>/identity', methods=["POST"])
94
def generate_certificate_pkcs_identity(id, certificate_controller: CertController):
95
    return certificate_controller.generate_certificate_pkcs_identity(id)
96

    
97

    
98
@app.errorhandler(CryptographyException)
99
def cryptography_error(e):
100
    return handle_cryptography_exception(e)
101

    
102

    
103
@app.errorhandler(DatabaseException)
104
def database_error(e):
105
    return handle_database_exception(e)
106

    
107

    
108
@app.errorhandler(Exception)
109
def generic_exception(e):
110
    if isinstance(e, HTTPException):
111
        # handle HTTPException exceptions here (MethodNotAllowed for example)
112
        Logger.warning(f""" HTTPException occurred: "{str(e)}" """)
113
        return str(e), e.code
114
    return handle_generic_exception(e)
115

    
116

    
117
def initialize_app(application) -> bool:
118
    """
119
    Initializes the application
120
        -   configure dependency injection
121
        -   check whether OpenSSL is on the system
122
    :param application Flask Application to be initialized.
123
    :return: boolean flag indicating whether initialization was successful or not
124
    """
125
    modules = [configuration.configure_env_variable, ConnectionProvider]
126
    injector = Injector(modules)
127
    FlaskInjector(app=application, modules=modules)
128

    
129
    config = injector.get(Configuration)
130
    logger.configure_logging(config)
131

    
132
    Logger.info(f"Using configuration file: {config.config_file}")
133

    
134
    # There's a little dependency on the CryptoService, which is not a pretty thing from
135
    # architectural point of view. However it is only a minimal piece of code and
136
    # it makes sense to do it in this way instead of trying to run openssl via subprocess here
137
    cryptography_service = injector.get(CryptographyService)
138
    try:
139
        # if version string is returned, OpenSSL is present on the system
140
        Logger.info(f"Using {cryptography_service.get_openssl_version()}")
141
        return True
142
    except CryptographyException:
143
        # If getting the version string throws an exception the OpenSSL is not available
144
        print("OpenSSL was not located on the system. Application will now exit.")
145
        Logger.error(f"OpenSSL was not located on the system. Application will now exit.")
146
        return False
147

    
148

    
149
# app initialization must follow endpoint declaration (after all Flask decoration)
150
with app.app_context():
151
    if not initialize_app(app):
152
        print("Failed to initialize app, aborting...")
153
        Logger.error(f"Failed to initialize app, aborting...")
154
        exit(-1)
155

    
156
if __name__ == '__main__':
157
    app_host = "0.0.0.0"
158
    app_port = 5000
159

    
160
    # TODO better load this from config.py
161
    if "FLASK_HOST" in os.environ:
162
        app_host = os.environ["FLASK_HOST"]
163

    
164
    if "FLASK_PORT" in os.environ:
165
        app_host = os.environ["FLASK_PORT"]
166

    
167
    app.run(host=app_host, port=app_port)
(7-7/12)