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
Beispiel #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
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
Beispiel #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
Beispiel #5
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))
Beispiel #6
0
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"])
Beispiel #7
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)
Beispiel #8
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
Beispiel #9
0
from fastapi_users import FastAPIUsers
from users_app import models, schemas
from main_package import security

fastapi_users = FastAPIUsers(
    models.user_db,
    [security.jwt_authentication],
    schemas.User,
    schemas.UserCreate,
    schemas.UserUpdate,
    schemas.UserDB,
)
Beispiel #10
0
from .settings import settings as s
from .validation import *
from .authentication.models.manager import *
from .authentication.models.core import *
from .authentication.models.account import *
from .authentication.models.pydantic import *
from .authentication.Mailman import *
from .authentication.fapiusers import *

userdb = TortoiseUDB(UserDB,
                     UserMod,
                     include=['username', 'timezone'],
                     alternate=UserDBComplete)
jwtauth = JWTAuthentication(secret=s.SECRET_KEY,
                            lifetime_seconds=s.ACCESS_TOKEN_EXPIRE)
fapiuser = FastAPIUsers(userdb, [jwtauth], User, UserCreate, UserUpdate,
                        UserDB)

current_user = fapiuser.current_user()
tokenonly = OAuth2PasswordBearer(tokenUrl='token')

REFRESH_TOKEN_KEY = 'refresh_token'  # Don't change this. This is hard-coded as a variable.


async def register_callback(user: UserDB, _: Response):
    """
    Send an email containing a link the user can use to verify their account. This email directly
    shows the success/fail notice upon completion.
    """
    # Set the groups for this new user
    groups = await Group.filter(name__in=s.USER_GROUPS)
    user = await UserMod.get(pk=user.id).only('id', 'email')
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)
Beispiel #12
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)})
Beispiel #13
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"],
)
Beispiel #14
0
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication, CookieAuthentication
from fastapi_users import models
from starlette.templating import Jinja2Templates

from src.models import user_db, UserDB, User


SECRET_KEY = "^-r+qb5+fs7c#7%7j7_6)tvf%nnd4a41_2jm3gg9zp4v%x+h-@"
templates = Jinja2Templates(directory="src/templates")

auth_backends = [
    JWTAuthentication(secret=SECRET_KEY, lifetime_seconds=6000),
    CookieAuthentication(secret=SECRET_KEY, lifetime_seconds=6000),
]


fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    models.BaseUserCreate,
    models.BaseUserUpdate,
    UserDB,
    SECRET_KEY
)
Beispiel #15
0
from fastapi import FastAPI, Request
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication
from .database import database
from . import schema, models
from .config import settings


SECRET = "SECRET"
auth_backends = []

jwt_authentication = JWTAuthentication(secret=settings.JWT_SECRET, lifetime_seconds=settings.JWT_LIFETIME, tokenUrl="/auth/jwt/login")
auth_backends.append(jwt_authentication)

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

app.include_router(fastapi_users.get_auth_router(jwt_authentication), prefix="/auth/jwt", tags=["auth"])
app.include_router(fastapi_users.get_register_router(models.on_after_register), prefix="/auth", tags=["auth"])
app.include_router(
    fastapi_users.get_reset_password_router(SECRET, after_forgot_password=models.on_after_forgot_password),
    prefix="/auth",
    tags=["auth"],
)
app.include_router(fastapi_users.get_users_router(), prefix="/users", tags=["users"])


@app.on_event("startup")
async def startup():
    await database.connect()
Beispiel #16
0
from starlette.templating import Jinja2Templates

from models.orm_models import User as UserModel
from models.data_models import UserDB, User, UserCreate, UserUpdate, UserDB, UserDBOut

# ======================================================================================

SECRET = "123456789?=test"

auth = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)
user_db = TortoiseUserDatabase(UserDB, UserModel)

# fastapi-users already defines a number of routes, we just need to call them using:
# app.include_router(fastapi_users.router, prefix="/users", tags=["users"])
# in main py file
fastapi_users = FastAPIUsers(user_db, [auth], User, UserCreate, UserUpdate,
                             UserDB, SECRET)

# @fastapi_users.on_after_register()
# async def on_after_register(user: UserModel):
#     print(f"User {user.id} has registered.")

# @fastapi_users.on_after_forgot_password()
# async def on_after_forgot_password(user: UserModel, token: str):
#     print(f"User {user.id} has forgot their password. Reset token: {token}")

# =======================================================================================
# == CUSTOM ROUTES

router = APIRouter()

import asyncio
Beispiel #17
0
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication

from {{ cookiecutter.project_slug }}.adapters.db import repo_sqlalchemy, models
from {{ cookiecutter.project_slug }}.config import config
from {{ cookiecutter.project_slug }} import domain


jwt_authentication = JWTAuthentication(
    secret=config.TOKEN_SECRET, lifetime_seconds=3600, tokenUrl=config.TOKEN_URL,
)


users = FastAPIUsers(
    repo_sqlalchemy.fastapi_user,
    [jwt_authentication],
    domain.User,
    domain.commands.CreateUser,
    domain.commands.UpdateUser,
    models.UserDB,
)


