def fastapi_users(request, mock_user_db, mock_authentication,
                  oauth_client) -> FastAPIUsers:
    fastapi_users = FastAPIUsers(
        mock_user_db,
        [mock_authentication],
        User,
        UserCreate,
        UserUpdate,
        UserDB,
        "SECRET",
    )

    fastapi_users.get_oauth_router(oauth_client, "SECRET")

    @fastapi_users.on_after_register()
    def on_after_register():
        return request.param()

    @fastapi_users.on_after_forgot_password()
    def on_after_forgot_password():
        return request.param()

    @fastapi_users.on_after_update()
    def on_after_update():
        return request.param()

    return fastapi_users
예제 #2
0
def get_users_router(db):
    users_collection = db["users"]

    user_db = MongoDBUserDatabase(UserDB, users_collection)

    fastapi_users = FastAPIUsers(
        user_db,
        [jwt_authentication],
        User,
        UserCreate,
        UserUpdate,
        UserDB,
    )

    users_router = APIRouter()
    users_router.include_router(
        fastapi_users.get_auth_router(jwt_authentication),
        prefix="/auth/jwt",
        tags=["auth"],
    )
    users_router.include_router(fastapi_users.get_register_router(),
                                prefix="/auth",
                                tags=["auth"])
    users_router.include_router(
        fastapi_users.get_reset_password_router(settings.JWT_SECRET_KEY),
        prefix="/auth",
        tags=["auth"],
    )
    users_router.include_router(fastapi_users.get_users_router(),
                                prefix="/users",
                                tags=["users"])

    return users_router
예제 #3
0
def test_get_oauth_router(mocker, fastapi_users: FastAPIUsers, oauth_client: OAuth2):
    # Check that existing OAuth router declared
    # before the handlers decorators is correctly binded
    existing_oauth_router = fastapi_users.oauth_routers[0]
    event_handlers = existing_oauth_router.event_handlers
    assert len(event_handlers[Event.ON_AFTER_REGISTER]) == 1
    assert len(event_handlers[Event.ON_AFTER_FORGOT_PASSWORD]) == 1

    # Check that OAuth router declared
    # after the handlers decorators is correctly binded
    oauth_router = fastapi_users.get_oauth_router(oauth_client, "SECRET")
    assert isinstance(oauth_router, EventHandlersRouter)
    event_handlers = oauth_router.event_handlers
    assert len(event_handlers[Event.ON_AFTER_REGISTER]) == 1
    assert len(event_handlers[Event.ON_AFTER_FORGOT_PASSWORD]) == 1
예제 #4
0
def fastapi_users(request, mock_user_db, mock_authentication) -> FastAPIUsers:
    class User(BaseUser):
        pass

    fastapi_users = FastAPIUsers(mock_user_db, mock_authentication, User,
                                 "SECRET")

    @fastapi_users.on_after_register()
    def on_after_register():
        return request.param()

    @fastapi_users.on_after_forgot_password()
    def on_after_forgot_password():
        return request.param()

    return fastapi_users
예제 #5
0
async def test_app_client(
        mock_user_db, mock_authentication, oauth_client,
        get_test_client) -> AsyncGenerator[httpx.AsyncClient, None]:
    fastapi_users = FastAPIUsers(
        mock_user_db,
        [mock_authentication],
        User,
        UserCreate,
        UserUpdate,
        UserDB,
    )

    app = FastAPI()
    app.include_router(fastapi_users.get_register_router())
    app.include_router(fastapi_users.get_reset_password_router("SECRET"))
    app.include_router(fastapi_users.get_auth_router(mock_authentication))
    app.include_router(fastapi_users.get_oauth_router(oauth_client, "SECRET"))
    app.include_router(fastapi_users.get_users_router(), prefix="/users")

    @app.get("/current-user")
    def current_user(user=Depends(fastapi_users.get_current_user)):
        return user

    @app.get("/current-active-user")
    def current_active_user(user=Depends(
        fastapi_users.get_current_active_user)):
        return user

    @app.get("/current-superuser")
    def current_superuser(user=Depends(fastapi_users.get_current_superuser)):
        return user

    @app.get("/optional-current-user")
    def optional_current_user(user=Depends(
        fastapi_users.get_optional_current_user)):
        return user

    @app.get("/optional-current-active-user")
    def optional_current_active_user(
            user=Depends(fastapi_users.get_optional_current_active_user), ):
        return user

    @app.get("/optional-current-superuser")
    def optional_current_superuser(
            user=Depends(fastapi_users.get_optional_current_superuser), ):
        return user

    async for client in get_test_client(app):
        yield client
