Exemplo n.º 1
0
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)
    expiration = {"jwt": period, "cookie": int(period.total_seconds())}
    return expiration
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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()):
    userName = form.username
Exemplo n.º 4
0
# -------------------
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)


# The ``user_loader`` decorator doesn't propagate type hints. Fix this manually.
load_user = cast(Callable[[str], Awaitable[AuthUserValidator]], _load_user)