Skip to content

Commit f84b065

Browse files
committed
new samples added
1 parent 4327262 commit f84b065

File tree

284 files changed

+9028
-4
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

284 files changed

+9028
-4
lines changed

FastAPIMongoEngine/Dockerfile

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
2+
3+
COPY app /app
4+
5+
RUN ls -l
6+
7+
# RUN apt-get install python3-psycopg2
8+
9+
RUN pip install -r ./requirements.txt

FastAPIMongoEngine/Jenkinsfile

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
pipeline {
2+
agent any
3+
stages {
4+
stage('Clone Repository') {
5+
/* Cloning the repository to our workspace */
6+
steps {
7+
checkout scm
8+
}
9+
}
10+
stage('Build Image') {
11+
steps {
12+
sh 'sudo docker-compose build'
13+
}
14+
}
15+
stage('Run Container') {
16+
steps {
17+
sh 'sudo docker-compose up -d'
18+
}
19+
}
20+
}
21+
}

FastAPIMongoEngine/README.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# FastAPI-MongoEngine
2+
3+
FastAPI-MongoEngine is a Python API Application with FastAPI, JWT Authentication,
4+
MongoDB, Mongoengine, Docker and Jenkins Pipeline
5+
6+
## Features
7+
8+
* Full **Docker** integration (Docker based).
9+
* **Production ready** Python web server using Uvicorn and Gunicorn.
10+
* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> backend:
11+
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
12+
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
13+
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
14+
* **Short**: Minimize code duplication. Multiple features from each parameter declaration.
15+
* **Robust**: Get production-ready code. With automatic interactive documentation.
16+
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
17+
* <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">**Many other features**</a> including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
18+
* **Secure password** hashing by default.
19+
* **JWT token** authentication.
20+
* **Mongoengine** Document-Object Mapper models.
21+
* Basic starting models for users (modify and remove as you need).
22+
* **CORS** (Cross Origin Resource Sharing).
23+
* Load balancing between frontend and backend with **Nginx**, so you can have both under the same domain, separated by path, but served by different containers.
24+
* Let's Encrypt **HTTPS** certificates automatic generation.
25+
26+
## How to use it
27+
28+
## JWT token authentication
29+
30+
JWT-Signature using RSA256 algorithm.
31+
32+
You can generate a 2048-bit RSA key pair with the following commands:
33+
34+
```bash
35+
openssl genpkey -algorithm RSA -out rsa_private.pem -pkeyopt rsa_keygen_bits:2048
36+
openssl rsa -in rsa_private.pem -pubout -out rsa_public.pem
37+
```
38+
39+
## Create SSL Certificates using Certbot
40+
41+
Generate SSL cerificates from trusted thirdparty or openssl
42+
43+
For Open SSL use Certbot (Let'sencrypt)
44+
```bash
45+
sudo apt-get update
46+
sudo apt-get install software-properties-common
47+
sudo add-apt-repository universe
48+
sudo add-apt-repository ppa:certbot/certbot
49+
sudo apt-get install certbot python3-certbot-nginx
50+
51+
sudo certbot -d example.com certonly
52+
```
53+
certificates will be found in "/etc/letsencrypt/live/example.com/"
54+
55+
Generate a set of 4096-bit diffie-hellman parameters to improve security for some types of ciphers.
56+
```bash
57+
sudo mkdir -p /etc/nginx/ssl
58+
sudo openssl dhparam -out /etc/nginx/ssl/dhp-4096.pem 4096
59+
```
60+
61+
## Deployment
62+
63+
FastAPI Backend can be deployed using docker. Use below docker image for deployment.
64+
65+
tiangolo/uvicorn-gunicorn-fastapi-docker - [Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.](https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker)
66+
67+
68+
#### References
69+
70+
The fundamental repositories:
71+
- FastAPI - [FastAPI framework, high performance, easy to learn, fast to code, ready for production](https://fastapi.tiangolo.com/)
72+
- blog-posts - [Build a web API from scratch with FastAPI - the workshop](https://github.com/tiangolo/blog-posts/tree/master/pyconby-web-api-from-scratch-with-fastapi)
73+
- uvicorn - [The lightning-fast ASGI server.](https://www.uvicorn.org/deployment/)
74+
- tiangolo/uvicorn-gunicorn-fastapi-docker - [Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.](https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker)
75+
- Mongoengine - [A Python Object-Document-Mapper for working with MongoDB](https://github.com/MongoEngine/mongoengine)
76+
- Mongoengine(Docs) - [MongoEngine is an Object-Document Mapper, written in Python for working with MongoDB](http://docs.mongoengine.org/)

FastAPIMongoEngine/app/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from . import auth
2+
from . import conf
3+
from . import controller
4+
from . import crud
5+
from . import db
6+
from . import logs
7+
from . import routes
8+
from . import util
191 Bytes
Binary file not shown.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .token import access_token
2+
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from datetime import timedelta, datetime
2+
import os
3+
from jwt import (
4+
JWT,
5+
jwk_from_pem,
6+
)
7+
from typing import Dict
8+
from pathlib import Path
9+
from jwt.utils import get_int_from_datetime
10+
import sys
11+
12+
sys.path.append("..")
13+
from conf import EmailSettings
14+
15+
16+
def get_root() -> str:
17+
return str(Path(__file__).parent.parent) + os.sep
18+
19+
20+
class AccessToken:
21+
""" Access Token Util Class"""
22+
23+
def __init__(self):
24+
25+
self.__instance = JWT()
26+
self.__algorithm = "RS256"
27+
with open(get_root() + 'auth' + os.sep + 'jwtRS256_private.pem',
28+
'rb') as fh:
29+
self.__signing_key = jwk_from_pem(fh.read())
30+
with open(get_root() + 'auth' + os.sep + 'jwtRS256_public.pem',
31+
'rb') as fh:
32+
self.__verifying_key = jwk_from_pem(fh.read())
33+
34+
def create_access_token(self, *, data: dict,
35+
expires_delta: timedelta = None) -> str:
36+
"""Create Access Token Using JWT with RSA256 Encryption"""
37+
to_encode = data.copy()
38+
if expires_delta:
39+
expire = datetime.utcnow() + expires_delta
40+
else:
41+
expire = datetime.utcnow() + timedelta(minutes=15)
42+
to_encode.update({"ist": get_int_from_datetime(datetime.utcnow())})
43+
to_encode.update({"exp": get_int_from_datetime(expire)})
44+
encoded_jwt = self.__instance.encode(to_encode, self.__signing_key,
45+
self.__algorithm)
46+
return encoded_jwt
47+
48+
def decode_access_token(self, *, token: str) -> Dict:
49+
""" Decode Access Token """
50+
return self.__instance.decode(token, self.__verifying_key,
51+
do_time_check=False)
52+
53+
def generate_password_reset_token(self, email: str) -> str:
54+
""" Generate Access Token for password Reset email"""
55+
delta = timedelta(hours=EmailSettings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
56+
now = datetime.utcnow()
57+
expires = now + delta
58+
encoded_jwt = self.__instance.encode(
59+
{"exp": get_int_from_datetime(expires),
60+
"ist": get_int_from_datetime(now), "sub": email},
61+
self.__signing_key,
62+
alg=self.__algorithm,
63+
)
64+
return encoded_jwt
65+
66+
def verify_password_reset_token(self, token: str) -> Dict:
67+
""" Decode Access Token """
68+
return self.__instance.decode(token, self.__verifying_key,
69+
do_time_check=False)
70+
71+
72+
access_token = AccessToken()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .config import ProjectSettings
2+
from .config import DBSettings
3+
from .config import EmailSettings
216 Bytes
Binary file not shown.
221 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)