コード例 #1
0
async def get_by_email(con: AsyncIOConnection, *,
                       email: str) -> Optional[User]:
    try:
        result = await con.query_one_json(
            """SELECT User {
                id,
                email,
                full_name,
                is_superuser,
                is_active,
                num_items,
                items: {
                    id,
                    title
                }
            }
            FILTER .email = <str>$email""",
            email=email,
        )
    except NoDataError:
        return None
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"{e}")
    user = User.parse_raw(result)
    return user
コード例 #2
0
async def update(con: AsyncIOConnection, *, db_obj: User,
                 obj_in: UserUpdate) -> User:
    update_data = obj_in.dict(exclude_unset=True)
    if update_data.get("password"):
        hashed_password = get_password_hash(update_data["password"])
        del update_data["password"]
        update_data["hashed_password"] = hashed_password
    shape = ", ".join(
        [k + db.type_cast(update_data[k]) + k for k in update_data])
    try:
        result = await con.fetchone_json(
            f"""SELECT (
                UPDATE User
                FILTER .id = <uuid>$id
                SET {{ {shape} }}
            ) {{
                id,
                full_name,
                email,
                is_superuser,
                is_active,
                num_items := count(.<owner[IS Item]),
                items:= .<owner[IS Item] {{ id, title }}
            }}""",
            id=db_obj.id,
            **update_data,
        )
    except Exception as e:
        print(f"EXCEPTION: {e}")
    user = User.parse_raw(result)
    return user
コード例 #3
0
async def create(con: AsyncIOConnection, *, obj_in: UserCreate) -> User:
    try:
        result = await con.fetchone_json(
            """SELECT (
                INSERT User {
                    full_name := <str>$full_name,
                    email := <str>$email,
                    hashed_password := <str>$hashed_password,
                    is_superuser := <bool>$is_superuser,
                    is_active := <bool>$is_active
                }
            ) {
                id,
                full_name,
                email,
                is_superuser,
                is_active,
                num_items := count(.<owner[IS Item]),
                items:= .<owner[IS Item] { id, title }
            }""",
            full_name=obj_in.full_name,
            email=obj_in.email,
            hashed_password=get_password_hash(obj_in.password),
            is_superuser=obj_in.is_superuser,
            is_active=obj_in.is_active,
        )
    except Exception as e:
        print(f"EXCEPTION: {e}")
    user = User.parse_raw(result)
    return user
コード例 #4
0
async def create(con: AsyncIOConnection, *, obj_in: UserCreate) -> User:
    data_in = obj_in.dict(exclude_unset=True)
    if data_in.get("password"):
        data_in["hashed_password"] = get_password_hash(obj_in.password)
        del data_in["password"]
    shape_expr = utils.get_shape(data_in)
    try:
        result = await con.query_one_json(
            f"""SELECT (
                INSERT User {{
                    {shape_expr}
                }}
            ) {{
                id,
                email,
                full_name,
                is_superuser,
                is_active,
                num_items,
                items: {{
                    id,
                    title
                }}
            }}""",
            **data_in,
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"{e}")
    user = User.parse_raw(result)
    return user
コード例 #5
0
ファイル: user_utils.py プロジェクト: wixot/productz
def get_request_user(api_key):
    if api_key:
        flask_app = current_app._get_current_object()
        user = User.objects.filter(api_key=api_key).first()
    else:
        user = User.objects(id=current_user.id).first()

    return user
コード例 #6
0
def create_random_item(user: User, collection: Collection) -> Item:
    geometry = Point(random.random(), random.random())
    properties = {"name": random_lower_string()}
    item_in = ItemCreate(geometry=geometry, properties=properties)
    item = services.item.create_collection_item(InternalUserDTO(**user.dict()),
                                                collection.uuid,
                                                item_in.to_dto())
    return Item.from_dto(item)
コード例 #7
0
async def create_user(user: UserCreate) -> Dict:
    exists = dao.user.get_user_by_email(user.email)
    if exists:
        raise HTTPException(status_code=400,
                            detail="Email is taken, please use another.")
    ret = dao.user.add_user(user)
    new_user = User(id=ret.inserted_id,
                    name=user.name,
                    username=user.username,
                    email=user.email)
    return {'user': new_user}
コード例 #8
0
async def login(response: Response,
                user_login: RegisterUser = Depends(),
                db: Session = Depends(get_db)):
    """Endpoint for logging in that gives access_token"""
    user = await auth_user(db, user_login.username, user_login.password)
    if not user:
        raise HTTPException(status_code=406,
                            detail="Supplied wrong username or password")
    token = str(jwt.encode(User.from_orm(user).dict(), JWT_SECRET))
    access_token = {"access_token": token}
    response.set_cookie(key="access_token", value=token)
    await store_token(token)
    return access_token
