Ejemplo n.º 1
0
def login_to_app(response: Response, credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
	if credentials.username in app.users and credentials.password == app.users[credentials.username]:
		session_token = sha256(bytes(f"{credentials.username}{credentials.password}{app.secret}", encoding='utf8')).hexdigest()
		app.tokens[session_token] = credentials.username
		response.set_cookie(key="session_token", value=session_token)
		print(session_token)
		response.status_code = 307
		response.headers['Location'] = "/welcome"
		return response
	else:
		raise HTTPException(status_code=401, detail="Niepoprawny login lub hasło")
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # self.counter: int = 0
        self.patients: Dict[int, PatientModel] = {}
        self.security = HTTPBasic(auto_error=False)
        self.secret_key = SECRET_KEY
        self.API_KEY = SESSION_TOKEN
        self.cookie_sec = APIKeyCookie(name=self.API_KEY, auto_error=False)
        self.templates = Jinja2Templates(directory="templates")

        self.user = {'login': '******', 'password': '******'}
Ejemplo n.º 3
0
def basic_authentication(credentials: HTTPBasicCredentials = Depends(HTTPBasic())) -> str:
    correct_username = secrets.compare_digest("jes", credentials.username)  # reduce the risk of timing attacks
    bd_hashed_password = bcrypt.hashpw(b"pass", bcrypt.gensalt())
    correct_password = bcrypt.checkpw(credentials.password.encode('utf-8'), bd_hashed_password)
    print('token:', secrets.token_urlsafe(16))  # secrets.token_hex(16)
    print('pass:', bd_hashed_password)  # secrets.token_hex(16)
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect user or password",
        )
    return credentials.username