예제 #6
0
async def configure_db_and_routes():
    app.mongodb_client = AsyncIOMotorClient(settings.DB_URL,
                                            uuidRepresentation="standard")
    app.db = app.mongodb_client.get_default_database()

    user_db = MongoDBUserDatabase(UserDB, app.db["users"])

    app.fastapi_users = FastAPIUsers(
        user_db,
        [jwt_authentication],
        User,
        UserCreate,
        UserUpdate,
        UserDB,
    )

    app.include_router(get_users_router(app))
    app.include_router(get_todo_router(app))
예제 #7
0
파일: api.py 프로젝트: menno4000/DiscGenius
async def startup():
    await db.connect_to_database(path=DATABASE_URL)
    disc_db = db.client[DATABASE_NAME]
    global fs
    fs = AsyncIOMotorGridFSBucket(disc_db)

    global song_db
    song_db = disc_db.get_collection(SONGS_DB)

    global mix_db
    mix_db = disc_db.get_collection(MIX_DB)

    user_col = disc_db[USER_DB]
    global user_db
    user_db = MongoDBUserDatabase(UserDB, user_col)
    global fastapi_users
    fastapi_users = FastAPIUsers(user_db, [jwt_authentication], User,
                                 UserCreate, UserUpdate, UserDB)

    app.include_router(fastapi_users.get_auth_router(jwt_authentication),
                       prefix="/auth/jwt",
                       tags=["auth"])
    app.include_router(
        fastapi_users.get_register_router(after_register=on_after_register),
        prefix="/auth",
        tags=["auth"])
    app.include_router(
        fastapi_users.get_reset_password_router(
            SECRET, after_forgot_password=on_after_forgot_password),
        prefix="/auth",
        tags=["auth"],
    )
    app.include_router(
        fastapi_users.get_verify_router(
            SECRET, after_verification_request=after_verification_request),
        prefix="/auth",
        tags=["auth"],
    )
    app.include_router(fastapi_users.get_users_router(),
                       prefix="/users",
                       tags=["users"])
예제 #8
0
from fastapi_jwt_auth.exceptions import AuthJWTException
from fastapi_jwt_auth import AuthJWT
from fastapi_users.router.common import ErrorCode
from fastapi_users.authentication import JWTAuthentication
from fastapi_users import FastAPIUsers

from app.app_app import app
from app.mail import send_mail
from app.google_analytics import ga
import common.models as M

jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=60 * 5)
fastapi_users = FastAPIUsers(
    M.user_db,
    [jwt_authentication],
    M.FU_User,
    M.FU_UserCreate,
    M.FU_UserUpdate,
    M.FU_UserDB,
)


def on_after_register(user: M.FU_UserDB, request: Request):
    ga(user.id, 'user', 'register')
    with db():
        t = M.Tag(user_id=user.id, main=True, selected=True, name='Main')
        db.session.add(t)
        db.session.commit()
    send_mail(user.email, "welcome", {})


def on_after_forgot_password(user: M.FU_UserDB, token: str, request: Request):
예제 #9
0
from fastapi import Depends, Response
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication

from ..config import settings
from .models import user_db, User, UserCreate, UserUpdate, UserDB

jwt_authentication = JWTAuthentication(secret=settings.jwt_secret, lifetime_seconds=3600, tokenUrl="/auth/login")

