示例#1
0
async def create_dummy_users():
    users = [
        {
            "email": "*****@*****.**",
            "hashed_password": get_password_hash("luna")
        },
        {
            "email": "*****@*****.**",
            "hashed_password": get_password_hash("harley")
        },
    ]
    for user in users:
        await add_user(UserInDB(**user))
        await add_user(UserInDB(**user))
async def create_user(user: UserCreate) -> User:
    """
    Accepts a UserCreate model and returns a User
    This is endpoint allows both users of any role to be created.
    It should only be used for testing
    """

    existing_user = await get_user_by_email(user.email)

    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="User already exists",
        )

    hashed_password = get_password_hash(user.password)
    db_user = UserInDB(**user.dict(), hashed_password=hashed_password)

    await add_user(db_user)
    return User(**user.dict())
async def create_admin(user: UserCreate) -> User:
    """
    Accepts a UserCreate model which has role set as admin and returns a User
    """

    existing_user = await get_user_by_email(user.email)

    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="User already exists",
        )

    if user.role != UserRole.admin:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect role, expected student",
        )

    hashed_password = get_password_hash(user.password)
    db_user = UserInDB(**user.dict(), hashed_password=hashed_password)

    await add_user(db_user)
    return User(**user.dict())
async def get_user_by_email(email: EmailStr):
    user = await users_collection.find_one({"email": email})
    # TODO: not sure about error handling here
    if user:
        return UserInDB(**user)
    return False
async def get_user_by_id(id: UUID4):
    user = await users_collection.find_one({"id": id})
    # TODO: not sure about error handling here
    if user:
        return UserInDB(**user)
    return False
async def add_user(user: UserInDB):
    await users_collection.insert_one(user.dict())