def path_login(response: Response,
               credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
    Valid_username = secrets.compare_digest(credentials.username, 'trudnY')
    Valid_password = secrets.compare_digest(credentials.password, 'PaC13Nt')
    if not (Valid_username and Valid_password):
        raise HTTPException(status_code=401,
                            detail='Invalid login or password')
    session_token = sha256(
        bytes(f'{credentials.username}{credentials.password}{app.secret_key}',
              encoding='utf8')).hexdigest()
    app.session_tokens.append(session_token)
    response.set_cookie(key='session_token', value=session_token)
    response.headers["Location"] = '/welcome'
    response.status_code = status.HTTP_302_FOUND
Ejemplo n.º 5
0
def get_current_user(response: Response,
                     credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
    correct_username = secrets.compare_digest(credentials.username, "trudnY")
    correct_password = secrets.compare_digest(credentials.password, "PaC13Nt")
    if not (correct_username and correct_password):
        raise HTTPException(status_code=401,
                            detail="Incorrect email or password")
    session_token = sha256(
        bytes(f"{credentials.username}{credentials.password}{app.secret_key}",
              encoding='utf8')).hexdigest()
    app.session_tokens.append(session_token)
    response.set_cookie(key="session_token", value=session_token)
    response.headers["Location"] = "/welcome"
    response.status_code = status.HTTP_302_FOUND
Ejemplo n.º 6
0
def login(response: Response,
          credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
    if credentials.username in app.users and app.users[
            credentials.username] == credentials.password:
        session_token = sha256(
            bytes(f"{credentials.username}{credentials.password}{app.secret}",
                  encoding="utf8")).hexdigest()
        response.set_cookie(key="session_token", value=session_token)
        app.session_tokens.append(session_token)
        response.status_code = 302
        response.headers["Location"] = '/welcome'
        print(session_token)
        return response
    else:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
Ejemplo n.º 7
0
def basic_auth(credentials: HTTPBasicCredentials = Depends(HTTPBasic())) -> str:
    correct_username = compare_digest(
        credentials.username, str(os.getenv("BASIC_AUTH_USERNAME", "test_username"))
    )
    correct_password = compare_digest(
        credentials.password,
        str(os.getenv("BASIC_AUTH_PASSWORD", "plunge-germane-tribal-pillar")),
    )
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username
Ejemplo n.º 8
0
async def authenticate_user(
    request: Request, credentials: HTTPBasicCredentials = Depends(HTTPBasic())
) -> str:
    """
    [Method for authenticating user credentials.]

    Args:
        request (Request): [API request object.]
        credentials (HTTPBasicCredentials, optional): [User credentials.].
            Defaults to Depends( HTTPBasic()).

    Raises:
        HTTPException: [Incorrect password.]
        HTTPException: [Inactive user.]
        HTTPException: [Unauthorized user.]

    Returns:
        str: [Username for user.]
    """
    IP = request.client.host
    _username = credentials.username
    password = credentials.password
    query = users.select().where(users.c.username == _username)
    user = await users_database.fetch_one(query)
    if user:
        if user['active']:
            user_salt = user['salt']
            user_password = user['password']
            if verify_hash(password + user_salt, user_password):
                return _username
            else:
                logger.warning(
                    'Failed authentication attempt was made with incorrect '
                    f'password for user {_username} with IP address {IP}.')
                raise HTTPException(status_code=401,
                                    detail="Incorrect password.")
        else:
            logger.warning(
                'Failed authentication attempt was made for inactive '
                f'user {_username} with IP address {IP}.')
            raise HTTPException(status_code=401,
                                detail=f"User {_username} is inactive.")
    else:
        logger.warning(
            'Failed authentication attempt was made for unauthorized '
            f'user {_username} with IP address {IP}.')
        raise HTTPException(status_code=401,
                            detail=f"Unauthorized user {_username}.")
Ejemplo n.º 9
0
class UserInventory:
    security = HTTPBasic()
    userDB = {
        "aslan": {
            "password": "******",
            "role": "k8s-admin",
        },
        "cansin": {
            "password": "******",
            "role": "guest",
        }
    }

    @classmethod
    def checkAuth(cls, credentials: HTTPBasicCredentials = Depends(security)):
        user = cls.getUser(credentials.username)
        if user:
            correct_password = secrets.compare_digest(credentials.password,
                                                      user.get("password"))
            if correct_password:
                return credentials.username
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )

    @classmethod
    def getUser(cls, user: str = None):
        if user:
            return cls.userDB.get(user)
        return cls.userDB

    @classmethod
    def getCurrentUser(cls,
                       credentials: HTTPBasicCredentials = Depends(security)):
        user = cls.getUser(credentials.username)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="User not found",
                headers={"WWW-Authenticate": "Basic"},
            )
        return User(userName=credentials.username,
                    password=credentials.password,
                    role=user.get("role"))
Ejemplo n.º 10
0
async def basic_auth(credentials: HTTPBasicCredentials = Depends(HTTPBasic())) -> str:
    """Authenticate a FastAPI request with HTTP Basic auth."""
    basic_auth_username = os.getenv("BASIC_AUTH_USERNAME")
    basic_auth_password = os.getenv("BASIC_AUTH_PASSWORD")
    if not (basic_auth_username and basic_auth_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Server HTTP Basic auth credentials not set",
            headers={"WWW-Authenticate": "Basic"},
        )
    correct_username = secrets.compare_digest(credentials.username, basic_auth_username)
    correct_password = secrets.compare_digest(credentials.password, basic_auth_password)
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="HTTP Basic auth credentials not correct",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username
Ejemplo n.º 11
0
    async def __call__(
        self,
        basic_credentials: Optional[HTTPBasicCredentials] = Depends(
            HTTPBasic(auto_error=False)),
        post_credentials: Optional[HTTPBasicCredentials] = Security(
            ClientIdSecretQuery(auto_error=False)),
    ) -> dict:
        credentials = post_credentials or basic_credentials

        if not credentials:
            raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                                detail="Not authenticated")
        client_data = await async_client_collection.find_one({
            '_id':
            credentials.username,
            'client_secret':
            credentials.password
        })
        if client_data is None:
            raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                                detail="Not authenticated")
        return client_data
Ejemplo n.º 12
0
import secrets
from typing import Optional, Union

