Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow users to bookmark variants and genes (#95) #173

Merged
merged 10 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions backend/alembic/versions/435a8e31682e_init_bookmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""empty message
gromdimon marked this conversation as resolved.
Show resolved Hide resolved

Revision ID: 435a8e31682e
Revises: 8ccd31a4f116
Create Date: 2023-10-23 18:44:22.900953+02:00

"""
import fastapi_users_db_sqlalchemy.generics # noqa
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = "435a8e31682e"
down_revision = "8ccd31a4f116"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"bookmarks",
sa.Column("id", fastapi_users_db_sqlalchemy.generics.GUID(), nullable=False),
sa.Column("user", sa.Uuid(), nullable=False),
gromdimon marked this conversation as resolved.
Show resolved Hide resolved
sa.Column(
"obj_type", sa.Enum("seqvar", "strucvar", "gene", name="bookmarktypes"), nullable=False
),
sa.Column("obj_id", sa.String(length=255), nullable=False),
sa.ForeignKeyConstraint(
["user"],
["user.id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("user", "obj_type", "obj_id", name="uq_bookmark"),
)
op.create_index(op.f("ix_bookmarks_id"), "bookmarks", ["id"], unique=False)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_bookmarks_id"), table_name="bookmarks")
op.drop_table("bookmarks")
# ### end Alembic commands ###
4 changes: 2 additions & 2 deletions backend/app/api/api_v1/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from fastapi import APIRouter
from httpx_oauth.clients.openid import OpenID
from httpx_oauth.errors import GetIdEmailError
from httpx_oauth.oauth2 import BaseOAuth2, OAuth2Error

from app.api.api_v1.endpoints import adminmsgs, auth
from app.api.api_v1.endpoints import adminmsgs, auth, bookmarks
from app.core.auth import auth_backend_bearer, auth_backend_cookie, fastapi_users
from app.core.config import settings
from app.schemas.user import UserRead, UserUpdate

api_router = APIRouter()
api_router.include_router(adminmsgs.router, prefix="/adminmsgs", tags=["adminmsgs"])
api_router.include_router(bookmarks.router, prefix="/bookmarks", tags=["bookmarks"])

api_router.include_router(
fastapi_users.get_auth_router(auth_backend_bearer), prefix="/auth/bearer", tags=["auth"]
Expand Down
2 changes: 1 addition & 1 deletion backend/app/api/api_v1/endpoints/adminmsgs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app import crud, models, schemas
from app import crud, schemas
from app.api import deps

router = APIRouter()
Expand Down
6 changes: 2 additions & 4 deletions backend/app/api/api_v1/endpoints/auth.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter

from app import crud, models, schemas
from app.api import deps
from app import schemas
from app.core import config

router = APIRouter()
Expand Down
154 changes: 154 additions & 0 deletions backend/app/api/api_v1/endpoints/bookmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from app import crud, schemas
from app.api import deps
from app.core import auth

router = APIRouter()


@router.post("/create", response_model=schemas.BookmarkCreate)
async def create_bookmark(
bookmark: schemas.BookmarkCreate, db: AsyncSession = Depends(deps.get_db)
):
"""
Create a new bookmark.

**Parameters**
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark
* **user**: user id of user who created the bookmark

**Response**
* **id**: id of the bookmark
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark
* **user**: user id of user who created the bookmark
"""
return await crud.bookmark.create(db, obj_in=bookmark)


@router.get("/list-all", response_model=list[schemas.BookmarkRead])
async def list_bookmarks(skip: int = 0, limit: int = 100, db: AsyncSession = Depends(deps.get_db)):
"""
List bookmarks. Available only for superusers.

**Parameters**
* **skip**: number of bookmarks to skip
* **limit**: maximum number of bookmarks to return

**Response**
* List of bookmarks
"""
user = auth.fastapi_users.current_user(active=True, superuser=True)
if user:
return await crud.bookmark.get_multi(db, skip=skip, limit=limit)
else:
raise HTTPException(status_code=403, detail="Not enough permissions")


@router.get("/get-by-id", response_model=schemas.BookmarkRead)
async def get_bookmark(id: str, db: AsyncSession = Depends(deps.get_db)):
"""
Get a bookmark by id. Available only for superusers.

**Parameters**
* **id**: id of the bookmark
gromdimon marked this conversation as resolved.
Show resolved Hide resolved

**Response**
* **id**: id of the bookmark
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark
* **user**: user id of user who created the bookmark
"""
user = auth.fastapi_users.current_user(active=True, superuser=True)
if user:
return await crud.bookmark.get(db, id=id)
else:
raise HTTPException(status_code=403, detail="Not enough permissions")


@router.delete("/delete-by-id", response_model=schemas.BookmarkRead)
async def delete_bookmark(id: str, db: AsyncSession = Depends(deps.get_db)):
"""
Delete a bookmark. Available only for superusers.

**Parameters**
* **id**: id of the bookmark

**Response**
* **id**: id of the bookmark
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark
* **user**: user id of user who created the bookmark
"""
user = auth.fastapi_users.current_user(active=True, superuser=True)
if user:
return await crud.bookmark.remove(db, id=id)
else:
raise HTTPException(status_code=403, detail="Not enough permissions")


@router.get("/list", response_model=list[schemas.BookmarkRead])
async def list_bookmarks_for_user(
user_id: str, skip: int = 0, limit: int = 100, db: AsyncSession = Depends(deps.get_db)
):
"""
List bookmarks for a user.

**Parameters**
* **user_id**: id of the user
* **skip**: number of bookmarks to skip
* **limit**: maximum number of bookmarks to return

**Response**
* List of bookmarks for the user
"""
return await crud.bookmark.get_multi_by_user(db, user_id=user_id, skip=skip, limit=limit)


@router.get("/get", response_model=schemas.BookmarkRead)
async def get_bookmark_for_user(
user_id: str, obj_type: str, obj_id: str, db: AsyncSession = Depends(deps.get_db)
):
"""
Get a bookmark for a user by obj_type and obj_id.

**Parameters**
* **user_id**: id of the user
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark

**Response**
* **id**: id of the bookmark
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark
* **user**: user id of user who created the bookmark
"""
return await crud.bookmark.get_by_user_and_obj(
db, user_id=user_id, obj_type=obj_type, obj_id=obj_id
)


@router.delete("/delete", response_model=schemas.BookmarkRead)
async def delete_bookmark_for_user(
user_id: str, obj_type: str, obj_id: str, db: AsyncSession = Depends(deps.get_db)
):
"""
Delete a bookmark for a user by obj_type and obj_id.

**Parameters**
* **user_id**: id of the user
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark

**Response**
* **id**: id of the bookmark
* **obj_type**: type of object to bookmark
* **obj_id**: id of object to bookmark
* **user**: user id of user who created the bookmark
"""
return await crud.bookmark.remove_by_user_and_obj(
db, user_id=user_id, obj_type=obj_type, obj_id=obj_id
)
2 changes: 1 addition & 1 deletion backend/app/core/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from fastapi_users_db_sqlalchemy import SQLAlchemyUserDatabase
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_async_session, get_db
from app.api.deps import get_async_session
from app.core.config import settings
from app.models.user import OAuthAccount, User

Expand Down
2 changes: 1 addition & 1 deletion backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import secrets
from typing import Any

from pydantic import AnyHttpUrl, BaseModel, EmailStr, HttpUrl, PostgresDsn, field_validator
from pydantic import AnyHttpUrl, EmailStr, HttpUrl, PostgresDsn, field_validator
from pydantic_core.core_schema import ValidationInfo
from pydantic_settings import BaseSettings, SettingsConfigDict

Expand Down
6 changes: 4 additions & 2 deletions backend/app/crud/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from typing import Any

from app.crud.base import CrudBase
from app.crud.bookmarks import CrudBookmark
from app.models.adminmsg import AdminMessage
from app.models.bookmark import Bookmark
from app.schemas.adminmsg import AdminMessageCreate, AdminMessageUpdate
from app.schemas.bookmark import BookmarkCreate, BookmarkUpdate

adminmessage = CrudBase[AdminMessage, AdminMessageCreate, AdminMessageUpdate](AdminMessage)
bookmark = CrudBookmark(Bookmark)
50 changes: 50 additions & 0 deletions backend/app/crud/bookmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from typing import Any, List

from sqlalchemy import and_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from app.crud.base import CrudBase
from app.models.bookmark import Bookmark
from app.schemas.bookmark import BookmarkCreate, BookmarkUpdate


class CrudBookmark(CrudBase[Bookmark, BookmarkCreate, BookmarkUpdate]):
async def get_multi_by_user(
self, session: AsyncSession, *, user_id: str, skip: int = 0, limit: int = 100
) -> List[Bookmark]:
query = (
select(self.model).filter(and_(self.model.user == user_id)).offset(skip).limit(limit)
)
result = await session.execute(query)
return result.scalars().all()

async def get_by_user_and_obj(
self, session: AsyncSession, *, user_id: str, obj_type: str, obj_id: str
) -> Bookmark:
query = select(self.model).filter(
and_(
self.model.user == user_id,
self.model.obj_type == obj_type,
self.model.obj_id == obj_id,
)
)
result = await session.execute(query)
return result.scalars().first()

async def remove_by_user_and_obj(
self, session: AsyncSession, *, user_id: str, obj_type: str, obj_id: str
) -> Bookmark:
gromdimon marked this conversation as resolved.
Show resolved Hide resolved
query = select(self.model).filter(
and_(
self.model.user == user_id,
self.model.obj_type == obj_type,
self.model.obj_id == obj_id,
)
)
result = await session.execute(query)
obj = result.scalars().first()
if obj:
await session.delete(obj)
await session.commit()
return obj
gromdimon marked this conversation as resolved.
Show resolved Hide resolved
1 change: 0 additions & 1 deletion backend/app/db/init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from app.api.deps import get_async_session
from app.core.auth import get_user_db, get_user_manager
from app.core.config import settings
from app.db.session import SessionLocal
from app.schemas import UserCreate

logging.basicConfig(level=logging.INFO)
Expand Down
3 changes: 1 addition & 2 deletions backend/app/db/session.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.orm import declarative_base

from app.core.config import settings

Expand Down
1 change: 1 addition & 0 deletions backend/app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from app.models.adminmsg import AdminMessage # noqa
from app.models.bookmark import Bookmark # noqa
from app.models.user import OAuthAccount, User # noqa
38 changes: 38 additions & 0 deletions backend/app/models/bookmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Models for bookmarks of variants and genes."""

import uuid as uuid_module
from typing import TYPE_CHECKING

from fastapi_users_db_sqlalchemy.generics import GUID # noqa
from sqlalchemy import Column, Enum, ForeignKey, String, UniqueConstraint, Uuid
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base
from app.schemas.bookmark import BookmarkTypes

UUID_ID = uuid_module.UUID


class Bookmark(Base):
"""Bookmark of a variant or gene."""

__tablename__ = "bookmarks"

__table_args__ = (UniqueConstraint("user", "obj_type", "obj_id", name="uq_bookmark"),)

if TYPE_CHECKING: # pragma: no cover
id: UUID_ID
user: UUID_ID
obj_type: BookmarkTypes
obj_id: str
else:
#: UUID of the bookmark.
id: Mapped[UUID_ID] = mapped_column(
GUID, primary_key=True, index=True, default=uuid_module.uuid4
)
#: User who created the bookmark.
user = Column(Uuid, ForeignKey("user.id"), nullable=False)
#: Type of the bookmarked object.
obj_type = Column(Enum(BookmarkTypes), nullable=False)
#: ID of the bookmarked object.
obj_id = Column(String(255), nullable=False)
1 change: 1 addition & 0 deletions backend/app/schemas/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from app.schemas.adminmsg import AdminMessageCreate, AdminMessageRead, AdminMessageUpdate # noqa
from app.schemas.auth import OAuth2ProviderConfig, OAuth2ProviderPublic # noqa
from app.schemas.bookmark import BookmarkCreate, BookmarkRead, BookmarkUpdate # noqa
from app.schemas.user import UserCreate, UserRead, UserUpdate # noqa
3 changes: 1 addition & 2 deletions backend/app/schemas/adminmsg.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ class AdminMessageUpdate(AdminMessageBase):
class AdminMessageInDbBase(AdminMessageBase):
model_config = ConfigDict(from_attributes=True)

id: int
uuid: UUID
id: UUID


class AdminMessageRead(AdminMessageInDbBase):
Expand Down
Loading
Loading