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
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
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
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
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
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)
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}
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
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
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
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
def admin_user(): return User(account_id='admin', password='******', email='admin@admin')
def regular_user(): return User(account_id='a', password='******', email='a@a')
# 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"]):
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
async def insert_user(db, user: User): doc = await db.users.insert_one(user.dict()) return doc
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
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
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)