from fastapi import Depends, status
from fastapi.exceptions import HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from passlib.context import CryptContext

from ..modals.collection import Collection
from ..modals.file import FileInDB
from ..modals.user import UserBase, UserInDB
from .db import get_conn, r

auth_required = HTTPBasic()
auth_optional = HTTPBasic(auto_error=False)

pwd_context = CryptContext(schemes=["argon2", "bcrypt"],
                           default="argon2",
                           deprecated=["bcrypt"])


def process_basic_auth(
        credentials: HTTPBasicCredentials) -> Optional[UserBase]:
    with get_conn() as conn:
        user_information = r.table("users").get(credentials.username).run(conn)
    if not user_information:
        return None

    user_information_parsed = UserInDB.parse_obj(user_information)
    if not (secrets.compare_digest(credentials.username,
                                   user_information_parsed.username)
Ejemplo n.º 13
0
from fastapi import Depends, HTTPException, Security, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic.types import PositiveInt

from ...db.repositories.api_keys import ApiKeysRepository
from ...db.repositories.users import UsersRepository
from .database import get_repository

# SEE https://swagger.io/docs/specification/authentication/basic-authentication/
basic_scheme = HTTPBasic()


def _create_exception():
    _unauthorized_headers = {
        "WWW-Authenticate":
        f'Basic realm="{basic_scheme.realm}"'
        if basic_scheme.realm else "Basic"
    }
    return HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid API credentials",
        headers=_unauthorized_headers,
    )