accounts = FastAPIUsers(
    db=user_db,
    auth_backends=[jwt_authentication],
    user_model=User,
    user_create_model=UserCreate,
    user_update_model=UserUpdate,
    user_db_model=UserDB,
)

authrouter = accounts.get_auth_router(jwt_authentication)
authresetpasswordrouter = accounts.get_reset_password_router(reset_password_token_secret=settings.reset_password_secret)
registerrouter = accounts.get_register_router()
usersrouter = accounts.get_users_router()


@authrouter.post("/refresh-token")
async def refresh_token(response: Response, user=Depends(accounts.get_current_active_user)):
    return await jwt_authentication.get_login_response(user, response)
예제 #10
0
import types

from fastapi_users import FastAPIUsers

from config.jwt import jwt_authentication
from db.init import user_db
from db.schema import User, UserDB, UserUpdate, UserCreate
from routers.v1.auth import get_refresh_token_router, get_verify_account_router

fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
fastapi_users.get_refresh_token = types.MethodType(get_refresh_token_router,
                                                   fastapi_users)
fastapi_users.get_verify_account = types.MethodType(get_verify_account_router,
                                                    fastapi_users)
예제 #11
0
def after_verification_request(user: UserDB, token: str, request: Request):
    print(
        f"Verification requested for user {user.id}. Verification token: {token}"
    )


jwt_authentication = JWTAuthentication(secret=SECRET,
                                       lifetime_seconds=3600,
                                       tokenUrl="auth/jwt/login")

app = FastAPI()
fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
app.include_router(fastapi_users.get_auth_router(jwt_authentication),
                   prefix="/auth/jwt",
                   tags=["auth"])
app.include_router(fastapi_users.get_register_router(on_after_register),
                   prefix="/auth",
                   tags=["auth"])
app.include_router(
    fastapi_users.get_reset_password_router(
        SECRET, after_forgot_password=on_after_forgot_password),
    prefix="/auth",
    tags=["auth"],
)
예제 #12
0
from app.app_app import app
from common.utils import vars, SECRET
from app.mail import send_mail
from fastapi import Depends, Response, Request, BackgroundTasks
from fastapi_sqlalchemy import db  # an object to provide global access to a database session

from fastapi_users.authentication import JWTAuthentication
from fastapi_users import FastAPIUsers
import common.models as M
from app.google_analytics import ga


jwt_lifetime = 60 * 60 * 24 * 7  # 1wk. TODO implement token refresh
jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=jwt_lifetime)
fastapi_users = FastAPIUsers(
    M.user_db, [jwt_authentication], M.FU_User, M.FU_UserCreate, M.FU_UserUpdate, M.FU_UserDB,
)

@app.post("/auth/jwt/refresh")
async def refresh_jwt(response: Response, user=Depends(fastapi_users.get_current_user)):
    return await jwt_authentication.get_login_response(user, response)

def on_after_register(user: M.FU_UserDB, request: Request):
    ga(user.id, 'user', 'register')
    with db():
        t = M.Tag(user_id=user.id, main=True, selected=True, name='Main')
        db.session.add(t)
        db.session.commit()
    send_mail(user.email, "welcome", {})

def on_after_forgot_password(user: M.FU_UserDB, token: str, request: Request):
예제 #13
0
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import SQLAlchemyUserDatabase
from fastapi_users import FastAPIUsers

from schemas.user_schema import UserDB, User, UserCreate, UserUpdate
from db import database
from models.users import users

user_db = SQLAlchemyUserDatabase(UserDB, database, users)
SECRET = "djfdjdd9s93jd00fh38d83r32dbcs8s9a02b3jd0s"

auth_backends = []

jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)

auth_backends.append(jwt_authentication)

fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
예제 #14
0
    print(f"User {user.id} has registered.")


def on_after_forgot_password(user: UserDB, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}")


jwt_authentication = JWTAuthentication(secret=SECRET,
                                       lifetime_seconds=3600,
                                       tokenUrl="/auth/jwt/login")

