Skip to content

Commit d051ea4

Browse files
committed
(1) Obtain JWT_SECRET_KEY from current_app (2) Fix Dockerfile pipenv install
1 parent 57f6163 commit d051ea4

File tree

10 files changed

+77
-16
lines changed

10 files changed

+77
-16
lines changed

Dockerfile

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ ADD src src
55
ADD Pipfile Pipfile
66
ADD Pipfile.lock Pipfile.lock
77
RUN pip install pipenv
8-
RUN pipenv install
9-
RUN openssl req -new -newkey rsa:4096 -x509 -nodes -days 365 -keyout server.key -out server.crt -subj "/C=SG/ST=Singapore/L=Singapore /O=Kok How Pte. Ltd./OU=PythonFlaskRestAPI/CN=localhost/emailAddress=funcoolgeek@gmail.com" -passin pass:PythonFlaskRestAPI
8+
RUN pipenv install --system --deploy --ignore-pipfile
9+
RUN openssl req -new -newkey rsa:4096 -x509 -nodes -days 365 -keyout server.key -out server.crt -subj "/C=SG/ST=Singapore/L=Singapore /O=Kok How Pte. Ltd./OU=PythonRestAPI/CN=localhost/emailAddress=funcoolgeek@gmail.com" -passin pass:PythonRestAPI
1010
EXPOSE 8080 4433
1111
ENTRYPOINT [ "hypercorn", "--quic-bind", "0.0.0.0:4433", "--certfile", "server.crt", "--keyfile", "server.key", "--bind", "0.0.0.0:8080", "src.main:app" ]

Pipfile.lock

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

build.sh

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/bash
2+
docker build -t khteh/pythonrestapi .
3+
docker push khteh/pythonrestapi:latest