async def get_current_user_id(
    credentials: HTTPBasicCredentials = Security(basic_scheme),
    apikeys_repo: ApiKeysRepository = Depends(
        get_repository(ApiKeysRepository)),
) -> PositiveInt:
    user_id = await apikeys_repo.get_user_id(api_key=credentials.username,
Ejemplo n.º 14
0
import hashlib
from fastapi import status, Depends, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials

http_security = HTTPBasic()


def get_password_hash(password: str) -> str:
    return hashlib.sha512(password.encode()).hexdigest()


async def authenticate(credentials: HTTPBasicCredentials = Depends(
    http_security)) -> str:
    from app.usecases.user import UserUseCase
    if not await UserUseCase.authenticate_user(credentials.username,
                                               credentials.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username
Ejemplo n.º 15
0
def get_security(sec=Security(HTTPBasic())):
    return sec
Ejemplo n.º 16
0
from fastapi import Depends, FastAPI, HTTPException, Path, Request, status
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from loguru import logger

from .models import LightOperation, LightDescription, EndPoint

from ..__version__ import __version__
from ..effects import rainbow, pulse, flash_lights_impressively
from ..manager import LightManager, BlinkSpeed
from ..manager import LightIdRangeError, ColorLookupError
from ..manager import ALL_LIGHTS
from ..color import rgb_to_hex

# FastAPI Security Scheme
busylightapi_security = HTTPBasic()


class BusylightAPI(FastAPI):
    def __init__(self):
        # Set up authentication, if env. variables set
        dependencies = []
        try:
            self.username = environ['BUSYLIGHT_API_USER']
            self.password = environ['BUSYLIGHT_API_PASS']
            dependencies.append(Depends(self.authenticate_user))
        except KeyError:
            # Env. variables not set, so auth disabled
            self.username = None
            self.password = None
Ejemplo n.º 17
0
import os

from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette.responses import JSONResponse

from models import Customer as MongoCustomer, Product as MongoProduct
from schemas import BaseCustomer, Customer, Product


API_USER = os.environ.get('API_USER', None)
API_PASSWORD = os.environ.get('API_PASSWORD', None)


app = FastAPI()
security = HTTPBasic(realm="simple")


# TODO: see future decorator options
def assert_credentials(credentials: HTTPBasicCredentials = Depends(security)):
    if not all([credentials.username==API_USER, credentials.password==API_PASSWORD]):
        raise HTTPException(status_code=401, detail="Invalid credentials!")


@app.get("/")
def api_version(credentials: HTTPBasicCredentials = Depends(assert_credentials)):
    return {
        "version": "v1.0.0",
        "docs": "To see the docs access the url /docs",
    }
Ejemplo n.º 18
0
from functools import lru_cache

from fakeredis import FakeRedis
from fastapi import Depends
from fastapi.exceptions import HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from redis import Redis

from .schemas import User
from .utils import Settings

basic = HTTPBasic()


@lru_cache
def get_settings() -> Settings:
    return Settings()


@lru_cache
def get_redis() -> Redis:
    settings = get_settings()
    if settings.SCORETRACKER_TESTING_MODE:
        return FakeRedis(decode_responses=True)
    if settings.REDIS_URL is None:
        return Redis(decode_responses=True)
    return Redis.from_url(settings.REDIS_URL, decode_responses=True)


def get_current_user(
    creds: HTTPBasicCredentials = Depends(basic), redis: Redis = Depends(get_redis)
Ejemplo n.º 19
0
    UnauthorizedResponse,
    VpnWaitlistSchema,
)

app = FastAPI(
    title="ConTact Management System (CTMS)",
    description="CTMS API (work in progress)",
    version="1.1.3",
)
SessionLocal = None
METRICS_REGISTRY = CollectorRegistry()
METRICS = None
get_metrics_registry = lambda: METRICS_REGISTRY
get_metrics = lambda: METRICS
oauth2_scheme = OAuth2ClientCredentials(tokenUrl="token")
token_scheme = HTTPBasic(auto_error=False)


@lru_cache()
def get_settings() -> config.Settings:
    return config.Settings()


# Initialize Sentry for each thread, unless we're in tests
if "pytest" not in sys.argv[0]:  # pragma: no cover
    init_sentry()
    app.add_middleware(SentryAsgiMiddleware)


@app.on_event("startup")
def startup_event():  # pragma: no cover
Ejemplo n.º 20
0
from CommonServerPython import *
from CommonServerUserPython import *

sample_events_to_store = deque(maxlen=20)  # type: ignore[var-annotated]


class Incident(BaseModel):
    name: Optional[str] = None
    type: Optional[str] = None
    occurred: Optional[str] = None
    raw_json: Optional[Dict] = None


app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)

basic_auth = HTTPBasic(auto_error=False)
token_auth = APIKeyHeader(auto_error=False, name='Authorization')


class GenericWebhookAccessFormatter(AccessFormatter):
    def get_user_agent(self, scope: Dict) -> str:
        headers = scope.get('headers', [])
        user_agent_header = list(
            filter(lambda header: header[0].decode() == 'user-agent', headers))
        user_agent = ''
        if len(user_agent_header) == 1:
            user_agent = user_agent_header[0][1].decode()
        return user_agent

    def formatMessage(self, record):
        recordcopy = copy(record)
Ejemplo n.º 21
0
from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi import Header, Security
from authentication.models.users import User
from fastapi.security import HTTPBasic, HTTPBasicCredentials, APIKeyHeader
from typing import List
from starlette.responses import Response
from fastapi.encoders import jsonable_encoder
from authentication.interfaces.database import database
import jwt
from starlette.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED
from datetime import datetime, timedelta
from hashlib import sha256
from authentication.interfaces.token import verify_token

router = APIRouter()
security = HTTPBasic(auto_error=True)
api_key = APIKeyHeader(name="x-api-key", auto_error=True)


@router.post("/login", tags=["token"])
async def renew_token(
        response: Response,
        user: dict = Depends(verify_token),
        x_api_key: str = Header(None),
):
    response.headers["x-api-key"] = x_api_key
    return {"verified": True, "user": user["email"]}


@router.put("/login", tags=["token"])
async def renew_token(response: Response, user: dict = Depends(verify_token)):
Ejemplo n.º 22
0
def boot_admin_server(registration_tracker: RegistrationTrackerFixture) -> Generator:
    boot_admin_app = FastAPI(
        title="Boot Admin Mock Server",
        description="Demonstrate Spring Boot Admin Integration with FastAPI",
        docs_url="/api",
    )

    security = HTTPBasic()

    def get_current_username(credentials: HTTPBasicCredentials = Depends(security)) -> str:
        correct_username = secrets.compare_digest(credentials.username, "moo")
        correct_password = secrets.compare_digest(credentials.password, "haha")
        if not (correct_username and correct_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Moo haha",
            )
        return credentials.username

    # pylint: disable=unused-variable
    @boot_admin_app.post("/register", tags=["admin-server"])
    def register(registration: RegistrationRequest) -> Dict[str, str]:
        logging.debug("Got registration post %s, %d registrations since %s",
                      registration, registration_tracker.count, registration_tracker.start_time)
        registration_tracker.registration = registration
        registration_tracker.count += 1
        if registration_tracker.start_time is None:
            registration_tracker.start_time = registration.metadata["startup"]
        return {"id": "JB007"}

    # pylint: disable=unused-variable
    @boot_admin_app.post("/register-with-basic-auth", tags=["admin-server"])
    def register_with_basic_auth(
            registration: RegistrationRequest,
            username: str = Depends(get_current_username)) -> Dict[str, str]:
        logging.debug("Got registration post %s from %s, %d registrations since %s",
                      registration, username, registration_tracker.count, registration_tracker.start_time)
        registration_tracker.registration = registration
        registration_tracker.count += 1
        if registration_tracker.start_time is None:
            registration_tracker.start_time = registration.metadata["startup"]
        return {"id": "JB007"}

    # pylint: disable=unused-argument,unused-variable
    @boot_admin_app.delete("/register/{registration_id}", tags=["admin-server"])
    def deregister(registration_id: str) -> None:
        logging.debug("Got deregistration, delete %s (previous deregistration time is %s)",
                      registration_id, registration_tracker.deregistration_time)
        registration_tracker.deregistration_time = datetime.now(timezone.utc)

    # Start the mock boot-admin server that is needed to test pyctuator's registration
    boot_admin_config = Config(app=boot_admin_app, port=8001, loop="asyncio")
    boot_admin_server = CustomServer(config=boot_admin_config)
    boot_admin_thread = threading.Thread(target=boot_admin_server.run)
    boot_admin_thread.start()
    while not boot_admin_server.started:
        time.sleep(0.01)

    # Yield back to pytest until the module is done
    yield None

    boot_admin_server.should_exit = True
    boot_admin_server.force_exit = True
    boot_admin_thread.join()
Ejemplo n.º 23
0
import logging

from fastapi import APIRouter, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials

from app.config import get_settings, Settings
from app.core.security.utils import get_auth_mode, create_access_token
from app.models.pydantic.token import Token

router = APIRouter()
httpbasic = HTTPBasic()

log = logging.getLogger(__name__)


@router.post("/token", response_model=Token)
async def get_access_token(
        credentials: HTTPBasicCredentials = Depends(httpbasic),
        settings: Settings = Depends(get_settings),
):
    auth_mode = get_auth_mode(settings.AUTH_MODE)
    auth = auth_mode(credentials.username, credentials.password)

    await auth.aauthenticate(
    ) if auth_mode.concurrency == "async" else auth.authenticate()

    expiry, key, algorithm = (
        settings.AUTH_TOKEN_EXPIRY,
        settings.AUTH_KEY,
        settings.TOKEN_ALGORITHM,
    )
Ejemplo n.º 24
0
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from configparser import ConfigParser

security_scheme = HTTPBasic()


def check_credentials(
        credentials: HTTPBasicCredentials = Depends(security_scheme)):
    valid_login = False

    login_information = ConfigParser()
    login_information.read('config.ini')
    login_information = login_information['CREDENTIALS']
    if credentials.username in login_information:
        if login_information[credentials.username] == credentials.password:
            valid_login = True

    if not valid_login:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    else:
        return credentials.username
Ejemplo n.º 25
0
from database.Influx import Influx

from classes.IcicleSpyPackage import IcicleSpyPackage

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=8000)
    parser.add_argument('--config', type=str, required=True)

    args = parser.parse_args()
    print(args)

    cfg = json.loads(open(args.config, 'r').read())

    app = FastAPI()
    user_security = HTTPBasic()

    device_auth = DeviceAuth(cfg['device_security']['login'],
                             cfg['device_security']['password'])
    device_security = HTTPBasic()

    influx_db = Influx(host=cfg['influx']['url'],
                       token=cfg['influx']['token'],
                       org=cfg['influx']['org'],
                       bucket=cfg['influx']['bucket'])

    mysql_db = MySQL(host=cfg['mysql']['host'],
                     port=cfg['mysql']['port'],
                     user=cfg['mysql']['user'],
                     password=cfg['mysql']['password'])
