def test_secure_session(): for jwt_alg, secret_key in ( ("HS256", "example"), ( "ES256", SecretKey( Secret(open(os.path.join(KEYS_DIR, "ec.key")).read()), Secret(open(os.path.join(KEYS_DIR, "ec.pub")).read()), ), ), ( "RS256", SecretKey( Secret(open(os.path.join(KEYS_DIR, "rsa.key")).read()), Secret(open(os.path.join(KEYS_DIR, "rsa.pub")).read()), ), ), ): app = create_app() app.add_middleware(SessionMiddleware, jwt_alg=jwt_alg, secret_key=secret_key, https_only=True) secure_client = TestClient(app, base_url="https://testserver") unsecure_client = TestClient(app, base_url="http://testserver") response = unsecure_client.get("/view_session") assert response.json() == {"session": {}} response = unsecure_client.post("/update_session", json={"some": "data"}) assert response.json() == {"session": {"some": "data"}} response = unsecure_client.get("/view_session") assert response.json() == {"session": {}} response = secure_client.get("/view_session") assert response.json() == {"session": {}} response = secure_client.post("/update_session", json={"some": "data"}) assert response.json() == {"session": {"some": "data"}} response = secure_client.get("/view_session").json() assert "exp" in response["session"] del response["session"]["exp"] assert response == {"session": {"some": "data"}} response = secure_client.post("/clear_session") assert response.json() == {"session": {}} response = secure_client.get("/view_session") assert response.json() == {"session": {}}
def test_failing_session_setup(): jwt_alg = "ES256" secret_key = SecretKey( Secret(open(os.path.join(KEYS_DIR, "ec.key")).read()), Secret(open(os.path.join(KEYS_DIR, "rsa.pub")).read()), ) app = create_app() with pytest.raises(Exception): app.add_middleware(SessionMiddleware, jwt_alg=jwt_alg, secret_key=secret_key)
def test_session(): for jwt_alg, secret_key in ( ("HS256", "example"), ( "ES256", SecretKey( Secret(open(os.path.join(KEYS_DIR, "ec.key")).read()), Secret(open(os.path.join(KEYS_DIR, "ec.pub")).read()), ), ), ( "RS256", SecretKey( Secret(open(os.path.join(KEYS_DIR, "rsa.key")).read()), Secret(open(os.path.join(KEYS_DIR, "rsa.pub")).read()), ), ), ): app = create_app() app.add_middleware(SessionMiddleware, jwt_alg=jwt_alg, secret_key=secret_key) client = TestClient(app) response = client.get("/view_session") assert response.json() == {"session": {}} response = client.post("/update_session", json={"some": "data"}) assert response.json() == {"session": {"some": "data"}} # check cookie max-age set_cookie = response.headers["set-cookie"] max_age_matches = re.search(r"; Max-Age=([0-9]+);", set_cookie) assert max_age_matches is not None assert int(max_age_matches[1]) == 14 * 24 * 3600 response = client.get("/view_session").json() assert "exp" in response["session"] del response["session"]["exp"] assert response == {"session": {"some": "data"}} response = client.post("/clear_session") assert response.json() == {"session": {}} response = client.get("/view_session") assert response.json() == {"session": {}}
def generate_token() -> Tuple[Secret, datetime.datetime]: global _TOKEN, _EXPIRATION _TOKEN = Secret(secrets.token_hex()) _EXPIRATION = _get_expiration_date() return _TOKEN, _EXPIRATION
def __init__(self, secret: str, tokenUrl: str, algorithm="HS256", use_cookie=False, use_header=True): """ :param str secret: Secret key used to sign and decrypt the JWT :param str algorithm: Should be "HS256" or "RS256" used to decrypt the JWT :param str tokenUrl: The url where the user can login to get the token :param bool use_cookie: Set if cookies should be checked for the token :param bool use_header: Set if headers should be checked for the token """ if use_cookie is False and use_header is False: raise Exception( "use_cookie and use_header are both False one of them needs to be True" ) self.secret = Secret(secret) self._user_callback = None self.algorithm = algorithm self.pwd_context = CryptContext(schemes=["bcrypt"]) # this is not mandatory as the user may want to use their own # function to get the token and pass it to the get_current_user method self.tokenUrl = tokenUrl self.oauth_scheme = None self._not_authenticated_exception = None self.use_cookie = use_cookie self.use_header = use_header self.cookie_name = 'access-token' super().__init__(tokenUrl=tokenUrl, auto_error=True)
def __init__(self, secret: str, token_url: str, algorithm="HS256", use_cookie=False, use_header=True): """ Initializes LoginManager Args: algorithm (str): Should be "HS256" or "RS256" used to decrypt the JWT token_url (str): The url where the user can login to get the token use_cookie (bool): Set if cookies should be checked for the token use_header (bool): Set if headers should be checked for the token """ if use_cookie is False and use_header is False: raise Exception("use_cookie and use_header are both False one of them needs to be True") self.secret = Secret(secret) self._user_callback = None self.algorithm = algorithm self.pwd_context = CryptContext(schemes=["bcrypt"]) self.tokenUrl = token_url self.oauth_scheme = None self._not_authenticated_exception = InvalidCredentialsException self.use_cookie = use_cookie self.use_header = use_header self.cookie_name = 'access-token' super().__init__(tokenUrl=token_url, auto_error=True)
def set_config_vars(self): self.config = Config(".env") self.CHANNEL_COMICS = self.config("CHANNEL_COMICS") self.CHANNEL_FORTUNKI = self.config("CHANNEL_FORTUNKI") self.DEPLOY_TIMESTAMP = self.config("DEPLOY_TIMESTAMP", cast=int, default=None) self.SENTRY_DSN = self.config("SENTRY_DSN", cast=Secret, default=None) self.SLACK_SIGNING_SECRET = self.config("SLACK_SIGNING_SECRET", cast=Secret) self.SLACK_TOKEN = self.config("SLACK_TOKEN", cast=Secret) self.SUPABASE_BUCKET = self.config("SUPABASE_BUCKET") self.SUPABASE_KEY = self.config("SUPABASE_KEY", cast=Secret) self.SUPABASE_URL = self.config("SUPABASE_URL") self.CURRENCY_API_KEY = self.config("CURRENCY_API_KEY", cast=Secret) self.DATABASE_URL = self.config("DATABASE_URL", cast=Secret, default=None) if self.DATABASE_URL is None: user = self.config("PG_USER", default="postgres") password = self.config("PG_PASS", default="postgres") host = self.config("PG_HOST", default="localhost") port = self.config("PG_PORT", default="5432") database = self.config("PG_NAME", default="postgres") self.DATABASE_URL = Secret( f"postgresql://{user}:{password}@{host}:{port}/{database}")
async def index(request): kwargs = {'secret_key': Secret('yyy'), 'field_name': 'csrf_token'} # generate token signed_token = generate_csrf(request, **kwargs) # test valid data validate_csrf(request, signed_token, **kwargs) return PlainTextResponse()
class Config: DB_NAME = 'fastapisimple' USERS_DOCUMENT_NAME = 'users' MONGODB_URL = f'mongodb://localhost:27017/{DB_NAME}' DEFAULT_ROUTE_STR = "/api" SECRET_KEY = Secret('a nice secret key') ALLOWED_HOSTS = CommaSeparatedStrings("localhost, 127.0.0.1")
def run(client: Kapten, token: str, host: str = "0.0.0.0", port: int = 8800) -> None: import uvicorn logger.info(f"Starting Kapten {__version__} server ...") app.state.client = client app.state.token = Secret(token) uvicorn.run(app, host=host, port=port, proxy_headers=True)
def test_session_expires(): for jwt_alg, secret_key in ( ("HS256", "example"), ( "ES256", SecretKey( Secret(open(os.path.join(KEYS_DIR, "ec.key")).read()), Secret(open(os.path.join(KEYS_DIR, "ec.pub")).read()), ), ), ( "RS256", SecretKey( Secret(open(os.path.join(KEYS_DIR, "rsa.key")).read()), Secret(open(os.path.join(KEYS_DIR, "rsa.pub")).read()), ), ), ): app = create_app() app.add_middleware(SessionMiddleware, jwt_alg=jwt_alg, secret_key=secret_key, max_age=-1) client = TestClient(app) response = client.post("/update_session", json={"some": "data"}) assert response.json() == {"session": {"some": "data"}} # requests removes expired cookies from response.cookies, we need to # fetch session id from the headers and pass it explicitly expired_cookie_header = response.headers["set-cookie"] expired_session_value = re.search(r"session=([^;]*);", expired_cookie_header)[1] response = client.get("/view_session", cookies={"session": expired_session_value}) assert response.json() == {"session": {}}
def __init__(self, secret: str, tokenUrl: str, algorithm="HS256"): """ :param str secret: Secret key used to sign and decrypt the JWT :param str algorithm: Should be "HS256" or "RS256" used to decrypt the JWT :param str tokenUrl: the url where the user can login to get the token """ self.secret = Secret(secret) self._user_callback = None self.algorithm = algorithm self.pwd_context = CryptContext(schemes=["bcrypt"]) # this is not mandatory as they user may want to user their own # function to get the token and pass it to the get_current_user method self.tokenUrl = tokenUrl self.oauth_scheme = None self._not_authenticated_exception = None
def __init__( self, app: ASGIApp, secret_key: typing.Union[str, Secret, SecretKey], session_cookie: str = "session", max_age: int = 14 * 24 * 60 * 60, # 14 days, in seconds same_site: str = "lax", https_only: bool = False, domain: str = config("DOMAIN", cast=str, default=None), jwt_alg: str = config("JWT_ALG", cast=str, default="HS256"), ) -> None: self.app = app self.jwt_header = {"alg": jwt_alg} if not isinstance(secret_key, SecretKey): self.jwt_secret = SecretKey(Secret(str(secret_key)), None) else: self.jwt_secret = secret_key # check crypto setup so we bail out if needed _jwt = jwt.encode(self.jwt_header, {"1": 2}, str(self.jwt_secret.encode)) assert { "1": 2 } == jwt.decode( _jwt, str(self.jwt_secret.decode if self.jwt_secret.decode else self. jwt_secret.encode), ), "wrong crypto setup" self.domain = domain self.session_cookie = session_cookie self.max_age = max_age self.security_flags = "httponly; samesite=" + same_site if https_only: # Secure flag can be used with HTTPS only self.security_flags += "; secure"
from databases import DatabaseURL from dotenv import load_dotenv, find_dotenv from starlette.config import Config from starlette.datastructures import Secret load_dotenv(find_dotenv()) _config = Config() DEBUG = _config("DEBUG", cast=bool, default=False) DATABASE_URL = _config( "DATABASE_URL", cast=DatabaseURL, default=DatabaseURL("postgresql://localhost/collages"), ) SECRET_KEY = _config( "SECRET_KEY", cast=Secret, default=Secret("SuperSecretKey!ChangeMe!") ) AUTH_EXPIRES = 7 * 24 * 60 * 60 # expiration time, in seconds COOKIE_PATH = "/api" APP_DOMAIN = _config("APP_DOMAIN", default="collages.local") COLLAGES_STORAGE_DIR = _config( "STORAGE_DIR", default=os.path.join("public", "media", "collages") )
from dotenv import load_dotenv from starlette.datastructures import CommaSeparatedStrings, Secret from databases import DatabaseURL import urllib.parse API_V1_STR = "/api" JWT_TOKEN_PREFIX = "Token" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # one week load_dotenv(".env") MAX_CONNECTIONS_COUNT = int(os.getenv("MAX_CONNECTIONS_COUNT", 10)) MIN_CONNECTIONS_COUNT = int(os.getenv("MIN_CONNECTIONS_COUNT", 10)) SECRET_KEY = Secret(os.getenv("SECRET_KEY", "123456")) PROJECT_NAME = os.getenv("PROJECT_NAME", "FastAPI example application") ALLOWED_HOSTS = CommaSeparatedStrings(os.getenv("ALLOWED_HOSTS", "")) MONGODB_URL = os.getenv("MONGODB_URL", "") # deploying without docker-compose #MONGODB_URL = os.getenv("DB_CONNECTION", "") # deploying without docker-compose if not MONGODB_URL: MONGO_HOST = os.getenv("MONGO_HOST", "localhost") MONGO_PORT = int(os.getenv("MONGO_PORT", 27017)) MONGO_USER = os.getenv("MONGO_USER", "admin") MONGO_PASS = os.getenv("MONGO_PASSWORD", "markqiu") MONGO_DB = os.getenv("MONGO_DB", "fastapi")
private_key = open( # pylint: disable=invalid-name os.path.join(KEYS_DIR, "rsa.key")).read() public_key = open( # pylint: disable=invalid-name os.path.join(KEYS_DIR, "rsa.pub")).read() elif JWT_ALG.startswith("ES"): private_key = open( # pylint: disable=invalid-name os.path.join(KEYS_DIR, "ec.key")).read() public_key = open( # pylint: disable=invalid-name os.path.join(KEYS_DIR, "ec.pub")).read() ## WIP: can't find a proper way to generate them # elif JWT_ALG.startswith("PS"): # # private_key = open( # pylint: disable=invalid-name # os.path.join(KEYS_DIR, "ps.key") # ).read() # # public_key = open( # pylint: disable=invalid-name # os.path.join(KEYS_DIR, "ps.pub") # ).read() secret_key = SecretKey( # pylint: disable=invalid-name Secret(private_key), Secret(public_key)) app.add_middleware(AuthlibMiddleware, secret_key=secret_key)
from starlette.datastructures import Secret from starlette.middleware import Middleware from starlette_authlib.middleware import AuthlibMiddleware from typing import List __all__: List[str] = ["middlewares"] middlewares: List[Middleware] = [ Middleware(AuthlibMiddleware, secret_key=Secret("CHANGEME")), ]
import os from dotenv import load_dotenv from starlette.datastructures import CommaSeparatedStrings, Secret from databases import DatabaseURL API_V1_STR = "/api" JWT_TOKEN_PREFIX = "Token" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 load_dotenv(".env") MAX_CONNECTIONS_COUNT = int(os.getenv("MAX_CONNECTIONS_COUNT", 10)) MIN_CONNECTIONS_COUNT = int(os.getenv("MIN_CONNECTIONS_COUNT", 10)) SECRET_KEY = Secret(os.getenv("SECRET_KEY", "project secret key")) PROJECT_NAME = os.getenv("PROJECT_NAME", "Moctor App") ALLOWED_HOSTS = CommaSeparatedStrings(os.getenv("ALLOWED_HOSTS", "")) MONGODB_URL = os.getenv("MONGODB_URL", "") if not MONGODB_URL: MONGO_HOST = os.getenv("MONGO_HOST", "localhost") MONGO_PORT = int(os.getenv("MONGO_PORT", 27017)) MONGO_USER = os.getenv("MONGO_USER", "moctor") MONGO_PASS = os.getenv("MONGO_PASSWORD", "moctor") MONGO_DB = os.getenv("MONGO_DB", "moctor") MONGODB_URL = DatabaseURL( f"mongodb://{MONGO_USER}:{MONGO_PASS}@{MONGO_HOST}:{MONGO_PORT}/{MONGO_DB}" )
import os from broadcaster import Broadcast from starlette.datastructures import Secret from dotenv import load_dotenv load_dotenv() PROJECT_NAME = "Planning Poker - Collaborative Planning" # JWT SECRET_KEY = str(Secret(os.getenv("SECRET_KEY", "precious"))) ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 8 # 60 minutes * 24 hours * 8 days = 8 days # Redis with Broadcaster BROADCAST_URL = os.getenv("BROADCAST_URL", "redis://*****:*****@cluster0-swdos.mongodb.net/test?retryWrites=true&w=majority" MONGO_DB_NAME = os.getenv("MONGO_DB", "planning_poker") TEST_MONGO_DB_NAME = "planning_poker_test" MAX_CONNECTIONS_COUNT = 10 MIN_CONNECTIONS_COUNT = 10 USER_COLLECTION_NAME = "users" POLL_COLLECTION_NAME = "polls"
from starlette.config import Config from starlette.datastructures import CommaSeparatedStrings, Secret config = Config(".env") MAX_CONNECTIONS_COUNT = int(config("MAX_CONNECTIONS_COUNT", default=10)) MIN_CONNECTIONS_COUNT = int(config("MIN_CONNECTIONS_COUNT", default=10)) SECRET_KEY = Secret(config("SECRET_KEY", default="secret key for project")) PROJECT_NAME = config("PROJECT_NAME", default="FastAPI example application") ALLOWED_HOSTS = CommaSeparatedStrings(config("ALLOWED_HOSTS", default="")) MONGODB_URL = config("DB", default="") # deploying without docker-compose database_name = "shostner" DEFAULT_URL = "http://jlugao.com" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30
# define your config here # coding=gbk import os from starlette.datastructures import Secret DEBUG = os.getenv("DEBUG", True) DATABASE_URL = os.getenv("DATABASE_URL", None) MAX_CONNECTIONS_COUNT = 10 MIN_CONNECTIONS_COUNT = 4 ALLOWED_HOSTS = [ "*", ] SECRET_KEY = Secret(os.getenv("SECRET_KEY", "application-secret")) # db connect config DB = { "user": '******', "pass": '******', "host": '120.253.41.92', "port": '8201', "db": 'tt', }
import os from dotenv import load_dotenv from starlette.datastructures import CommaSeparatedStrings, Secret ACCESS_COOKIE_EXPIRE_SECONDS = 60 * 60 # one hour in seconds REMEMBER_ME_COOKIE_EXPIRE_SECONDS = 60 * 60 * 24 * 7 # one week in seconds load_dotenv('.env') MAX_CONNECTIONS_COUNT = int(os.getenv('MAX_CONNECTIONS_COUNT', 10)) MIN_CONNECTIONS_COUNT = int(os.getenv('MIN_CONNECTIONS_COUNT', 10)) SECRET_KEY = Secret(os.getenv('SECRET_KEY', 'secret key for project')) #PROJECT_NAME = os.getenv('PROJECT_NAME', 'FastAPI example application') #ALLOWED_HOSTS = CommaSeparatedStrings(os.getenv('ALLOWED_HOSTS', '')) MONGO_HOST = os.getenv('MONGO_HOST', 'localhost') MONGO_PORT = int(os.getenv('MONGO_PORT', 1234)) MONGO_USER = os.getenv('MONGO_USER', 'user') MONGO_PASS = os.getenv('MONGO_PASS', 'password') MONGO_DB = os.getenv('MONGO_DB', 'doggy') MONGO_AUTH_TYPE = os.getenv('MONGO_AUTH_TYPE', 'SCRAM-SHA-1') users_collection = 'users' cookies_collection = 'cookies'
import os from pathlib import Path from starlette.datastructures import Secret from constants import ENGLISH from utils import str2bool DEV_MODE = str2bool(os.getenv('DEV_MODE', '')) # User if not DEV_MODE: USERNAME = Secret(os.environ['USERNAME']) PASSWORD = Secret(os.environ['PASSWORD']) else: USERNAME = Secret(os.getenv('USERNAME', 'admin')) PASSWORD = Secret(os.getenv('PASSWORD', 'pass')) # Paths CWD = Path.cwd() CACHE_PATH = Path(os.getenv('CACHE_PATH', '/var/lib/naive_feedya/')) CACHE_PATH.mkdir(exist_ok=True) DB_PATH = CACHE_PATH / 'dbs' DB_PATH.mkdir(exist_ok=True) FEED_ENTRIES_DB_FILENAME = 'feed_entries.sqlite' FEED_ENTRIES_DB_FILEPATH = DB_PATH / FEED_ENTRIES_DB_FILENAME STATS_DB_FILENAME = 'classifier.sqlite'
import os import bcrypt from fastapi.security import OAuth2PasswordBearer from passlib.context import CryptContext from starlette.datastructures import Secret pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") ALGORITHM = "HS256" JWT_TOKEN_PREFIX = "Bearer" SECRET_KEY = Secret(os.getenv("SECRET_KEY", None)) ACCESS_TOKEN_EXPIRE_MINUTES = 60 * .5 * 1 # 30 min ACCESS_TOKEN_JWT_SUBJECT = "access" OAUTH2_SCHEME = OAuth2PasswordBearer(tokenUrl="api/token") class TokenProvider: @staticmethod def generate_salt(): return bcrypt.gensalt().decode() @staticmethod def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) @staticmethod def get_password_hash(password): return pwd_context.hash(password)
import os from dotenv import load_dotenv from starlette.datastructures import CommaSeparatedStrings, Secret from databases import DatabaseURL API_V1_STR = "/api" load_dotenv(".env") MAX_CONNECTIONS_COUNT = int(os.getenv("MAX_CONNECTIONS_COUNT", 10)) MIN_CONNECTIONS_COUNT = int(os.getenv("MIN_CONNECTIONS_COUNT", 10)) SECRET_KEY = Secret(os.getenv("SECRET_KEY", "secret key for project")) PROJECT_NAME = os.getenv("PROJECT_NAME", "Social Media App") ALLOWED_HOSTS = CommaSeparatedStrings(os.getenv("ALLOWED_HOSTS", "")) MONGODB_URL = os.getenv("MONGODB_URL", "") # deploying without docker-compose if not MONGODB_URL: MONGO_HOST = os.getenv("MONGO_HOST", "localhost") MONGO_PORT = int(os.getenv("MONGO_PORT", 27017)) # MONGO_USER = os.getenv("MONGO_USER", "userdb") # MONGO_PASS = os.getenv("MONGO_PASSWORD", "pass") MONGO_DB = os.getenv("MONGO_DB", "Social_media") MONGODB_URL = DatabaseURL( f"mongodb://{MONGO_HOST}:{MONGO_PORT}/{MONGO_DB}") print(MONGODB_URL) else: MONGODB_URL = DatabaseURL(MONGODB_URL)
def set_secret(self, secret: str): self._config['secret'] = Secret(secret)
from typing import Optional, cast import os from pathlib import Path from starlette.config import Config from starlette.datastructures import CommaSeparatedStrings, Secret from .base import config SECRET_KEY = Secret( config( "DUCK_SECRET_KEY", default= "361e9e128ac204e66d5bfeca82814626353b96768d9180537aec5fdefc83d32d", )) JWT_ALGORITHM = config( "DUCK_JWT_ALGORITHM", default="HS256", ) ACCESS_TOKEN_EXPIRE_MINUTES = config( "DUCK_ACCESS_TOKEN_EXPIRE_MINUTES", cast=int, default=(7 * 24 * 60), )
""" Project Settings file """ import os from starlette.datastructures import CommaSeparatedStrings, Secret default_route_str = "/api" ALLOWED_HOSTS = CommaSeparatedStrings(os.getenv("ALLOWED_HOSTS", "*")) SECRET_KEY = Secret( os.getenv( "SECRET_KEY", "4bf4f696a653b292bc674daacd25195b93fce08a8dac7373b36c38f63cd442938b12ef911bd5d7d0" )) # Mongo configuration mongo_max_connections = int(os.getenv("MAX_CONNECTIONS_COUNT", 10)) mongo_min_connections = int(os.getenv("MIN_CONNECTIONS_COUNT", 10)) mongo_db = "fastapi" mongo_url = f"mongodb://*****:*****@email.com"
# config here import os from dotenv import load_dotenv # if using .env from starlette.datastructures import Secret # load local .env load_dotenv() DATABASE_URL = os.getenv('DATABASE_URL', None) MAX_CONNECTIONS_COUNT = 10 MIN_CONNECTIONS_COUNT = 4 ALLOWED_HOSTS = [ "*", ] SECRET_KEY = Secret(os.getenv('SECRET_KEY', 'app_secret'))