def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) 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': '******'}
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.counter: int = 0 self.storage: Dict[int, Patient] = {} self.security = HTTPBasic(auto_error=False) self.secret_key = "kluczyk" self.API_KEY = "session" self.cookie_sec = APIKeyCookie(name=self.API_KEY, auto_error=False) self.templates = Jinja2Templates(directory="templates")
def __init__( self, secret: str, lifetime_seconds: int, cookie_name: str = "fastapiusersauth", name: str = "cookie", ): super().__init__(secret, lifetime_seconds, name=name) self.lifetime_seconds = lifetime_seconds self.cookie_name = cookie_name self.api_key_cookie = APIKeyCookie(name=self.cookie_name, auto_error=False)
def __init__( self, cookie_name: str = "fastapiusersauth", cookie_max_age: Optional[int] = None, cookie_path: str = "/", cookie_domain: Optional[str] = None, cookie_secure: bool = True, cookie_httponly: bool = True, cookie_samesite: str = "lax", ): self.cookie_name = cookie_name self.cookie_max_age = cookie_max_age self.cookie_path = cookie_path self.cookie_domain = cookie_domain self.cookie_secure = cookie_secure self.cookie_httponly = cookie_httponly self.cookie_samesite = cookie_samesite self.scheme = APIKeyCookie(name=self.cookie_name, auto_error=False)
def __init__( self, secret: str, lifetime_seconds: int, cookie_name: str = "fastapiusersauth", cookie_path: str = "/", cookie_domain: str = None, cookie_secure: bool = True, cookie_httponly: bool = True, name: str = "cookie", ): super().__init__(secret, lifetime_seconds, name=name) self.lifetime_seconds = lifetime_seconds self.cookie_name = cookie_name self.cookie_path = cookie_path self.cookie_domain = cookie_domain self.cookie_secure = cookie_secure self.cookie_httponly = cookie_httponly self.api_key_cookie = APIKeyCookie(name=self.cookie_name, auto_error=False)
def __init__( self, secret: str, lifetime_seconds: int, cookie_name: str = "fastapiusersauth", cookie_path: str = "/", cookie_domain: str = None, cookie_secure: bool = True, cookie_httponly: bool = True, cookie_samesite: str = "lax", name: str = "cookie", ): super().__init__(name, logout=True) self.secret = secret self.lifetime_seconds = lifetime_seconds self.cookie_name = cookie_name self.cookie_path = cookie_path self.cookie_domain = cookie_domain self.cookie_secure = cookie_secure self.cookie_httponly = cookie_httponly self.cookie_samesite = cookie_samesite self.scheme = APIKeyCookie(name=self.cookie_name, auto_error=False)
from typing import Optional from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyCookie from pydantic import BaseModel from starlette.testclient import TestClient app = FastAPI() api_key = APIKeyCookie(name="key", auto_error=False) class User(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(api_key)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): if current_user is None: return {"msg": "Create an account first"} else: return current_user
from fastapi import (Depends, HTTPException, status) from fastapi.security import APIKeyCookie from konoha.core import config import jwt cookie_sec = APIKeyCookie(name="session", auto_error=False) def get_current_user(session: str = Depends(cookie_sec)): try: payload = jwt.decode(session, config.session_key) return payload except Exception: return None db = {} def set_data(key, payload): global db db[key] = payload def get_data(key): global db print(db) return db.get(key)
from passlib.context import CryptContext # type: ignore from sqlalchemy.orm import Session from db import db_session from db.models import AccessToken, User from forms.auth import TokenPayload # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" TOKEN_SUBJECT = "access" ACCESS_TOKEN_EXPIRE_MINUTES = 30 PWD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto") OAUTH2_SCHEME = OAuth2PasswordBearer(tokenUrl="/api/me/signin") COOKIE_SCHEME = APIKeyCookie(name="auth._token.local") def verify_password(plain_password: str, hashed_password: str) -> bool: """Verifies plain and hashed password to be equal.""" return PWD_CONTEXT.verify(plain_password, hashed_password) def get_user(session: Session, login: str) -> User: """Returns User by specified login.""" session.expire_on_commit = False return session.query(User).filter_by(email=login).first() def authenticate_user(session: Session, login: str, password: str) -> Optional[User]:
'https://www.apple.com/us/search/Kitsunebi?src=globalnav' ]] class v2rayItems(BaseModel): config: dict class UserItems(BaseModel): UserItems: dict app = FastAPI() templates = Jinja2Templates(directory="templates") app.mount('/static', StaticFiles(directory='static'), name='static') cookie_sec = APIKeyCookie(name="session") v2raydata = appconfigLoad('v2ray_console/v2ray.ini') secret_key = v2raydata.get('key2') vaes = V2rayCryp(v2raydata.get('key1')) v2rayUsers = json.loads(vaes.decrypt(v2raydata.get('users'))) # mqttConfig = {"host": "dongbala.top", "port": "1883", "user": "******", "pwd": "2623824"} # app.mqttc = MQTTPubBase('v2ray', mqttConfig) def turnfile(file): with open(file, 'rb') as f: data = f.read() encoding = chardet.detect(data)['encoding'] data_str = data.decode(encoding) tp = 'LF' if '\r\n' in data_str:
from fido2 import cbor from fido2.client import ClientData from fido2.ctap2 import AttestationObject, AuthenticatorData from fido2.server import Fido2Server from fido2.webauthn import PublicKeyCredentialRpEntity from jwt import exceptions from pydantic import EmailStr, SecretStr from . import config, main from .db.schema import User, WebAuthnEntry # the api router which will be later registered in the main file router = APIRouter() # the cookie used to store the session token cookie_sec = APIKeyCookie(name="session") # Used to store the state while doing webauthn webauthn_state = APIKeyCookie(name="_state", auto_error=True) # argon2 password hasher and verifier ph = PasswordHasher() # webauthn rp = PublicKeyCredentialRpEntity(config.WEBAUTHN_RP_ID, config.WEBAUTHN_RP_NAME) fido2server = Fido2Server(rp) # on get render the html page @router.get("/login", response_class=HTMLResponse) async def view_login_page(request: Request):
class Server: api_key_name = "access-token" key_query = Security(APIKeyQuery(name=api_key_name, auto_error=False)) key_header = Security(APIKeyHeader(name=api_key_name, auto_error=False)) key_cookie = Security(APIKeyCookie(name=api_key_name, auto_error=False)) def __init__(self, app: BaseApp, telegram: BaseTelegram, routers: list[AppRouter], templates: Templates): self.app = app self.telegram = telegram self.server = FastAPI( title=app.app_config.app_name, docs_url=None, redoc_url=None, openapi_url=None, openapi_tags=app.app_config.tags_metadata, ) self.templates = templates self._configure_server() self._configure_openapi() self._configure_routers(routers) telegram.start() def get_server(self) -> FastAPI: return self.server def _configure_routers(self, routers: list[AppRouter]): base_routers = [ AppRouter(dconfig_router.init(self.app), "dconfig", "/api/dconfigs"), AppRouter(dvalue_router.init(self.app), "dvalue", "/api/dvalues"), AppRouter(dlog_router.init(self.app), "dlog", "/api/dlogs"), AppRouter(system_router.init(self.app, self.telegram), "system", "/api/system"), AppRouter( base_ui_router.init(self.app, self.templates, self.telegram), "base-ui"), ] for r in base_routers + routers: self.server.include_router( r.router, prefix=r.prefix, dependencies=[Depends(self._get_api_key())], tags=[r.tag]) def _configure_server(self): @self.server.exception_handler(Exception) async def exception_handler(_request: Request, err: Exception): code = getattr(err, "code", None) message = str(err) hide_stacktrace = isinstance(err, UserError) if code in [400, 401, 403, 404, 405]: hide_stacktrace = True if not hide_stacktrace: self.app.logger.exception(err) message += "\n\n" + traceback.format_exc() if not self.app.app_config.debug: message = "error" return PlainTextResponse(message, status_code=500) @self.server.on_event("shutdown") def shutdown_server(): self.telegram.stop() self.app.shutdown() current_dir = Path(__file__).parent.absolute() self.server.mount( "/static", StaticFiles(directory=current_dir.joinpath("static")), name="static") def _configure_openapi(self): @self.server.get("/openapi.json", tags=["openapi"], include_in_schema=False) async def get_open_api_endpoint(_api_key: APIKey = Depends( self._get_api_key())): response = JSONResponse( get_openapi( title=self.app.app_config.app_name, version=self.app.app_config.app_version, routes=self.server.routes, tags=self.app.app_config.tags_metadata, ), ) return response @self.server.get("/api", tags=["openapi"], include_in_schema=False) async def get_documentation(api_key: APIKey = Depends( self._get_api_key())): response = get_swagger_ui_html(openapi_url="/openapi.json", title=self.app.app_config.app_name) # noinspection PyTypeChecker response.set_cookie( self.api_key_name, value=api_key, domain=self.app.app_config.domain, httponly=True, max_age=60 * 60 * 24 * 30, expires=60 * 60 * 24 * 30, ) return response @self.server.get("/login", tags=["auth"]) async def route_login_page(): return self.templates.render("login.j2") @self.server.post("/login", tags=["auth"]) async def route_login_action(access_token: str = Form(...)): response = RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER) response.set_cookie( self.api_key_name, value=access_token, domain=self.app.app_config.domain, httponly=True, max_age=60 * 60 * 24 * 30, expires=60 * 60 * 24 * 30, ) return response @self.server.get("/logout", tags=["auth"]) async def route_logout_and_remove_cookie(): response = RedirectResponse(url="/") response.delete_cookie(self.api_key_name, domain=self.app.app_config.domain) return response @self.server.get("/api-link") def api_redirect( request: Request, url: str, method: str, data: Optional[str] = None, api_key: APIKey = Depends(self._get_api_key()), ): method = method.lower() headers = {self.api_key_name: api_key} url = str(request.base_url).removesuffix("/") + url if self.app.app_config.use_https: url = url.replace("http://", "https://", 1) params = None if data: params = json.loads(data) res = hrequest(url, method=method, headers=headers, params=params, json_params=True, timeout=600) if res.json: return res.json return res.body def _get_api_key(self) -> Callable: async def _get_api_key( query: str = Server.key_query, header: str = Server.key_header, cookie: str = Server.key_cookie, ): if query == self.app.app_config.access_token: return query elif header == self.app.app_config.access_token: return header elif cookie == self.app.app_config.access_token: return cookie else: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="access denied") return _get_api_key
from fastapi import Security, HTTPException from fastapi import status from fastapi.security import APIKeyQuery, APIKeyHeader, APIKeyCookie from settings import settings api_key = settings.api_key api_key_name = settings.api_key_name api_key_query = APIKeyQuery(name=api_key_name, auto_error=False) api_key_header = APIKeyHeader(name=api_key_name, auto_error=False) api_key_cookie = APIKeyCookie(name=api_key_name, auto_error=False) async def check_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), api_key_cookie: str = Security(api_key_cookie), ): if api_key not in (api_key_query, api_key_header, api_key_cookie): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", )
from fastapi import HTTPException, Security from fastapi.security import APIKeyCookie, APIKeyHeader, APIKeyQuery from starlette.status import HTTP_403_FORBIDDEN from drama.config import settings api_key_query = APIKeyQuery(name=settings.API_KEY_NAME, auto_error=False) api_key_header = APIKeyHeader(name=settings.API_KEY_NAME, auto_error=False) api_key_cookie = APIKeyCookie(name=settings.API_KEY_NAME, auto_error=False) async def get_api_key( api_key_query: str = Security(api_key_query), api_key_header: str = Security(api_key_header), api_key_cookie: str = Security(api_key_cookie), ): """ Checks the presence of an API key in the following order: * Query parameter * Header value * Cookie """ if api_key_query == settings.API_KEY: return api_key_query elif api_key_header == settings.API_KEY: return api_key_header elif api_key_cookie == settings.API_KEY: return api_key_cookie else: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Invalid access token")
from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyCookie from fastapi.testclient import TestClient from pydantic import BaseModel app = FastAPI() api_key = APIKeyCookie(name="key", description="An API Cookie Key") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": { "title": "FastAPI", "version": "0.1.0"
import jwt import hashlib import uuid from google.oauth2.id_token import verify_oauth2_token from google.auth.transport import requests from fastapi import Depends, HTTPException from fastapi.security import APIKeyCookie from starlette.status import HTTP_403_FORBIDDEN from sqlalchemy.orm import Session from pydantic import EmailStr from typing import Optional from ..models import User from .common import get_session cookie_name = "session" cookie_security = APIKeyCookie(name=cookie_name, auto_error=False) secret_key = '825d86db7d67844c086c01ed8001f8df82dc99c16a8cad4e' client_id = '558318040284-qq4i7nn9ol3767cgg5neroen7mb65vkb.apps.googleusercontent.com' def load_user(email: str, session: Session) -> Optional[User]: return session.query(User).filter_by(email=email).one_or_none() def create_token(email: EmailStr) -> bytes: return jwt.encode({"sub": email}, secret_key) def get_current_user(token: str = Depends(cookie_security), session: Session = Depends( get_session)) -> Optional[User]:
from fastapi.security import APIKeyCookie cookie_scheme = APIKeyCookie(name='bgm-tv-auto-tracker')
class Server: api_key_name = "access_token" key_query = Security(APIKeyQuery(name=api_key_name, auto_error=False)) key_header = Security(APIKeyHeader(name=api_key_name, auto_error=False)) key_cookie = Security(APIKeyCookie(name=api_key_name, auto_error=False)) def __init__(self, core: Core, telegram: Telegram): self.core = core self.telegram = telegram self.app = FastAPI( title=core.config.app_name, docs_url=None, redoc_url=None, openapi_url=None, openapi_tags=core.config.tags_metadata, ) self.templates = configure_jinja(core) self._configure_app() self._configure_openapi() self._configure_routers() telegram.start() def get_app(self) -> FastAPI: return self.app def _configure_routers(self): self.app.include_router( worker_router.init(self.core), prefix="/api/workers", dependencies=[Depends(self._get_api_key())], tags=["workers"], ) self.app.include_router( data_router.init(self.core), prefix="/api/data", dependencies=[Depends(self._get_api_key())], tags=["data"], ) self.app.include_router( system_router.init(self.core), prefix="/api/system", dependencies=[Depends(self._get_api_key())], tags=["system"], ) self.app.include_router( telegram_router.init(self.telegram), prefix="/api/telegram", dependencies=[Depends(self._get_api_key())], tags=["telegram"], ) self.app.include_router( ui_router.init(self.core, self.templates), prefix="/ui", dependencies=[Depends(self._get_api_key())], tags=["ui"], ) def _configure_app(self): @self.app.exception_handler(Exception) async def exception_handler(_request: Request, err: Exception): code = getattr(err, "code", None) message = str(err) hide_stacktrace = isinstance(err, UserError) if code in [400, 401, 403, 404, 405]: hide_stacktrace = True if not hide_stacktrace: self.core.log.exception(err) message += "\n\n" + traceback.format_exc() if not self.core.config.debug: message = "error" return PlainTextResponse(message, status_code=500) @self.app.on_event("shutdown") def shutdown_server(): self.telegram.stop() self.core.shutdown() current_dir = Path(__file__).parent.absolute() self.app.mount("/static", StaticFiles(directory=current_dir.joinpath("static")), name="static") def _configure_openapi(self): @self.app.get("/openapi.json", tags=["openapi"], include_in_schema=False) async def get_open_api_endpoint(_api_key: APIKey = Depends(self._get_api_key())): response = JSONResponse( get_openapi( title=self.core.config.app_name, version=self.core.config.version, routes=self.app.routes, tags=self.core.config.tags_metadata, ), ) return response @self.app.get("/api", tags=["openapi"], include_in_schema=False) async def get_documentation(api_key: APIKey = Depends(self._get_api_key())): response = get_swagger_ui_html(openapi_url="/openapi.json", title=self.core.config.app_name) # noinspection PyTypeChecker response.set_cookie( self.api_key_name, value=api_key, domain=self.core.config.domain, httponly=True, max_age=60 * 60 * 24 * 30, expires=60 * 60 * 24 * 30, ) return response @self.app.get("/logout", tags=["auth"]) async def route_logout_and_remove_cookie(): response = RedirectResponse(url="/") response.delete_cookie(self.api_key_name, domain=self.core.config.domain) return response @self.app.get("/") async def redirect_to_api(): return RedirectResponse(url="/ui") def _get_api_key(self) -> Callable: async def _get_api_key( query: str = Server.key_query, header: str = Server.key_header, cookie: str = Server.key_cookie, ): if query == self.core.config.access_token: return query elif header == self.core.config.access_token: return header elif cookie == self.core.config.access_token: return cookie else: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="access denied") return _get_api_key
from fastapi import Depends, HTTPException, status from starlette.requests import Request from fastapi.security import OAuth2PasswordBearer, APIKeyCookie from fastapi.logger import logger from itsdangerous.exc import BadSignature from sqlalchemy.orm import Session from jwt import PyJWTError, ExpiredSignatureError from . import crud, models, utils, cookie_auth from .database import SessionLocal from .settings import AUTH_COOKIE_NAME oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") cookie_sec = APIKeyCookie(name=AUTH_COOKIE_NAME) def get_db(): db = SessionLocal() try: yield db finally: db.close() def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)) -> models.User: """Return the current user based on the bearer token from the header""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, )
from fastapi import Depends, FastAPI, Security from fastapi.security import APIKeyCookie from pydantic import BaseModel from starlette.testclient import TestClient app = FastAPI() api_key = APIKeyCookie(name="key") class User(BaseModel): username: str def get_current_user(oauth_header: str = Security(api_key)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) openapi_schema = { "openapi": "3.0.2", "info": { "title": "FastAPI", "version": "0.1.0"
from jose import JWTError, jwt from sqlalchemy.orm import Session from sse_starlette.sse import EventSourceResponse from . import crud, models, schemas from .config import settings from .database import SessionLocal from .utils import CleanDiceRolls, CreateAccessToken, GenerateRoomCode ACCESS_TOKEN_EXPIRE_MINUTES = 1440 # 24 hours API_KEY_COOKIE_NAME = "key" # THIS STRING IS ALSO USED BY THE APP. CLOSE_ROOM_COMMAND = "***CLOSE_ROOM***" api_key = APIKeyCookie(name=API_KEY_COOKIE_NAME) broadcast = Broadcast(settings.SQLALCHEMY_DATABASE_URI) app = FastAPI(on_startup=[broadcast.connect], on_shutdown=[broadcast.disconnect],) app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["GET", "PUT"], ) roomQueues = {} # Dependency