Automatic keypair creation

This commit is contained in:
Éloi Rivard 2020-08-28 16:08:29 +02:00
parent 0ae8a5a0f5
commit 2c71e44eb3

View file

@ -12,6 +12,9 @@ import web.oauth
import web.routes
import web.tokens
import web.well_known
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend
from .flaskutils import current_user
from .ldaputils import LDAPObjectHelper
from .oauth2utils import config_oauth
@ -38,10 +41,45 @@ def create_app(config=None):
"Either create conf/config.toml or set the 'CONFIG' variable environment."
)
setup_dev_keypair(app)
if not os.path.exists(app.config["JWT"]["PUBLIC_KEY"]) or not os.path.exists(
app.config["JWT"]["PRIVATE_KEY"]
):
raise Exception("Invalid keypair")
setup_app(app)
return app
def setup_dev_keypair(app):
if not os.environ.get("FLASK_ENV") == "development":
return
if os.path.exists(app.config["JWT"]["PUBLIC_KEY"]) or os.path.exists(
app.config["JWT"]["PRIVATE_KEY"]
):
return
key = rsa.generate_private_key(
backend=crypto_default_backend(), public_exponent=65537, key_size=2048
)
private_key = key.private_bytes(
crypto_serialization.Encoding.PEM,
crypto_serialization.PrivateFormat.PKCS8,
crypto_serialization.NoEncryption(),
)
public_key = key.public_key().public_bytes(
crypto_serialization.Encoding.OpenSSH, crypto_serialization.PublicFormat.OpenSSH
)
with open(app.config["JWT"]["PUBLIC_KEY"], "wb") as fd:
fd.write(public_key)
with open(app.config["JWT"]["PRIVATE_KEY"], "wb") as fd:
fd.write(private_key)
def setup_app(app):
app.url_map.strict_slashes = False