Ejemplo n.º 26
0
from fastapi import FastAPI, File, UploadFile, Form, Depends, HTTPException, status
from fastapi.responses import HTMLResponse

from uuid import uuid4

from utils.file import dump_uploaded_file

## --------------- Authentication --------------- ##

PRODUCTION_MODE = True

import secrets
from fastapi.security import HTTPBasic, HTTPBasicCredentials

if PRODUCTION_MODE:
    security = Depends(HTTPBasic())

    # TODO: Use DB for authentication
    with open('credentials.json') as f:
        CREDENTIALS = json.load(f)
else:
    security = None


def authenticate(credentials: HTTPBasicCredentials = security):
    if not PRODUCTION_MODE:
        return True

    if credentials.username in CREDENTIALS and secrets.compare_digest(
            credentials.password, CREDENTIALS[credentials.username]):
        return True  # Authenticated!
from base64 import b64encode
from typing import Optional

from fastapi import FastAPI, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.testclient import TestClient
from requests.auth import HTTPBasicAuth

app = FastAPI()

security = HTTPBasic(auto_error=False)


@app.get("/users/me")
def read_current_user(
        credentials: Optional[HTTPBasicCredentials] = Security(security)):
    if credentials is None:
        return {"msg": "Create an account first"}
    return {"username": credentials.username, "password": credentials.password}


