Skip to content

Commit

Permalink
feat: Allow users to bookmark variants and genes (#95) (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
gromdimon authored Oct 27, 2023
1 parent a7e2853 commit 162ae13
Show file tree
Hide file tree
Showing 37 changed files with 1,084 additions and 31 deletions.
2 changes: 1 addition & 1 deletion backend/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ ci: \

.PHONY: docs
docs:
pipenv run -- make -C ../docs clean html
PYTHONPATH=$(PWD) pipenv run -- make -C ../docs clean html

.PHONY: serve
serve:
Expand Down
42 changes: 42 additions & 0 deletions backend/alembic/versions/27c3977494f7_init_bookmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""init bookmarks
Revision ID: 27c3977494f7
Revises: 8ccd31a4f116
Create Date: 2023-10-27 09:40:49.740067+02:00
"""
import fastapi_users_db_sqlalchemy.generics # noqa
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = "27c3977494f7"
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),
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"], ondelete="CASCADE"),
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
from app.models.user import User

router = APIRouter()

current_active_user = auth.fastapi_users.current_user(active=True)
current_superuser = auth.fastapi_users.current_user(active=True, superuser=True)


@router.post("/create", response_model=schemas.BookmarkCreate)
async def create_bookmark(
bookmark: schemas.BookmarkCreate,
db: AsyncSession = Depends(deps.get_db),
user: User = Depends(current_active_user),
):
"""
Create a new bookmark.
:param obj_type: type of object to bookmark
:type obj_type: str (enum) - "gene", "seqvar", "strucvar"
:param obj_id: id of object to bookmark
:type obj_id: uuid
:return: bookmark
:rtype: dict
"""
bookmark.user = user.id
return await crud.bookmark.create(db, obj_in=bookmark)


@router.get(
"/list-all",
dependencies=[Depends(current_superuser)],
response_model=list[schemas.BookmarkRead],
)
async def list_bookmarks(skip: int = 0, limit: int = 100, db: AsyncSession = Depends(deps.get_db)):
"""
List all bookmarks. Available only for superusers.
:param skip: number of bookmarks to skip
:type skip: int
:param limit: maximum number of bookmarks to return
:type limit: int
:return: list of bookmarks
:rtype: list
"""
return await crud.bookmark.get_multi(db, skip=skip, limit=limit)


@router.get(
"/get-by-id", dependencies=[Depends(current_superuser)], 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.
:param id: id of the bookmark
:type id: uuid
:return: bookmark
:rtype: dict
"""
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, dependencies=[Depends(current_superuser)]
)
async def delete_bookmark(id: str, db: AsyncSession = Depends(deps.get_db)):
"""
Delete a bookmark. Available for superusers and bookmark owners.
:param id: id of the bookmark
:type id: uuid
:return: bookmark which was deleted
:rtype: dict
"""
return await crud.bookmark.remove(db, id=id)


@router.get("/list", response_model=list[schemas.BookmarkRead])
async def list_bookmarks_for_user(
skip: int = 0,
limit: int = 100,
db: AsyncSession = Depends(deps.get_db),
user: User = Depends(current_active_user),
):
"""
List bookmarks for a current user.
:param skip: number of bookmarks to skip
:type skip: int
:param limit: maximum number of bookmarks to return
:type limit: int
:return: list of bookmarks
:rtype: list
"""
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(
obj_type: str,
obj_id: str,
db: AsyncSession = Depends(deps.get_db),
user: User = Depends(current_active_user),
):
"""
Get a bookmark for a current user by obj_type and obj_id.
:param obj_type: type of object to bookmark
:type obj_type: str (enum) - "gene", "seqvar", "strucvar"
:param obj_id: id of object to bookmark
:type obj_id: uuid
:return: bookmark
:rtype: dict
"""
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(
obj_type: str,
obj_id: str,
db: AsyncSession = Depends(deps.get_db),
user: User = Depends(current_active_user),
):
"""
Delete a bookmark for a current user by obj_type and obj_id.
:param obj_type: type of object to bookmark
:type obj_type: str (enum) - "gene", "seqvar", "strucvar"
:param obj_id: id of object to bookmark
:type obj_id: uuid
:return: bookmark which was deleted
:rtype: dict
:raises HTTPException: if bookmark not found
"""
bookmark = await crud.bookmark.get_by_user_and_obj(
db, user_id=user.id, obj_type=obj_type, obj_id=obj_id
)
if bookmark:
return await crud.bookmark.remove(db, id=bookmark.id)
else:
raise HTTPException(status_code=404, detail="Bookmark not found")
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)
27 changes: 27 additions & 0 deletions backend/app/crud/bookmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import Any, Sequence

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: Any, skip: int = 0, limit: int = 100
) -> Sequence[Bookmark]:
query = select(self.model).filter(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: Any, obj_type: Any, obj_id: Any
) -> Bookmark | None:
query = select(self.model).filter(
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()
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", ondelete="CASCADE"), 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

0 comments on commit 162ae13

Please sign in to comment.