app = FastAPI()
fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
app.include_router(fastapi_users.get_auth_router(jwt_authentication),
                   prefix="/auth/jwt",
                   tags=["auth"])
app.include_router(fastapi_users.get_register_router(on_after_register),
                   prefix="/auth",
                   tags=["auth"])
app.include_router(
    fastapi_users.get_reset_password_router(
        SECRET, after_forgot_password=on_after_forgot_password),
    prefix="/auth",
    tags=["auth"],
)
예제 #15
0
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

SECRET = "VERYBIGSECRET"
jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)

fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

db = Database(
    "quiz"
)  # TODO: Rewrite to https://fastapi.tiangolo.com/tutorial/sql-databases


@app.get("/", description="Check if site working", tags=['dev'])
def test():
    return {"status": "Hello, slvt!"}


@app.get("/hard_reset", description="Drop full database", tags=['dev'])
예제 #16
0
Define API endpoints for the users resource. 
Most of it has been included by the fastapi_users package.
"""

from fastapi_users import FastAPIUsers
from fastapi import Request
from typing import Dict, Any

from backend.server.models.user_models import User, UserCreate, UserUpdate, UserDB
from backend.server.auth import auth_backends
from backend.server.database import user_db

fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)


def on_after_register(user: UserDB, request: Request):
    print(f"User {user.id} has registered.")


def on_after_update(user: UserDB, updated_user_data: Dict[str, Any],
                    request: Request):
    print(
        f"User {user.id} has been updated with the following data: {updated_user_data}"
    )
예제 #17
0
auth_backends = []
authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)
auth_backends.append(authentication)


# --- FastAPIUsers Object Declaration -----------------------------------------

# MongoDB "users" collection adaptor for API calls
user_db = MongoDBUserDatabase(UserDB, collection)

# FastAPI Users helper class with all the configurations from above
# It provides us all the routes
fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB
)


# --- FastAPI Server Initialization -------------------------------------------

# Learn more https://frankie567.github.io/fastapi-users/configuration/routers/

# Initiating FastAPI Server
app = FastAPI()

# Managing CORS for the React Frontend connections
from fastapi.middleware.cors import CORSMiddleware
origins = [
예제 #18
0
from fastapi_users.authentication import JWTAuthentication
from fastapi_users import FastAPIUsers
from .models import user_db
from .schemas import User, UserDB, UserCreate, UserUpdate

SECRET = "BHIVGIVBKLJBytspfpuh1438a7089;ASAEPIUHAGH312839ASFNsdfgsdg"

auth_backends = []

jwt_authentication = JWTAuthentication(secret=SECRET,
                                       lifetime_seconds=3600,
                                       tokenUrl="/auth/jwt/login")

auth_backends.append(jwt_authentication)

fastapi_users = FastAPIUsers(user_db, auth_backends, User, UserCreate,
                             UserUpdate, UserDB)

current_active_user = fastapi_users.current_user(active=True)
예제 #19
0
파일: users.py 프로젝트: Asinphi/maowebsite
    print(f"User {user.id} has forgot their password. Reset token: {token}")


def after_verification_request(user: UserDB, token: str, request: Request):
    print(
        f"Verification requested for user {user.id}. Verification token: {token}"
    )


cookie_authentication = CookieAuthentication(secret=SECRET,
                                             cookie_secure=not IS_DEVELOPMENT)

fastapi_users = FastAPIUsers(
    user_db,
    [cookie_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
app.include_router(fastapi_users.get_auth_router(cookie_authentication),
                   prefix="/auth/cookie",
                   tags=["auth"])
"""
app.include_router(
    fastapi_users.get_register_router(on_after_register), prefix="/auth", tags=["auth"]
)
"""
app.include_router(
    fastapi_users.get_reset_password_router(
        SECRET, after_forgot_password=on_after_forgot_password),
    prefix="/auth",
예제 #20
0
from .schemas.experience import ExperienceDB
from .schemas.language import Language as LanguageSchema
from .schemas.language import LanguageDB
from .schemas.user import User, UserCreate, UserDB, UserUpdate

APP_SECRET = os.getenv("APP_SECRET")

jwt_authentication = JWTAuthentication(secret=APP_SECRET,
                                       lifetime_seconds=3600,
                                       tokenUrl="/auth/jwt/login")

app = FastAPI()
fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
app.include_router(fastapi_users.get_auth_router(jwt_authentication),
                   prefix="/auth/jwt",
                   tags=["auth"])
app.include_router(fastapi_users.get_register_router(),
                   prefix="/auth",
                   tags=["auth"])
app.include_router(fastapi_users.get_reset_password_router(APP_SECRET),
                   prefix="/auth",
                   tags=["auth"])
app.include_router(fastapi_users.get_verify_router(APP_SECRET),
                   prefix="/auth",
                   tags=["auth"])
예제 #21
0
from motor.motor_asyncio import AsyncIOMotorClient
from uuid import UUID, uuid4

from server.models.users import *
from server.config import *
from server.database import get_database

client = AsyncIOMotorClient(MONGO_ENDPOINT, uuidRepresentation="standard")
db = client[DB_NAME]
collection = db["users"]
user_db = MongoDBUserDatabase(UserDB, collection)

fastapi_users = FastAPIUsers(
    user_db,
    AUTH_BACKENDS,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

router = APIRouter()


@router.post("/{id}/deactivate", response_model=User, status_code=HTTP_200_OK)
async def deactivate_user(
        id,
        db: AsyncIOMotorClient = Depends(get_database),
        user: User = Depends(fastapi_users.get_current_user),
):
    if user.heir_id != '':
        assets = db["assets"].find({"user_id": str(user.id)})
예제 #22
0
Base.metadata.create_all(engine)

users = UserTable.__table__
oauth_accounts = OAuthAccount.__table__
user_db = SQLAlchemyUserDatabase(UserDB, database, users, oauth_accounts)

auth_backends = [
    JWTAuthentication(secret=SECRET, lifetime_seconds=3600),
]

app = FastAPI()
fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
    SECRET,
)
app.include_router(fastapi_users.router, prefix="/users", tags=["users"])

google_oauth_router = fastapi_users.get_oauth_router(google_oauth_client,
                                                     SECRET)
app.include_router(google_oauth_router, prefix="/google-oauth", tags=["users"])


@fastapi_users.on_after_register()
def on_after_register(user: User):
    print(f"User {user.id} has registered.")
예제 #23
0
파일: auth.py 프로젝트: nikosuk/Yacht

engine = sqlalchemy.create_engine(DATABASE_URL,
                                  connect_args={"check_same_thread": False})

Base.metadata.create_all(engine)

users = UserTable.__table__
user_db = SQLAlchemyUserDatabase(UserDB, database, users)

app = FastAPI()

fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)


async def fake_get_active_user():
    DISABLE_AUTH = settings.DISABLE_AUTH
    if DISABLE_AUTH == "True":
        return True
    else:
        await fastapi_users.get_current_active_user()


if settings.DISABLE_AUTH != "True":
    get_active_user = fastapi_users.get_current_active_user
예제 #24
0
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import SQLAlchemyUserDatabase

from . import database, dbutils, models, schemas, settings

user_db = SQLAlchemyUserDatabase(
    schemas.UserDB, database.database, models.User.__table__
)
jwt_authentication = JWTAuthentication(
    secret=settings.SECRET, lifetime_seconds=3600, tokenUrl="/auth/jwt/login"
)
fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    schemas.UserBase,
    schemas.UserCreate,
    schemas.UserUpdate,
    schemas.UserDB,
)


class Boto3ClientCache:
    """
    There may be many s3 nodes in the cluser.  Once a client has been established,
    cache it for future use.  This class works for sts and s3 type clients.
    """

    def __init__(self):
        self.cache: Dict[str, boto3.Session] = {}

    @staticmethod
예제 #25
0
from fastapi import APIRouter
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication

from app.db import user_db
from app.models.users import User, UserCreate, UserUpdate, UserDB

SECRET = "SECRET"
auth_backends = []
jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)
auth_backends.append(jwt_authentication)

fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

current_active_user = fastapi_users.current_user(active=True)

auth_router = APIRouter(tags=["auth"])

auth_router.include_router(
    fastapi_users.get_auth_router(jwt_authentication, requires_verification=False)
)
auth_router.include_router(fastapi_users.get_register_router())

user_router = APIRouter(tags=["users"])
예제 #26
0
from fastapi import FastAPI, Response, Request

from backend.api import routers
from backend.core.config import BACKEND_CORS_ORIGINS
from fastapi.middleware.cors import CORSMiddleware

from backend.db.session import database
from backend.users.logic import user_db, auth_backends, SECRET, jwt_authentication
from backend.users.schemas import User, UserCreate, UserUpdate, UserDB

app = FastAPI()

fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)

# @app.middleware("http")
# async def db_session_middleware(request: Request, call_next):
#     response = Response("Internal server error", status_code=500)
예제 #27
0
def on_after_forgot_password(user: UserDB, token: str, request: Request):
    # todo: send email to user with token
    print(f"User {user.id} has forgot their password. Reset token: {token}")


jwt_authentication = JWTAuthentication(
    secret=SECRET,
    lifetime_seconds=3600,
    tokenUrl=requests.utils.urlparse(base_url()).path + "/auth/jwt/login"
)

fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

jwt_auth_router = fastapi_users.get_auth_router(jwt_authentication)

@jwt_auth_router.post("/refresh")
async def refresh_jwt(response: Response, user=Depends(fastapi_users.get_current_active_user)):
    return await jwt_authentication.get_login_response(user, response)

register_router = fastapi_users.get_register_router(on_after_register)

reset_password_router = fastapi_users.get_reset_password_router(
        SECRET, after_forgot_password=on_after_forgot_password
)
예제 #28
0
    ):
        print(f"Verification requested for user {user.id}. Verification token: {token}")


async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
    yield UserManager(user_db)


bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")


def get_jwt_strategy() -> JWTStrategy:
    return JWTStrategy(secret=SECRET, lifetime_seconds=3600)


auth_backend = AuthenticationBackend(
    name="jwt",
    transport=bearer_transport,
    get_strategy=get_jwt_strategy,
)
fastapi_users = FastAPIUsers(
    get_user_manager,
    [auth_backend],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

current_active_user = fastapi_users.current_user(active=True)
예제 #29
0
from pydantic.types import UUID4
from pydantic import EmailStr
from ..desk.models import appeals
from ..reference_book.services import update_employee_licence
from ..service import send_mail, Email

auth_backends = []

jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)

auth_backends.append(jwt_authentication)

all_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

any_user = all_users.current_user(active=True)
employee = all_users.current_user(active=True, superuser=False)
developer_user = all_users.current_user(active=True, superuser=True)

default_uuid = UUID4("00000000-0000-0000-0000-000000000000")


async def get_owner(client_id: int, user: UserTable = Depends(any_user)):
    if not (user.client_id == client_id and user.is_owner):
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
    return user
예제 #30
0
    print(f"User {user.id} has registered.")


def on_after_forgot_password(user: UserDB, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}")


jwt_authentication = JWTAuthentication(
    secret=SECRET, lifetime_seconds=3600, tokenUrl="/auth/jwt/login"
)

app = FastAPI()
fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)
app.include_router(
    fastapi_users.get_auth_router(jwt_authentication), prefix="/auth/jwt", tags=["auth"]
)
app.include_router(
    fastapi_users.get_register_router(on_after_register), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_reset_password_router(
        SECRET, after_forgot_password=on_after_forgot_password
    ),
    prefix="/auth",
    tags=["auth"],