client = TestClient(app)

openapi_schema = {
    "openapi": "3.0.2",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {
        "/users/me": {
Ejemplo n.º 28
0
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
from http import HTTPStatus

from .cipher import RSA_Logic
from passlib.context import CryptContext

app = FastAPI()  # API's instance
security = HTTPBasic()  # Security instance
'''
Cipher parameters
'''
public, private = RSA_Logic.generate_keys()  # RSA keys generator
pwd_context = CryptContext(schemes=["bcrypt"],
                           deprecated="auto")  # password hash method
'''
API models
'''

ciph_db = []  # Basic database used to encoding and decoding

users_db = {  # Basic database with one user used to authentication
    "hubertkniola": {
        "username": "******",
        "hashed_password": pwd_context.hash('password'),  # 'password' in hash
        "disabled": False,
    }
}

Ejemplo n.º 29
0
    # intercept everything at the root logger
    logging.root.handlers = [handler]
    logging.root.setLevel(logging.DEBUG)

    # remove every other logger's handlers
    # and propagate to root logger
    for name in logging.root.manager.loggerDict.keys():
        logging.getLogger(name).handlers = []
        logging.getLogger(name).propagate = True


logger = logging.getLogger(__name__)

app = FastAPI()

security = HTTPBasic()


@dataclasses.dataclass
class Config:
    username: str
    password: str
    use_security: bool
    save_dir: Path
    url: str


config: Config


def get_ip():
from base64 import b64encode

from fastapi import FastAPI, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.testclient import TestClient
from requests.auth import HTTPBasicAuth

app = FastAPI()

security = HTTPBasic(realm="simple", description="HTTPBasic scheme")


@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
    return {"username": credentials.username, "password": credentials.password}


client = TestClient(app)

openapi_schema = {
    "openapi": "3.0.2",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {
        "/users/me": {
            "get": {
                "responses": {
                    "200": {
                        "description": "Successful Response",