async def startup_event(): global config # load config with open('../config/config.yml', 'r') as ymlfile: config_yml = yaml.load(ymlfile, Loader=yaml.FullLoader) # convert settings to pydantic BaseSettings ServiceConfig.initialise_config(config=config_yml) logging.info("Signing Service Initialised and started up")
def get_user_by_username(username: str) -> Optional[UserSettings]: config = ServiceConfig() for user in config.users: if user.username != username: continue return user return None
def create_access_token(*, data: dict, expires_delta: timedelta = None): config = ServiceConfig() to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire, "sub": access_token_jwt_subject}) encoded_jwt = jwt.encode(to_encode, config.settings.secret_key.get_secret_value(), algorithm=ALGORITHM) return encoded_jwt
def user_authenticate(username: str, password: str) -> Optional[UserSettings]: config = ServiceConfig() for user in config.users: if user.username != username: continue if not verify_password(password, user.password_hash.get_secret_value()): continue return user return None
def get_current_user(token: str = Security( reusable_oauth2)) -> Optional[UserSettings]: config = ServiceConfig() try: payload = jwt.decode(token, config.settings.secret_key.get_secret_value(), algorithms=[ALGORITHM]) token_data = TokenPayload(**payload) except PyJWTError: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials") user = get_user_by_username(username=token_data.username) if not user: raise HTTPException(status_code=404, detail="User not found") return user
def login(login_details: Login): """ OAuth2 compatible token login, get an access token for future requests """ config = ServiceConfig() user = user_authenticate(username=login_details.username, password=login_details.password) if not user: raise HTTPException(status_code=400, detail=json.dumps( {"error": "Incorrect email or password"})) access_token_expires = timedelta( minutes=config.settings.access_token_expiry_minutes) return { "access_token": create_access_token(data={"username": user.username}, expires_delta=access_token_expires), "token_type": "bearer", }
async def get_wallet(request: Request) -> WalletConfig: """Checks IP restriction on wallet :param request: :return: """ config = ServiceConfig() body_json = await request.json() wallet_name = body_json.get('wallet_name', None) if not wallet_name: raise HTTPException(status_code=400, detail="Expecting wallet_name parameter") wallet = await config.get_wallet(wallet_name, initialise=True) # if not wallet.ip_authorised(request.client.host): # print(f'wallet not authorised from {request.client.host}') # raise HTTPException(status_code=403, detail=f"Access denied {request.client.host}") return wallet
import logging import yaml from fastapi import FastAPI from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware from starlette.middleware.cors import CORSMiddleware from config.config import ServiceConfig from api.api import api_router logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) app = FastAPI(title="Binance Chain Signing Service", openapi_url="/api/openapi.json") config: ServiceConfig() @app.on_event("startup") async def startup_event(): global config # load config with open('../config/config.yml', 'r') as ymlfile: config_yml = yaml.load(ymlfile, Loader=yaml.FullLoader) # convert settings to pydantic BaseSettings ServiceConfig.initialise_config(config=config_yml) logging.info("Signing Service Initialised and started up")