Settings working now. Everything working now.

Time for docker and beta test
This commit is contained in:
2020-05-30 23:39:02 +05:30
parent 95e92fc2bd
commit 013fce2e96
16 changed files with 73 additions and 214 deletions

View File

@ -1,12 +0,0 @@
from environs import Env
env = Env()
env.read_env() # read .env file, if it exists
class Settings:
debug: bool = env("DEBUG")
host: str = env("HOST")
port: int = env.int("PORT")
db_url: str = env("DB_URL")
log_level: str = env("LOG_LEVEL")

View File

@ -1,36 +1,24 @@
from dotenv import load_dotenv
import secrets
from typing import Any, Dict, List, Optional, Union
from typing import Any, Dict, Optional
from pydantic import AnyHttpUrl, BaseSettings, PostgresDsn, validator
from pydantic import BaseSettings, PostgresDsn, validator
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
# openssl rand -hex 32
SECRET_KEY: str = secrets.token_urlsafe(32)
# 60 minutes * 24 hours * 8 days = 8 days
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
SERVER_NAME: str = "localhost"
SERVER_HOST: AnyHttpUrl = "http://localhost:9998"
# BACKEND_CORS_ORIGINS is a JSON-formatted list of origins
# e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", \
# "http://localhost:8080", "http://local.dockertoolbox.tiangolo.com"]'
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)
PROJECT_NAME: str = "bifrost"
POSTGRES_SERVER: str = "localhost"
ALGORITHM: str = "HS256"
JWT_TOKEN_EXPIRE_MINUTES: int = 30
HOST: str = "0.0.0.0"
PORT: int = 80
DEBUG: bool = False
LOG_LEVEL: str = "NOTSET"
POSTGRES_SERVER: str = ""
POSTGRES_USER: str = "postgres"
POSTGRES_PASSWORD: str = "123456"
POSTGRES_DB: str = "hops"
SQLALCHEMY_DATABASE_URI: Optional[PostgresDsn] = None
POSTGRES_PASSWORD: str = ""
POSTGRES_DB: str = ""
SQLALCHEMY_DATABASE_URI: Optional[str] = None
@validator("SQLALCHEMY_DATABASE_URI", pre=True)
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
@ -44,9 +32,13 @@ class Settings(BaseSettings):
path=f"/{values.get('POSTGRES_DB') or ''}",
)
ALEMBIC_LOG_LEVEL: str = "INFO"
ALEMBIC_SQLALCHEMY_LOG_LEVEL: str = "WARN"
class Config:
case_sensitive = True
env_file = '.env'
load_dotenv()
settings = Settings()

View File

@ -1,6 +1,6 @@
import uuid
from datetime import datetime, timedelta
from typing import List, Union, Optional
from typing import List, Optional
from jwt import PyJWTError
from fastapi import Depends, HTTPException, status, Security
@ -10,19 +10,14 @@ from sqlalchemy.orm import Session
from jose import jwt
from jose.exceptions import ExpiredSignatureError
from brewman.core.config import settings
from brewman.models.auth import User as UserModel, Client
from ..db.session import SessionLocal
# to get a string like this run:
# openssl rand -hex 32
from ..schemas.auth import UserToken
SECRET_KEY = "8546a61262dab7c05ccf2e26abe30bc10966904df6dfd29259ea85dd0844a8e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token", scopes={})
@ -58,7 +53,7 @@ def create_access_token(*, data: dict, expires_delta: timedelta = None):
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
@ -116,7 +111,7 @@ async def get_current_user(
headers={"WWW-Authenticate": authenticate_value},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception

View File

@ -1,7 +1,10 @@
import logging
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from brewman.core.config import settings
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(settings.LOG_LEVEL)
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

View File

@ -53,7 +53,7 @@ from .routers.reports import (
)
from .db.base_class import Base
from .config import Settings
from .core.config import settings
from .db.session import engine
Base.metadata.create_all(bind=engine)
@ -149,4 +149,4 @@ app.include_router(rebase.router, prefix="/api/rebase", tags=["management"])
def init():
uvicorn.run(app, host=Settings.host, port=Settings.port)
uvicorn.run(app, host=settings.HOST, port=settings.PORT)

View File

@ -7,9 +7,9 @@ from sqlalchemy.orm import Session
from ..core.security import (
Token,
authenticate_user,
ACCESS_TOKEN_EXPIRE_MINUTES,
create_access_token, get_current_active_user, client_allowed,
)
from brewman.core.config import settings
from ..db.session import SessionLocal
from ..schemas.auth import UserToken
@ -52,7 +52,7 @@ async def login_for_access_token(
)
not_allowed_response.set_cookie(key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60)
return not_allowed_response
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={
"sub": user.name,
@ -78,7 +78,7 @@ async def login_for_access_token(
async def refresh_token(
user: UserToken = Security(get_current_active_user)
):
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={
"sub": user.name,