manifests/config.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
apiVersion: v1
22
kind: ConfigMap
33
metadata:
4-
name: python-config
4+
name: pythonrestapi
55
data:
66
config.json: |
77
{
8-
"ENV": "development",
8+
"ENVIRONMENT": "development",
99
"DEBUG": true,
1010
"TESTING": true,
11-
"SECRET_KEY": "PythonFlaskRestAPI",
11+
"SECRET_KEY": "PythonRestAPI",
1212
"SQLALCHEMY_TRACK_MODIFICATIONS": false,
1313
"HEALTHZ": {
1414
"live": "src.app.liveness",

manifests/config_local.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
"ENV": "development",
33
"DEBUG": true,
44
"TESTING": true,
5-
"SECRET_KEY": "PythonFlaskRestAPI",
5+
"SECRET_KEY": "PythonRestAPI",
6+
"JWT_SECRET_KEY": "PythonRestAPI",
67
"SQLALCHEMY_DATABASE_URI": "mysql+pymysql://guest:P*ssw0rd@localhost:30001/library",
78
"DB_USERNAME": "guest",
89
"DB_PASSWORD": "P*ssw0rd",

manifests/library.yml

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
library.sql: "-- MySQL dump 10.13 Distrib 8.0.26, for Linux (x86_64)\n--\n-- Host:
2+
localhost Database: library\n-- ------------------------------------------------------\n--
3+
Server version\t8.0.26\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT
4+
*/;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101
5+
SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n/*!50503 SET NAMES utf8mb4
6+
*/;\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n/*!40103 SET TIME_ZONE='+00:00'
7+
*/;\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n/*!40014
8+
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n/*!40101
9+
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n/*!40111 SET
10+
@OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n\n--\n-- Table structure for table
11+
`alembic_version`\n--\n\nDROP TABLE IF EXISTS `alembic_version`;\n/*!40101 SET
12+
@saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client
13+
= utf8mb4 */;\nCREATE TABLE `alembic_version` (\n `version_num` varchar(32) NOT
14+
NULL,\n PRIMARY KEY (`version_num`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
15+
COLLATE=utf8mb4_0900_ai_ci;\n/*!40101 SET character_set_client = @saved_cs_client
16+
*/;\n\n--\n-- Dumping data for table `alembic_version`\n--\n\nLOCK TABLES `alembic_version`
17+
WRITE;\n/*!40000 ALTER TABLE `alembic_version` DISABLE KEYS */;\nINSERT INTO `alembic_version`
18+
VALUES ('c8fac49602e6');\n/*!40000 ALTER TABLE `alembic_version` ENABLE KEYS */;\nUNLOCK
19+
TABLES;\n\n--\n-- Table structure for table `authors`\n--\n\nDROP TABLE IF EXISTS
20+
`authors`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503
21+
SET character_set_client = utf8mb4 */;\nCREATE TABLE `authors` (\n `id` int NOT
22+
NULL AUTO_INCREMENT,\n `firstname` varchar(128) NOT NULL,\n `lastname` varchar(128)
23+
NOT NULL,\n `email` varchar(255) NOT NULL,\n `phone` varchar(15) DEFAULT NULL,\n
24+
\ `created_at` datetime DEFAULT NULL,\n `modified_at` datetime DEFAULT NULL,\n
25+
\ PRIMARY KEY (`id`),\n UNIQUE KEY `ix_authors_email` (`email`),\n UNIQUE KEY
26+
`ix_authors_phone` (`phone`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n/*!40101
27+
SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table
28+
`authors`\n--\n\nLOCK TABLES `authors` WRITE;\n/*!40000 ALTER TABLE `authors`
29+
DISABLE KEYS */;\n/*!40000 ALTER TABLE `authors` ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n--
30+
Table structure for table `books`\n--\n\nDROP TABLE IF EXISTS `books`;\n/*!40101
31+
SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client
32+
= utf8mb4 */;\nCREATE TABLE `books` (\n `id` int NOT NULL AUTO_INCREMENT,\n `title`
33+
varchar(128) NOT NULL,\n `isbn` varchar(255) NOT NULL,\n `page_count` int NOT
34+
NULL,\n `created_at` datetime DEFAULT NULL,\n `modified_at` datetime DEFAULT
35+
NULL,\n `author_id` int NOT NULL,\n PRIMARY KEY (`id`),\n KEY `author_id` (`author_id`),\n
36+
\ CONSTRAINT `books_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`)\n)
37+
ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n/*!40101 SET
38+
character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `books`\n--\n\nLOCK
39+
TABLES `books` WRITE;\n/*!40000 ALTER TABLE `books` DISABLE KEYS */;\n/*!40000
40+
ALTER TABLE `books` ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure
41+
for table `users`\n--\n\nDROP TABLE IF EXISTS `users`;\n/*!40101 SET @saved_cs_client
42+
\ = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4
43+
*/;\nCREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `firstname`
44+
varchar(128) NOT NULL,\n `lastname` varchar(128) NOT NULL,\n `email` varchar(255)
45+
NOT NULL,\n `phone` varchar(15) DEFAULT NULL,\n `password` varchar(128) DEFAULT
46+
NULL,\n `created_at` datetime DEFAULT NULL,\n `modified_at` datetime DEFAULT
47+
NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `ix_users_email` (`email`),\n UNIQUE
48+
KEY `ix_users_phone` (`phone`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n/*!40101
49+
SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table
50+
`users`\n--\n\nLOCK TABLES `users` WRITE;\n/*!40000 ALTER TABLE `users` DISABLE
51+
KEYS */;\n/*!40000 ALTER TABLE `users` ENABLE KEYS */;\nUNLOCK TABLES;\n/*!40103
52+
SET TIME_ZONE=@OLD_TIME_ZONE */;\n\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014
53+
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS
54+
*/;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101
55+
SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION
56+
*/;\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n\n-- Dump completed on 2021-09-27
57+
10:45:57\n"

quart.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
#!/bin/bash
22
openssl req -new -newkey rsa:4096 -x509 -nodes -days 365 -keyout server.key -out server.crt -subj "/C=SG/ST=Singapore/L=Singapore /O=Kok How Pte. Ltd./OU=PythonFlaskRestAPI/CN=localhost/emailAddress=funcoolgeek@gmail.com" -passin pass:PythonFlaskRestAPI
3-
hypercorn --quic-bind 0.0.0.0:4433 --certfile server.crt --keyfile server.key --bind 0.0.0.0:8080 src.main:app
3+
pipenv run hypercorn --quic-bind 0.0.0.0:4433 --certfile server.crt --keyfile server.key --bind 0.0.0.0:8080 src.main:app

src/app.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
This script runs the application using a development server.
33
It contains the definition of routes and views for the application.
44
"""
5-
import quart.flask_patch, json, logging
5+
import quart.flask_patch, json, logging, os
66
from quart import Quart, request
77
from flask_healthz import HealthError
88
from datetime import datetime

src/common/Authentication.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import jwt, os, sys, datetime, logging
2-
from flask import request, json, Response, Blueprint, g, render_template, flash, session, abort
2+
from quart import request, json, Response, Blueprint, g, render_template, flash, session, abort, current_app
33
from flask_oidc import OpenIDConnect
44
from functools import wraps
55
from ..models.UserModel import UserModel
@@ -15,7 +15,7 @@ def generate_token(user_id):
1515
Generate Token
1616
"""
1717
#print(f"generate_token(): user_id: {user_id}")
18-
if not os.getenv("JWT_SECRET_KEY"):
18+
if not current_app.config["JWT_SECRET_KEY"]:
1919
raise Exception("Invalid user id!")
2020
if user_id:
2121
try:
@@ -30,7 +30,7 @@ def generate_token(user_id):
3030
"user_id": user_id
3131
# https://stackoverflow.com/questions/28418360/jwt-json-web-token-audience-aud-versus-client-id-whats-the-difference
3232
}
33-
return jwt.encode(payload, os.getenv("JWT_SECRET_KEY"), "HS512")
33+
return jwt.encode(payload, current_app.config["JWT_SECRET_KEY"], "HS512")
3434
except Exception as e:
3535
print("generate_token() exception!")
3636
print(type(e)) # the exception instance
@@ -48,7 +48,7 @@ def decode_token(token):
4848
result = {"data": {}, "error": {}}
4949
if token:
5050
try:
51-
payload = jwt.decode(token, os.getenv("JWT_SECRET_KEY"), "HS512", audience="urn:PythonFlaskRestAPI")
51+
payload = jwt.decode(token, current_app.config["JWT_SECRET_KEY"], "HS512", audience="urn:PythonFlaskRestAPI")
5252
result["data"] = {"user_id": payload["user_id"]}
5353
return result
5454
except jwt.ExpiredSignatureError as expired:
@@ -99,4 +99,4 @@ def wrapped_require_role(*args, **kwargs):
9999
else:
100100
return abort(403)
101101
return wrapped_require_role
102-
return decorated_require_role
102+
return decorated_require_role

src/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
Healthz(app, no_log=True)
1414
csrf = CSRFProtect(app)
1515
bcrypt.init_app(app)
16+
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
1617
#oidc.init_app(app)
1718

1819
numberRegex = "^(\d)+$"
@@ -105,5 +106,4 @@
105106
print(f"Valid phone: {phone}") if re.match(phoneRegex, phone) else print(f"Invalid phone: {phone}")
106107
phone = "+123-"
107108
print(f"Valid phone: {phone}") if re.match(phoneRegex, phone) else print(f"Invalid phone: {phone}")
108-
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
109109
#app.run(HOST, PORT)

0 commit comments

Comments
 (0)