コード例 #9
0
async def get(con: AsyncIOConnection, *, id: UUID) -> Optional[User]:
    try:
        result = await con.fetchone_json(
            """SELECT User {
                    id,
                    full_name,
                    email,
                    is_superuser,
                    is_active,
                    num_items := count(.<owner[IS Item]),
                    items:= .<owner[IS Item] { id, title }
            }
            FILTER .id = <uuid>$id""",
            id=id,
        )
    except NoDataError:
        return None
    except Exception as e:
        print(f"EXCEPTION: {e}")
    user = User.parse_raw(result)
    return user
コード例 #10
0
async def update(con: AsyncIOConnection, *, id: UUID,
                 obj_in: UserUpdate) -> Optional[User]:
    data_in = obj_in.dict(exclude_unset=True)
    if not data_in:
        user = await get(con, id=id)
        return user
    if data_in.get("password"):
        data_in["hashed_password"] = get_password_hash(
            obj_in.password)  # type: ignore
        del data_in["password"]
    shape_expr = utils.get_shape(data_in)
    try:
        result = await con.query_one_json(
            f"""SELECT (
                UPDATE User
                FILTER .id = <uuid>$id
                SET {{
                    {shape_expr}
                }}
                ) {{
                    id,
                    email,
                    full_name,
                    is_superuser,
                    is_active,
                    num_items,
                    items: {{
                        id,
                        title
                    }}
                }}""",
            id=id,
            **data_in,
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"{e}")
    user = User.parse_raw(result)
    return user
コード例 #11
0
async def remove(con: AsyncIOConnection, *, id: UUID) -> User:
    try:
        result = await con.query_one_json(
            """SELECT (
                DELETE User
                FILTER .id = <uuid>$id
            ) {
                id,
                email,
                full_name,
                is_superuser,
                is_active,
                num_items,
                items: {
                    id,
                    title
                }
            }""",
            id=id,
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"{e}")
    user = User.parse_raw(result)
    return user
コード例 #12
0
def admin_user():
    return User(account_id='admin', password='******', email='admin@admin')
コード例 #13
0
def regular_user():
    return User(account_id='a', password='******', email='a@a')
コード例 #14
0
        # Use transaction to make sure both user and wallet are created
        async with con.transaction():
            # Creating user
            user_id = await con.fetch_val(
                users.insert().values(user).returning(users.c.id))
            # Creating user wallet
            await con.execute(wallets.insert().values(user_id=user_id,
                                                      amount=0,
                                                      currency=wallet_currency)
                              )
            return json_response({})


@docs(tags=["auth"], summary="User authorization")
@request_schema(User(only=["login", "password"]))
async def login(request: web.Request):
    db: Database = request.app["db"]
    redis: Redis = request.app["redis"]
    user = request["data"]

    actual_user = await db.fetch_one(
        sa.select([users.c.id,
                   users.c.password]).where(users.c.login == user["login"]))

    # Login not found
    if not actual_user:
        return json_response({}, status=401)

    # Password is incorrect
    if not pbkdf2_sha256.verify(user["password"], actual_user["password"]):
コード例 #15
0
ファイル: users.py プロジェクト: xgkkdash/Meal-Recommender
async def update_user(db, user: User):
    old_doc = await db.users.find_one({"account_id": user.account_id})
    result = await db.users.replace_one({'_id': old_doc['_id']}, user.dict())
    return result
コード例 #16
0
ファイル: users.py プロジェクト: xgkkdash/Meal-Recommender
async def insert_user(db, user: User):
    doc = await db.users.insert_one(user.dict())
    return doc
コード例 #17
0
ファイル: users.py プロジェクト: xgkkdash/Meal-Recommender
async def find_user(db, user_id):
    doc = await db.users.find_one({"account_id": user_id})
    if doc:
        doc.pop("_id", None)
    return User(**doc) if doc else None
コード例 #18
0
ファイル: users.py プロジェクト: xgkkdash/Meal-Recommender
async def find_all_users(db):
    docs = [doc async for doc in db.users.find()]
    for doc in docs:
        doc.pop("_id", None)
    users = [User(**doc) for doc in docs]
    return users
コード例 #19
0
def create_random_collection(user: User) -> Collection:
    name = random_lower_string()
    collection_in = CollectionCreate(name=name, is_public=False)
    collection = services.collection.create_collection(
        InternalUserDTO(**user.dict()), collection_in.to_dto())
    return Collection.from_dto(collection)