Skip to content

Commit 5d26db2

Browse files
committed
Fix: Automatic secret key generation
1 parent d6d3406 commit 5d26db2

File tree

4 files changed

+30
-2
lines changed

4 files changed

+30
-2
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
security/
33
web/
44
data.db
5+
secrets/
56

67
# IDE specific
78
.vscode/

configurations/dev.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"DEBUG": true,
3-
"SECRET_KEY": "THIS_SHOULD_BE_CHANGED",
3+
"SECRETS_PATH": "./secrets",
44
"ENABLE_SIMPLE_HTTP_SERVER": true,
55
"RESTFUL_PREFIX": "/api",
66
"HOST": "0.0.0.0",

core/startup.py

+27
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ def create_app(name: str, config_name: str, init_tables=True) -> Flask:
4444
# Set configuration into the app
4545
for key in config.keys():
4646
app.config[key] = config[key]
47+
48+
# Initialize secret key
49+
init_secrets(app)
4750

4851
# Initialize core modules
4952
init_core_modules(app)
@@ -58,6 +61,30 @@ def create_app(name: str, config_name: str, init_tables=True) -> Flask:
5861
return app
5962

6063

64+
def init_secrets(app):
65+
"""Initializes the secrete key
66+
67+
Args:
68+
app (flask.app.Flask): A Flask application.
69+
"""
70+
secrets_path = app.config.get('SECRETS_PATH', './secrets')
71+
secret_key_file = os.path.join(secrets_path, 'secret_key')
72+
73+
if not os.path.exists(secrets_path):
74+
os.makedirs(secrets_path)
75+
76+
if not os.path.isfile(secret_key_file):
77+
import secrets
78+
with open(secret_key_file, 'wb') as f:
79+
secret_key = secrets.token_bytes(32) # Generate a random 32-byte secret key
80+
f.write(secret_key)
81+
else:
82+
with open(secret_key_file, 'rb') as f:
83+
secret_key = f.read()
84+
85+
app.config['SECRET_KEY'] = secret_key
86+
87+
6188
def init_core_modules(app):
6289
"""Initializes the core modules for the given context.
6390

docs/configurations.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ The configuration module provides an easy way to manage all the profiles used th
1818
```json
1919
{
2020
"DEBUG": true,
21-
"SECRET_KEY": "THIS SHOULD BE CHANGED!!!",
21+
"SECRETS_PATH": "./secrets",
2222
"ENABLE_SIMPLE_HTTP_SERVER": false,
2323
"RESTFUL_PREFIX": "/api",
2424
"HOST": "127.0.0.1",

0 commit comments

Comments
 (0)