auth_router = users.get_auth_router(jwt_authentication)
register_router = users.get_register_router()
reset_password_router = users.get_reset_password_router(config.TOKEN_SECRET)
verify_router = users.get_verify_router(config.TOKEN_SECRET)
users_router = users.get_users_router()
Beispiel #18
0

def get_jwt_strategy() -> JWTStrategy:
    return JWTStrategy(secret=os.environ["SECRET"], lifetime_seconds=3600)


jwt_authentication = AuthenticationBackend(
    name="jwt",
    transport=bearer_transport,
    get_strategy=get_jwt_strategy,
)

fastapi_users = FastAPIUsers(
    get_user_manager,
    auth_backends=[jwt_authentication],
    user_model=User,
    user_create_model=UserCreate,
    user_update_model=UserUpdate,
    user_db_model=UserDB,
)

routers = [
    dict(
        router=fastapi_users.get_auth_router(jwt_authentication, "password"),
        prefix="/api/auth/jwt",
        tags=["auth"],
    ),
    dict(
        router=fastapi_users.get_register_router(),
        prefix="/api/auth",
        tags=["auth"],
    ),
Beispiel #19
0
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import TortoiseUserDatabase

from server.models import User
from server.serializers.users import UserCreateSerializer, UserDBSerializer, UserSerializer, UserUpdateSerializer
from server.settings import settings

jwt_authentication = JWTAuthentication(secret=settings.secret_key,
                                       lifetime_seconds=settings.jwt_lifetime,
                                       tokenUrl='/api/auth/jwt/login')
user_db = TortoiseUserDatabase(UserDBSerializer, User)
fastapi_users = FastAPIUsers(
    user_db,
    [jwt_authentication],
    UserSerializer,
    UserCreateSerializer,
    UserUpdateSerializer,
    UserDBSerializer,
)
Beispiel #20
0
    reset_password_token_secret = config.secret
    verification_token_secret = config.secret


def get_user_db():
    yield OrmarUserDatabase(auth.UserDB, auth.UserModel)


def get_user_manager(user_db: OrmarUserDatabase = Depends(get_user_db)):
    yield UserManager(user_db)


fastapiUsers = FastAPIUsers(
    get_user_manager,
    [authBackend],
    auth.User,
    auth.UserCreate,
    auth.UserUpdate,
    auth.UserDB,
)


class CurrentUser:
    def __init__(self) -> None:
        self.user = fastapiUsers.current_user()
        self.active = fastapiUsers.current_user(active=True)
        self.verified = fastapiUsers.current_user(verified=True)
        self.active_verified = fastapiUsers.current_user(active=True,
                                                         verified=True)
        self.superuser = fastapiUsers.current_user(active=True, superuser=True)

Beispiel #21
0
from fastapi import APIRouter
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import JWTAuthentication
from settings import SECRET
from app.api.models import User, UserCreate, UserUpdate, UserDB
from app.db import user_db
from fastapi import Body, Depends, HTTPException

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

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


@router.get("/ping")
async def pong(user: user_db = Depends(
    fastapi_users.authenticator.get_current_active_user)):
    return {"ping": "pong!"}
                                  connect_args={"check_same_thread": False})

Base.metadata.create_all(engine)

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


class User(BaseUser):
    pass


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

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


@fastapi_users.on_after_register()
def on_after_register(user: User):
    print(f"User {user.id} has registered.")


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


@app.on_event("startup")
async def startup():
Beispiel #23
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):
Beispiel #24
0
from fastapi_users import FastAPIUsers
from fastapi_users.db import MongoDBUserDatabase

from app.auth.Users import UserDB, User, UserCreate, UserUpdate
from app.settings.auth import JWT_AUTHENTICATION
from app.settings.database import users_collections

fastapi_users = FastAPIUsers(MongoDBUserDatabase(UserDB, users_collections), [JWT_AUTHENTICATION], User, UserCreate,UserUpdate, UserDB)
Beispiel #25
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
Beispiel #26
0
Datei: api.py Projekt: IBM/arcade
# Tell fastpai_users how to interact with user data
user_db = graph.FastAPIUserDBAdapter(models.UserDB)

api_desc = ('The Advanced Research Collaboration and Application Development '
            'Environment (ARCADE) provides a unified and coherent API for '
            'accessing, analyzing, and extending a diverse set of derived '
            'data products concerning anthropogenic space objects.')
app = FastAPI(title='ARCADE', description=api_desc)

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

# Setup fastapi_users to handle user CRUD, authentication, and authorization
fastapi_users = FastAPIUsers(user_db, [jwt_authentication], models.User,
                             models.UserCreate, models.UserUpdate,
                             models.UserDB)

# Add the router for users to get JWTs
app.include_router(fastapi_users.get_auth_router(jwt_authentication),
                   prefix="/auth/jwt",
                   tags=["Authentication"])

# Add the router that provides the user registration endpoint
app.include_router(fastapi_users.get_register_router(),
                   prefix="/auth",
                   tags=["Authentication"],
                   include_in_schema=False)

# Helper functions that gets the user based on the JWT passed to the endpoint
current_active_user = fastapi_users.current_user(active=True)