def header_manager(app, secret, token_url, load_user_fn) -> LoginManager: instance = LoginManager(secret, token_url) instance.user_loader(load_user_fn) @app.get("/private/header") def private_header_route(_=Depends(instance)): return {"detail": "Success"} return instance
def cookie_manager(app, secret, token_url, load_user_fn) -> LoginManager: instance = LoginManager(secret, token_url, use_cookie=True, use_header=False) instance.user_loader(load_user_fn) @app.get("/private/cookie") def private_cookie_route(_=Depends(instance)): return {"detail": "Success"} return instance
async def test_no_user_callback(): manager = LoginManager(SECRET, app) token = manager.create_access_token(data=dict(sub='*****@*****.**')) with pytest.raises(Exception): try: await manager.get_current_user(token) except HTTPException: raise Exception else: assert False
def exception_manager(app, secret, token_url, load_user_fn, custom_exception) -> LoginManager: instance = LoginManager(secret, token_url) instance.user_loader(load_user_fn) # exception handling setup def redirect_on_auth_exc(request, exc): return RedirectResponse(url="/redirect") instance.not_authenticated_exception = custom_exception app.add_exception_handler(custom_exception, redirect_on_auth_exc) # routes @app.get("/private/exception") def raise_exception(_=Depends(instance)): return {"detail": "error"} @app.get("/redirect") def redirect(): return {"detail": "Redirected"} return instance
def middleware_manager(app, token_url, load_user_fn): instance = LoginManager("secret", "/auth/token") instance.user_loader(load_user_fn) instance.useRequest(app) @app.get("/private/request") def private_request_route(request: Request): user = request.state.user if user is None: raise InvalidCredentialsException else: return {"detail": "Success"} return instance
def app_factory(): settings = get_settings() app = FastAPI() origins = {settings.WEBAPP_URL} app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], expose_headers=[ "X-Content-Filename", "Content-Disposition", "application/x-www-form-urlencoded", ], ) login_manager = LoginManager(settings.SECRET, "/login") return app, login_manager
from config import DEFAULT_SETTINGS from fastapi_login import LoginManager manager = LoginManager(DEFAULT_SETTINGS.secret, DEFAULT_SETTINGS.token_url) def hash_password(plaintext_password: str): """ Return the hash of a password """ return manager.pwd_context.hash(plaintext_password) def verify_password(password_input: str, hashed_password: str): """ Check if the provided password matches """ return manager.pwd_context.verify(password_input, hashed_password)
from fastapi import FastAPI, Request, Depends, HTTPException, status from fastapi.responses import RedirectResponse, HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from fastapi.security import OAuth2PasswordRequestForm from fastapi_login import LoginManager from models import user as userModel app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") SECRET = "secret-key" manager = LoginManager(SECRET, tokenUrl="/login", use_cookie=True) manager.cookie_name = "some-name" @manager.user_loader def user_loader(userName): return userModel.getUser(userName) @app.get("/", response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("login.html", {"request": request}) @app.post("/login") async def login(form: OAuth2PasswordRequestForm = Depends()):
from sqlalchemy.orm.session import Session from hipyrion_back.database import get_db from fastapi_login import LoginManager import os from ..models import User SECRET_KEY = os.getenv('SECRET_KEY', 'hard-to-guess') login_manager = LoginManager(SECRET_KEY, tokenUrl='/auth/token') db = get_db() @login_manager.user_loader def load_user(db: Session, username: str): return db.query(User).filter(User.username == username).first()
from core.auth import TokenManager, PasswordHasher from fastapi_login import LoginManager from web_server.settings import settings token_manager = TokenManager() password_hasher = PasswordHasher() login_manager = LoginManager(settings.SECRET_KEY, tokenUrl="/auth/token")
from fastapi_login import LoginManager from datetime import timedelta from database import Hash, User from email_validator import validate_email, EmailNotValidError from password_strength import PasswordStats # Router initialization router = APIRouter( tags=['Authentication'], prefix='/v1/auth', ) # Session Manager initialization manager = LoginManager( secret=env.SECRET_KEY, tokenUrl="/auth/login", use_cookie=False, use_header=True, ) @manager.user_loader def load_user(username: str, db: database.Session = next(database.get_db())): return db.query(database.User).filter_by(username=username).first() # Routes @router.post('/login') def login(data: OAuth2PasswordRequestForm = Depends()): username = data.username
def clean_manager(secret, token_url) -> LoginManager: """ Return a new LoginManager instance """ return LoginManager(secret, token_url)
SECRET_KEY = "8c1d92746114dea8497b7c82f7da4231c71f0e0a4a6dc71af593d36b6303e16a" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 DATABASE_URL = "sqlite://db/server.db" class NotAuthenticatedException(Exception): pass # these two argument are mandatory def exc_handler(request, exc): return RedirectResponse(url='/login') manager = LoginManager(SECRET_KEY, tokenUrl='/auth/token', use_cookie=True) manager.not_authenticated_exception = NotAuthenticatedException app = FastAPI() app.add_exception_handler(NotAuthenticatedException, exc_handler) app.mount("/sdk", StaticFiles(directory="templates/sdk"), name="static") templates = Jinja2Templates(directory="templates") @manager.user_loader async def load_user(email: str): # could also be an asynchronous function query = users.select().where(users.c.email == email) user = await database.fetch_one(query) return user
import os import uvicorn from fastapi import FastAPI, Depends, Header, File, UploadFile from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi_login import LoginManager from fastapi_login.exceptions import InvalidCredentialsException from app_data import users from data import predictions_handler # Initiate app instance app = FastAPI(title='ReArt', version='1.0', description='NN Image classification of recyclables') manager = LoginManager(os.getenv("SECRET_KEY"), tokenUrl='/auth/token') security = HTTPBasic() # unprotected @app.post("/send_image_predict/") async def send_image_predict(file: UploadFile = File(...)): contents = await file.read() return {"pred": predictions_handler.get_prediction(contents)} # protected @manager.user_loader def load_user(user_name: str, password: str): user = users.find_one({'username': user_name, "password": password})
'surname': 'Doe', 'email': '*****@*****.**', 'password': '******' }, '*****@*****.**': { 'name': 'Sandra', 'surname': 'Johnson', 'email': '*****@*****.**', 'password': '******' } } app = FastAPI() client = TestClient(app) SECRET = os.urandom(24).hex() lm = LoginManager(SECRET, tokenUrl='/auth/token') @app.post('/auth/token') def login(data: OAuth2PasswordRequestForm = Depends()): user_identifier = data.username password = data.password user = load_user(user_identifier) if not user: raise InvalidCredentialsException elif password != user['password']: raise InvalidCredentialsException access_token = lm.create_access_token(data=dict(sub=user_identifier))
def test_config_no_cookie_no_header_raises(secret, token_url): with pytest.raises(Exception) as exc_info: LoginManager(secret, token_url, use_cookie=False, use_header=False) assert "use_cookie and use_header are both False one of them needs to be True" == str(exc_info.value)
from fastapi import FastAPI from fastapi_login import LoginManager app = FastAPI() SECRET = "super-secret-key" manager = LoginManager(SECRET, '/login')
from fastapi_login import LoginManager manager = LoginManager('secret', '/login', use_cookie=True, use_header=False)
from fastapi_login import LoginManager manager = LoginManager( 'secret', '/login', use_cookie=True )
class NotAuthenticatedException(Exception): pass def handle_exc(request, exc): print(request, exc) return RedirectResponse(url='/redirect') # app setup app = FastAPI() app.add_exception_handler(NotAuthenticatedException, handle_exc) # Manager setup manager = LoginManager(SECRET, tokenUrl=TOKEN_URL) cookie_manager = LoginManager(SECRET, tokenUrl=TOKEN_URL, use_cookie=True) manager.user_loader(load_user) cookie_manager.user_loader(load_user) manager.useRequest(app) # routes @app.post(TOKEN_URL) def login(response: Response, data: OAuth2PasswordRequestForm = Depends(), cookie=Optional[bool]): user_identifier = data.username password = data.password
from fastapi import APIRouter, Depends from fastapi.security import OAuth2PasswordRequestForm from fastapi_login import LoginManager from fastapi_login.exceptions import InvalidCredentialsException from config import settings from app.models.models import User manager = LoginManager( settings.SECRET_KEY, token_url='/auth/token', # use_cookie=True ) router = APIRouter() @manager.user_loader async def load_user(phone: str): user = await User.get(phone=phone) return user # 获取token @router.post('/auth/token') async def login(data: dict): phone = data['phone'] password = data['password'] user = await load_user(phone) if not user:
# Third-party imports # ------------------- from fastapi import Request from fastapi.exceptions import HTTPException from fastapi_login import LoginManager # Local application imports # ------------------------- from .config import settings from .crud import fetch_instructor_courses, fetch_user from .applogger import rslogger from .models import AuthUserValidator auth_manager = LoginManager(settings.jwt_secret, "/auth/validate", use_cookie=True) auth_manager.cookie_name = "access_token" @auth_manager.user_loader() # type: ignore async def _load_user(user_id: str) -> AuthUserValidator: """ fetch a user object from the database. This is designed to work with the original web2py auth_user schema but make it easier to migrate to a new database by simply returning a user object. """ rslogger.debug(f"Going to fetch {user_id}") return await fetch_user(user_id)
from fastapi.security import OAuth2PasswordRequestForm from fastapi_login import LoginManager from datetime import timedelta from passlib.hash import bcrypt from .models import User, UserIn from config import jwt_secret import jwt # Router Setup router = APIRouter(prefix="/user", tags=["Auth"]) # Credentials Setup token_cookie_name = "access-token" token_expire_time = 5 credentials = LoginManager(secret=jwt_secret, tokenUrl="/login/", use_cookie=True, use_header=False) credentials.cookie_name = token_cookie_name # Callback run when credentials used as dependency # Logic in fastapi-login library, Grabs cookie and decodes jwt value, returns user_id @credentials.user_loader async def query_user(user): return user # Used to sync expiration for jwt and auth cookie, used in /login route # jwt is timedelta object, cookie is int in seconds def set_duration_days(time_days: int): period = timedelta(days=time_days)
def test_no_cookie_and_no_header_exception(): with pytest.raises(Exception): LoginManager('secret', 'login', use_cookie=False, use_header=False)
from fastapi_login import LoginManager from app.core import Config from app.core.errors import ACCESS_DENIED_ERROR from app.db_models.expense import Expense from app.db_models.user import User manager = LoginManager(Config.secret, tokenUrl='/auth/login') def hash_password(plain_password): return manager.pwd_context.hash(plain_password) def verify_password(plain_password, hashed_password): return manager.pwd_context.verify(plain_password, hashed_password) def belongs_to_user(expense: Expense, user: User): if expense.owner_id == user.id: return True else: raise ACCESS_DENIED_ERROR
from fastapi import APIRouter, Depends, status from fastapi.responses import RedirectResponse, HTMLResponse from fastapi.security import OAuth2PasswordRequestForm from fastapi_login import LoginManager from .settings import SECRET, USERNAME, PASSWORD from fastapi_login.exceptions import InvalidCredentialsException authr = APIRouter() manager = LoginManager(SECRET, tokenUrl="/auth/login", use_cookie=True) manager.cookie_name = "jimbru" DB = {USERNAME: {"password": PASSWORD}} @manager.user_loader def load_user(username: str): user = DB.get(username) return user @authr.post("/auth/login") def login(data: OAuth2PasswordRequestForm = Depends()): username = data.username password = data.password user = load_user(username) if not user: raise InvalidCredentialsException elif password != user['password']: raise InvalidCredentialsException
# remove statment # REMOVE REPORT # Procedure -> remove performerFunction ; focalDeviceAction.csv # ADD API FOR GETTING BMI OF A SINGLE PATIENT # return db.query(models.Care_team.department,func.count(models.Care_team.department)).join(models.user_details, full = True).filter(models.user_details.org_id == org_id).filter(models.user_details.entity_type == "C").group_by(models.Care_team.department).all() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) manager = LoginManager(SECRET, token_url='/auth/token') # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() @manager.user_loader def load_user(username: str, db ): # could also be an asynchronous function user = db.query(models.user_details).filter(models.user_details.username == username).first() return user @app.get("/") async def root():
from fastapi_login.exceptions import InvalidCredentialsException from datetime import timedelta from .. import API_PREFIX from ..utils.helpers import BaseSchema # Environment Import from .config import JWT_SECRET from .config import JWT_EXPIRATION_DAYS # Database Import from ..db.engine import get_db from ..modules.users.models import User manager = LoginManager(JWT_SECRET, tokenUrl=API_PREFIX+'/auth/token') route = APIRouter() # Login Schema class LoginData(BaseSchema): username: str password: str class Config: schema_extra = { "example": { "username": "******", "password": "******" } }
from fastapi.security import OAuth2PasswordRequestForm from fastapi_login.exceptions import InvalidCredentialsException from datetime import timedelta origins = ["http://*****:*****@aerospike.com": {'password': '******'}} SUMMARY_FILE_NAME = "../../collectinfo_output/collect_info_20200525_092140/20200525_092140_summary.log" HEALTH_FILE_NAME = "../../collectinfo_output/collect_info_20200525_092140/20200525_092140_health.log" @manager.user_loader def load_user(email: str): user = fake_db.get(email) print("User is {}".format(user)) return user
from fastapi_login import LoginManager from app import config from app.database import SessionLocal from app import models SECRET = config.settings.SECRET login_manager = LoginManager(SECRET, '/user/login') @login_manager.user_loader def get_user(user_id: int): db = SessionLocal() return db.query(models.User).filter(models.User.id == user_id).first()