diff --git a/app/__init__.py b/app/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/app/__pycache__/__init__.cpython-311.pyc b/app/__pycache__/__init__.cpython-311.pyc deleted file mode 100644 index 3fe059aef479293274c0cc30340847029fbcd85d..0000000000000000000000000000000000000000 Binary files a/app/__pycache__/__init__.cpython-311.pyc and /dev/null differ diff --git a/app/__pycache__/__init__.cpython-312.pyc b/app/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 68547f5d7ef9e0e455c8027a6013b28d1715ea6f..0000000000000000000000000000000000000000 Binary files a/app/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/__pycache__/main.cpython-311.pyc b/app/__pycache__/main.cpython-311.pyc deleted file mode 100644 index 491fc32cd112dce1ae24c4a65ceea536f705377b..0000000000000000000000000000000000000000 Binary files a/app/__pycache__/main.cpython-311.pyc and /dev/null differ diff --git a/app/__pycache__/main.cpython-312.pyc b/app/__pycache__/main.cpython-312.pyc deleted file mode 100644 index a90b423981920f1ede9c74d8f8f54fed53db4a25..0000000000000000000000000000000000000000 Binary files a/app/__pycache__/main.cpython-312.pyc and /dev/null differ diff --git a/app/alembic.ini b/app/alembic.ini deleted file mode 100644 index d17e9a1b6edf60ecf51c95ef14b15f82b691d548..0000000000000000000000000000000000000000 --- a/app/alembic.ini +++ /dev/null @@ -1,117 +0,0 @@ -# A generic, single database configuration. - -[alembic] -# path to migration scripts -# Use forward slashes (/) also on windows to provide an os agnostic path -script_location = alembic - -# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s -# Uncomment the line below if you want the files to be prepended with date and time -# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file -# for all available tokens -# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s - -# sys.path path, will be prepended to sys.path if present. -# defaults to the current working directory. -prepend_sys_path = . - -# timezone to use when rendering the date within the migration file -# as well as the filename. -# If specified, requires the python>=3.9 or backports.zoneinfo library. -# Any required deps can installed by adding `alembic[tz]` to the pip requirements -# string value is passed to ZoneInfo() -# leave blank for localtime -# timezone = - -# max length of characters to apply to the "slug" field -# truncate_slug_length = 40 - -# set to 'true' to run the environment during -# the 'revision' command, regardless of autogenerate -# revision_environment = false - -# set to 'true' to allow .pyc and .pyo files without -# a source .py file to be detected as revisions in the -# versions/ directory -# sourceless = false - -# version location specification; This defaults -# to alembic/versions. When using multiple version -# directories, initial revisions must be specified with --version-path. -# The path separator used here should be the separator specified by "version_path_separator" below. -# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions - -# version path separator; As mentioned above, this is the character used to split -# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. -# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. -# Valid values for version_path_separator are: -# -# version_path_separator = : -# version_path_separator = ; -# version_path_separator = space -# version_path_separator = newline -version_path_separator = os # Use os.pathsep. Default configuration used for new projects. - -# set to 'true' to search source files recursively -# in each "version_locations" directory -# new in Alembic version 1.10 -# recursive_version_locations = false - -# the output encoding used when revision files -# are written from script.py.mako -# output_encoding = utf-8 - -sqlalchemy.url = driver://user:pass@localhost/dbname - - -[post_write_hooks] -# post_write_hooks defines scripts or Python functions that are run -# on newly generated revision scripts. See the documentation for further -# detail and examples - -# format using "black" - use the console_scripts runner, against the "black" entrypoint -# hooks = black -# black.type = console_scripts -# black.entrypoint = black -# black.options = -l 79 REVISION_SCRIPT_FILENAME - -# lint with attempts to fix using "ruff" - use the exec runner, execute a binary -# hooks = ruff -# ruff.type = exec -# ruff.executable = %(here)s/.venv/bin/ruff -# ruff.options = --fix REVISION_SCRIPT_FILENAME - -# Logging configuration -[loggers] -keys = root,sqlalchemy,alembic - -[handlers] -keys = console - -[formatters] -keys = generic - -[logger_root] -level = WARN -handlers = console -qualname = - -[logger_sqlalchemy] -level = WARN -handlers = -qualname = sqlalchemy.engine - -[logger_alembic] -level = INFO -handlers = -qualname = alembic - -[handler_console] -class = StreamHandler -args = (sys.stderr,) -level = NOTSET -formatter = generic - -[formatter_generic] -format = %(levelname)-5.5s [%(name)s] %(message)s -datefmt = %H:%M:%S diff --git a/app/alembic/README b/app/alembic/README deleted file mode 100644 index 98e4f9c44effe479ed38c66ba922e7bcc672916f..0000000000000000000000000000000000000000 --- a/app/alembic/README +++ /dev/null @@ -1 +0,0 @@ -Generic single-database configuration. \ No newline at end of file diff --git a/app/alembic/__pycache__/env.cpython-312.pyc b/app/alembic/__pycache__/env.cpython-312.pyc deleted file mode 100644 index b7cc21c667f2a0916c5f58c89925280fc92c1ee0..0000000000000000000000000000000000000000 Binary files a/app/alembic/__pycache__/env.cpython-312.pyc and /dev/null differ diff --git a/app/alembic/env.py b/app/alembic/env.py deleted file mode 100644 index 8c130ca5990fdda37b7fabcb7acc098335a879d1..0000000000000000000000000000000000000000 --- a/app/alembic/env.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -from logging.config import fileConfig - -from dotenv import load_dotenv - -from sqlalchemy import engine_from_config -from sqlalchemy import pool -from sqlmodel import SQLModel - -from alembic import context - -from models import Poll, PollOption, Vote, RollRange - -load_dotenv() -# this is the Alembic Config object, which provides -# access to the values within the .ini file in use. -config = context.config -config.set_main_option( - "sqlalchemy.url", - f"{os.environ['DATABASE_URL']}", -) - -# Interpret the config file for Python logging. -# This line sets up loggers basically. -if config.config_file_name is not None: - fileConfig(config.config_file_name) - -# add your model's MetaData object here -# for 'autogenerate' support -# from myapp import mymodel -# target_metadata = mymodel.Base.metadata -target_metadata = SQLModel.metadata - -# other values from the config, defined by the needs of env.py, -# can be acquired: -# my_important_option = config.get_main_option("my_important_option") -# ... etc. - - -def run_migrations_offline() -> None: - """Run migrations in 'offline' mode. - - This configures the context with just a URL - and not an Engine, though an Engine is acceptable - here as well. By skipping the Engine creation - we don't even need a DBAPI to be available. - - Calls to context.execute() here emit the given string to the - script output. - - """ - url = config.get_main_option("sqlalchemy.url") - context.configure( - url=url, - target_metadata=target_metadata, - literal_binds=True, - dialect_opts={"paramstyle": "named"}, - ) - - with context.begin_transaction(): - context.run_migrations() - - -def run_migrations_online() -> None: - """Run migrations in 'online' mode. - - In this scenario we need to create an Engine - and associate a connection with the context. - - """ - connectable = engine_from_config( - config.get_section(config.config_ini_section, {}), - prefix="sqlalchemy.", - poolclass=pool.NullPool, - ) - - with connectable.connect() as connection: - context.configure( - connection=connection, target_metadata=target_metadata - ) - - with context.begin_transaction(): - context.run_migrations() - - -if context.is_offline_mode(): - run_migrations_offline() -else: - run_migrations_online() diff --git a/app/alembic/script.py.mako b/app/alembic/script.py.mako deleted file mode 100644 index 6ce3351093cfb7fbe7c9c68943d7a14e954845ad..0000000000000000000000000000000000000000 --- a/app/alembic/script.py.mako +++ /dev/null @@ -1,27 +0,0 @@ -"""${message} - -Revision ID: ${up_revision} -Revises: ${down_revision | comma,n} -Create Date: ${create_date} - -""" -from typing import Sequence, Union - -from alembic import op -import sqlalchemy as sa -import sqlmodel -${imports if imports else ""} - -# revision identifiers, used by Alembic. -revision: str = ${repr(up_revision)} -down_revision: Union[str, None] = ${repr(down_revision)} -branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} -depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} - - -def upgrade() -> None: - ${upgrades if upgrades else "pass"} - - -def downgrade() -> None: - ${downgrades if downgrades else "pass"} diff --git a/app/alembic/versions/2d970db44571_.py b/app/alembic/versions/2d970db44571_.py deleted file mode 100644 index a76bd9f41f9e43c00a69dce5adcdcaf323f745da..0000000000000000000000000000000000000000 --- a/app/alembic/versions/2d970db44571_.py +++ /dev/null @@ -1,33 +0,0 @@ -"""empty message - -Revision ID: 2d970db44571 -Revises: 4a25da80a496 -Create Date: 2024-10-11 22:59:38.796430 - -""" -from typing import Sequence, Union - -from alembic import op -import sqlalchemy as sa -import sqlmodel - - -# revision identifiers, used by Alembic. -revision: str = '2d970db44571' -down_revision: Union[str, None] = '4a25da80a496' -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - - -def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('polloption', 'total_votes') - op.create_index(op.f('ix_vote_option_id'), 'vote', ['option_id'], unique=False) - # ### end Alembic commands ### - - -def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_vote_option_id'), table_name='vote') - op.add_column('polloption', sa.Column('total_votes', sa.INTEGER(), autoincrement=False, nullable=False)) - # ### end Alembic commands ### diff --git a/app/alembic/versions/4a25da80a496_initial_migration.py b/app/alembic/versions/4a25da80a496_initial_migration.py deleted file mode 100644 index 6463aa3f258455bd1315417ae3e104d6d7a8a090..0000000000000000000000000000000000000000 --- a/app/alembic/versions/4a25da80a496_initial_migration.py +++ /dev/null @@ -1,70 +0,0 @@ -"""initial migration - -Revision ID: 4a25da80a496 -Revises: -Create Date: 2024-10-11 16:31:22.565721 - -""" -from typing import Sequence, Union - -from alembic import op -import sqlalchemy as sa -import sqlmodel - - -# revision identifiers, used by Alembic. -revision: str = '4a25da80a496' -down_revision: Union[str, None] = None -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - - -def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('poll', - sa.Column('id', sa.Uuid(), nullable=False), - sa.Column('title', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False), - sa.Column('description', sqlmodel.sql.sqltypes.AutoString(length=1024), nullable=False), - sa.Column('is_private', sa.Boolean(), nullable=False), - sa.Column('created_at', sa.DateTime(), nullable=False), - sa.Column('creator_email', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False), - sa.Column('start_time', sa.DateTime(), nullable=False), - sa.Column('end_time', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('polloption', - sa.Column('id', sa.Uuid(), nullable=False), - sa.Column('poll_id', sa.Uuid(), nullable=False), - sa.Column('option_text', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False), - sa.Column('total_votes', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['poll_id'], ['poll.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('rollrange', - sa.Column('id', sa.Uuid(), nullable=False), - sa.Column('start', sa.Integer(), nullable=False), - sa.Column('end', sa.Integer(), nullable=False), - sa.Column('poll_id', sa.Uuid(), nullable=False), - sa.ForeignKeyConstraint(['poll_id'], ['poll.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('vote', - sa.Column('id', sa.Uuid(), nullable=False), - sa.Column('option_id', sa.Uuid(), nullable=False), - sa.Column('voter_email_hash', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False), - sa.Column('timestamp', sa.DateTime(), nullable=False), - sa.ForeignKeyConstraint(['option_id'], ['polloption.id'], ondelete='CASCADE'), - sa.PrimaryKeyConstraint('id') - ) - op.create_index(op.f('ix_vote_id'), 'vote', ['id'], unique=False) - # ### end Alembic commands ### - - -def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_vote_id'), table_name='vote') - op.drop_table('vote') - op.drop_table('rollrange') - op.drop_table('polloption') - op.drop_table('poll') - # ### end Alembic commands ### diff --git a/app/alembic/versions/4c9cd9554f1c_timezone_utc.py b/app/alembic/versions/4c9cd9554f1c_timezone_utc.py deleted file mode 100644 index e49f841615a36843e4296a5e3e11ae28221dafc0..0000000000000000000000000000000000000000 --- a/app/alembic/versions/4c9cd9554f1c_timezone_utc.py +++ /dev/null @@ -1,61 +0,0 @@ -"""timezone utc - -Revision ID: 4c9cd9554f1c -Revises: 2d970db44571 -Create Date: 2024-10-16 00:30:26.544361 - -""" -from typing import Sequence, Union - -from alembic import op -import sqlalchemy as sa -import sqlmodel -from sqlalchemy.dialects import postgresql - -# revision identifiers, used by Alembic. -revision: str = '4c9cd9554f1c' -down_revision: Union[str, None] = '2d970db44571' -branch_labels: Union[str, Sequence[str], None] = None -depends_on: Union[str, Sequence[str], None] = None - - -def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('poll', 'created_at', - existing_type=postgresql.TIMESTAMP(timezone=True), - type_=sa.DateTime(), - existing_nullable=False) - op.alter_column('poll', 'start_time', - existing_type=postgresql.TIMESTAMP(timezone=True), - type_=sa.DateTime(), - existing_nullable=False) - op.alter_column('poll', 'end_time', - existing_type=postgresql.TIMESTAMP(timezone=True), - type_=sa.DateTime(), - existing_nullable=False) - op.alter_column('vote', 'timestamp', - existing_type=postgresql.TIMESTAMP(timezone=True), - type_=sa.DateTime(), - existing_nullable=False) - # ### end Alembic commands ### - - -def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('vote', 'timestamp', - existing_type=sa.DateTime(), - type_=postgresql.TIMESTAMP(timezone=True), - existing_nullable=False) - op.alter_column('poll', 'end_time', - existing_type=sa.DateTime(), - type_=postgresql.TIMESTAMP(timezone=True), - existing_nullable=False) - op.alter_column('poll', 'start_time', - existing_type=sa.DateTime(), - type_=postgresql.TIMESTAMP(timezone=True), - existing_nullable=False) - op.alter_column('poll', 'created_at', - existing_type=sa.DateTime(), - type_=postgresql.TIMESTAMP(timezone=True), - existing_nullable=False) - # ### end Alembic commands ### diff --git a/app/alembic/versions/__pycache__/2d970db44571_.cpython-312.pyc b/app/alembic/versions/__pycache__/2d970db44571_.cpython-312.pyc deleted file mode 100644 index 28b2e52d4a77b1cd15fc2ddfb71ef4fcff46be49..0000000000000000000000000000000000000000 Binary files a/app/alembic/versions/__pycache__/2d970db44571_.cpython-312.pyc and /dev/null differ diff --git a/app/alembic/versions/__pycache__/4a25da80a496_initial_migration.cpython-312.pyc b/app/alembic/versions/__pycache__/4a25da80a496_initial_migration.cpython-312.pyc deleted file mode 100644 index adf25e0b01df998cc5ff77c6c08d8953cf6ec44d..0000000000000000000000000000000000000000 Binary files a/app/alembic/versions/__pycache__/4a25da80a496_initial_migration.cpython-312.pyc and /dev/null differ diff --git a/app/alembic/versions/__pycache__/4c9cd9554f1c_timezone_utc.cpython-312.pyc b/app/alembic/versions/__pycache__/4c9cd9554f1c_timezone_utc.cpython-312.pyc deleted file mode 100644 index 797a0ae17639b434f228f53141a3b307e177fe57..0000000000000000000000000000000000000000 Binary files a/app/alembic/versions/__pycache__/4c9cd9554f1c_timezone_utc.cpython-312.pyc and /dev/null differ diff --git a/app/api/__init__.py b/app/api/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/app/api/__pycache__/__init__.cpython-312.pyc b/app/api/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 67cde0413245beb36529b5f9b4ab053b09328b29..0000000000000000000000000000000000000000 Binary files a/app/api/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/api/__pycache__/deps.cpython-312.pyc b/app/api/__pycache__/deps.cpython-312.pyc deleted file mode 100644 index a8d728f33b9de6688711dfe3b26ee5de00879369..0000000000000000000000000000000000000000 Binary files a/app/api/__pycache__/deps.cpython-312.pyc and /dev/null differ diff --git a/app/api/__pycache__/main.cpython-312.pyc b/app/api/__pycache__/main.cpython-312.pyc deleted file mode 100644 index 6d997bb92a18008e607978a6b9935a6499f3f490..0000000000000000000000000000000000000000 Binary files a/app/api/__pycache__/main.cpython-312.pyc and /dev/null differ diff --git a/app/api/__pycache__/poll.cpython-312.pyc b/app/api/__pycache__/poll.cpython-312.pyc deleted file mode 100644 index 243f1cccc33e6a607a89660be5754e0bd297e46d..0000000000000000000000000000000000000000 Binary files a/app/api/__pycache__/poll.cpython-312.pyc and /dev/null differ diff --git a/app/api/__pycache__/vote.cpython-312.pyc b/app/api/__pycache__/vote.cpython-312.pyc deleted file mode 100644 index 073c202277123ab8677e48c67dd5abef5d91a299..0000000000000000000000000000000000000000 Binary files a/app/api/__pycache__/vote.cpython-312.pyc and /dev/null differ diff --git a/app/api/deps.py b/app/api/deps.py deleted file mode 100644 index 0a8092854d4b8cb5dd7ea6745a1d0ed0aeb32f6f..0000000000000000000000000000000000000000 --- a/app/api/deps.py +++ /dev/null @@ -1,60 +0,0 @@ -from collections.abc import Generator -from typing import Annotated - -import jwt -from fastapi import Depends, HTTPException, status -from fastapi.security import HTTPBearer -from sqlmodel import Session - -from core.db import engine -from core.config import settings -from core import security -from models.common import AuthUser -from utils.email_validator import is_valid_cuet_email - - -httpBearer = HTTPBearer() - - -def get_db() -> Generator[Session, None, None]: - with Session(engine) as session: - yield session - - -SessionDep = Annotated[Session, Depends(get_db)] -TokenDep = Annotated[str, Depends(httpBearer)] - - -def get_current_user(session: SessionDep, token: TokenDep): - try: - payload = jwt.decode( - token.credentials, - settings.SECRET_KEY, - algorithms=[security.ALGORITHM], - audience=settings.AUDIENCE, - ) - - if not is_valid_cuet_email(payload.get("email")): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Must be a CUET-student email") - - return AuthUser( - email=payload.get("email"), - full_name=" ".join(payload.get( - "user_metadata").get("full_name").split()[:2]), - roll=payload.get("email")[1:8], - avatar_url=payload.get("user_metadata").get("avatar_url") - ) - - except jwt.ExpiredSignatureError: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired") - except jwt.InvalidTokenError: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") - except Exception as e: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid authentication credentials. {e}") - - -CurrentUser = Annotated[AuthUser, Depends(get_current_user)] diff --git a/app/api/main.py b/app/api/main.py deleted file mode 100644 index e1305708cc2c5eeb73f12d333b2d4fb97ac90343..0000000000000000000000000000000000000000 --- a/app/api/main.py +++ /dev/null @@ -1,7 +0,0 @@ -from fastapi import APIRouter -from api.routes import poll, vote, user - -api_router = APIRouter() -api_router.include_router(poll.router, prefix="/polls", tags=["polls"]) -api_router.include_router(vote.router, prefix="/votes", tags=["votes"]) -api_router.include_router(user.router, prefix="/users", tags=["users"]) diff --git a/app/api/routes/__init__.py b/app/api/routes/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/app/api/routes/__pycache__/__init__.cpython-312.pyc b/app/api/routes/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 259d35c858ce27006f25ee5132c4b029c9698f82..0000000000000000000000000000000000000000 Binary files a/app/api/routes/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/api/routes/__pycache__/auth.cpython-312.pyc b/app/api/routes/__pycache__/auth.cpython-312.pyc deleted file mode 100644 index 7d024ab1e423e40a7dca7bab71e73495857fabdf..0000000000000000000000000000000000000000 Binary files a/app/api/routes/__pycache__/auth.cpython-312.pyc and /dev/null differ diff --git a/app/api/routes/__pycache__/poll.cpython-312.pyc b/app/api/routes/__pycache__/poll.cpython-312.pyc deleted file mode 100644 index 6e74879ae42d326dd814984281cc1d9af41ff3d7..0000000000000000000000000000000000000000 Binary files a/app/api/routes/__pycache__/poll.cpython-312.pyc and /dev/null differ diff --git a/app/api/routes/__pycache__/user.cpython-312.pyc b/app/api/routes/__pycache__/user.cpython-312.pyc deleted file mode 100644 index 3c122abdcac3251cbdf6685e30c3a1d8aa26f9ed..0000000000000000000000000000000000000000 Binary files a/app/api/routes/__pycache__/user.cpython-312.pyc and /dev/null differ diff --git a/app/api/routes/__pycache__/vote.cpython-312.pyc b/app/api/routes/__pycache__/vote.cpython-312.pyc deleted file mode 100644 index ca16e1820169078c179beda0012896583099522a..0000000000000000000000000000000000000000 Binary files a/app/api/routes/__pycache__/vote.cpython-312.pyc and /dev/null differ diff --git a/app/api/routes/poll.py b/app/api/routes/poll.py deleted file mode 100644 index 0854ca44fb0fbabf596aabdd0e2ae7bcccd1c3d7..0000000000000000000000000000000000000000 --- a/app/api/routes/poll.py +++ /dev/null @@ -1,429 +0,0 @@ -from datetime import datetime, timezone -from fastapi import APIRouter, HTTPException, status -from sqlmodel import select, func -from sqlalchemy.orm import subqueryload -from sqlalchemy.sql import or_, and_ -from uuid import UUID - -from api.deps import SessionDep, CurrentUser -from core.security import hash_email -from models.common import Message -from models.poll import ( - Poll, - PollCreate, - PollCreateResponse, - PollOption, - PollOptions, - PollOptionsCreate, - PollResponse, - PollsResponse, - PollOptionResult, - PollResult, - RollRange, - RollRanges, - RollRangesCreate, -) -from models.vote import Vote - - -router = APIRouter() - - -def _serialize_poll_public(poll, total_votes, selected_option) -> PollResponse: - return PollResponse( - id=poll.id, - title=poll.title, - description=poll.description, - is_private=poll.is_private, - creator_email=poll.creator_email, - created_at=poll.created_at, - start_time=poll.start_time, - end_time=poll.end_time, - options=poll.options, - selected_option=selected_option, - total_votes=total_votes, - roll_ranges=poll.roll_ranges - ) - - -def _get_polls(user, session, skip, limit, search, where_clause, order_by_clause=None) -> PollsResponse: - """Get polls based on query parameters.""" - vote_count_subquery = ( - select(PollOption.poll_id, func.count(Vote.id).label('total_votes')) - .join(Vote, Vote.option_id == PollOption.id, isouter=True) - .group_by(PollOption.poll_id) - .subquery() - ) - - selected_option_subquery = ( - select(Vote.option_id, PollOption.poll_id) - .join(PollOption, PollOption.id == Vote.option_id) - .where(Vote.voter_email_hash == hash_email(user.email) if user else None) - .subquery() - ) - - query = ( - select(Poll, vote_count_subquery.c.total_votes, selected_option_subquery.c.option_id.label('selected_option'), - func.count().over().label('total_count')) - .join(vote_count_subquery, vote_count_subquery.c.poll_id == Poll.id, isouter=True) - .join(selected_option_subquery, selected_option_subquery.c.poll_id == Poll.id, isouter=True) - .where(where_clause) - .options( - subqueryload(Poll.options), - subqueryload(Poll.roll_ranges) - ) - .order_by(func.coalesce(vote_count_subquery.c.total_votes, 0).desc() if order_by_clause is None else order_by_clause) - .offset(skip) - .limit(limit) - ) - - if search: - search = f"%{search}%" - query = query.where( - or_(Poll.title.ilike(search), Poll.description.ilike(search)) - ) - - polls = session.exec(query).unique().all() - total_count = polls[0][3] if polls else 0 - - data = [ - _serialize_poll_public(poll, total_votes or 0, - session.exec( - select(PollOption) - .where(PollOption.id == selected_option)).first() - ) - for poll, total_votes, selected_option, _ in polls - ] - - return PollsResponse(data=data, count=total_count) - - -@ router.get("/", response_model=PollsResponse) -def get_polls(user: CurrentUser, session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all polls.""" - polls = _get_polls( - user=user, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=or_( - Poll.is_private.is_(False), - Poll.creator_email == user.email, - Poll.roll_ranges.any( - and_(RollRange.start <= user.roll, RollRange.end >= user.roll) - ), - ), - order_by_clause=Poll.created_at.desc() - ) - return polls - - -@ router.get("/public", response_model=PollsResponse) -def get_public_polls(session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all public polls.""" - polls = _get_polls( - user=None, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=Poll.is_private.is_(False), - order_by_clause=Poll.created_at.desc() - ) - return polls - - -@ router.get("/my-polls", response_model=PollsResponse) -def get_my_polls(user: CurrentUser, session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all polls created by the user.""" - polls = _get_polls( - user=user, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=Poll.creator_email == user.email, - order_by_clause=Poll.created_at.desc() - ) - return polls - - -@ router.get("/allowed-polls", response_model=PollsResponse) -def get_allowed_polls(user: CurrentUser, session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all polls allowed for the user.""" - polls = _get_polls( - user=user, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=or_( - Poll.is_private.is_(False), - Poll.creator_email == user.email, - Poll.roll_ranges.any( - and_(RollRange.start <= user.roll, RollRange.end >= user.roll) - ) - ), - order_by_clause=Poll.created_at.desc() - ) - return polls - - -@ router.get("/popular-polls", response_model=PollsResponse) -def get_popular_polls(user: CurrentUser, session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all popular polls.""" - polls = _get_polls( - user=user, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=or_( - Poll.is_private.is_(False), - Poll.creator_email == user.email, - Poll.roll_ranges.any( - and_(RollRange.start <= user.roll, RollRange.end >= user.roll) - ), - ), - ) - return polls - - -@ router.get("/upcoming-polls", response_model=PollsResponse) -def get_upcoming_polls(user: CurrentUser, session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all upcoming polls.""" - polls = _get_polls( - user=user, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=and_( - Poll.start_time > datetime.now(timezone.utc), - or_( - Poll.is_private.is_(False), - Poll.creator_email == user.email, - Poll.roll_ranges.any( - and_(RollRange.start <= user.roll, RollRange.end >= user.roll)) - ) - ), - order_by_clause=Poll.start_time.asc() - ) - return polls - - -@ router.get("/ended-polls/", response_model=PollsResponse) -def get_ended_polls(user: CurrentUser, session: SessionDep, skip: int = 0, limit: int = 20, search: str = None): - """Get all ended polls.""" - polls = _get_polls( - user=user, - session=session, - skip=skip, - limit=limit, - search=search, - where_clause=and_( - Poll.end_time < datetime.now(timezone.utc), - or_( - Poll.is_private.is_(False), - Poll.creator_email == user.email, - Poll.roll_ranges.any( - and_(RollRange.start <= user.roll, RollRange.end >= user.roll)) - ) - ), - order_by_clause=Poll.end_time.desc() - ) - return polls - - -@ router.post("/create/", response_model=PollCreateResponse) -def create_poll(request: PollCreate, user: CurrentUser, session: SessionDep): - """Create a new poll.""" - poll = Poll( - title=request.title, - description=request.description, - is_private=request.is_private, - creator_email=user.email, - start_time=request.start_time, - end_time=request.end_time, - ) - - session.add(poll) - session.commit() - session.refresh(poll) - return PollCreateResponse(poll_id=poll.id) - - -@ router.get("/{poll_id}", response_model=PollResponse) -def get_poll(poll_id: UUID, user: CurrentUser, session: SessionDep): - """Get a poll by its ID.""" - poll_with_votes = session.exec( - select(Poll, func.coalesce(func.count(Vote.id), 0).label('total_votes')) - .outerjoin(PollOption, PollOption.poll_id == Poll.id) - .outerjoin(Vote, Vote.option_id == PollOption.id) - .where(Poll.id == poll_id) - .group_by(Poll.id) - ).first() - - if not poll_with_votes: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="Poll not found") - - poll, total_votes = poll_with_votes - - if poll.is_private and poll.creator_email != user.email and not any(roll_range.start <= user.roll <= roll_range.end for roll_range in poll.roll_ranges): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to view this poll") - - selected_option = session.exec( - select(PollOption) - .join(Vote, Vote.option_id == PollOption.id) - .where(Vote.voter_email_hash == hash_email(user.email), PollOption.poll_id == poll_id) - ).first() - - return _serialize_poll_public(poll, total_votes, selected_option) - - -@ router.delete("/{poll_id}", response_model=Message) -def delete_poll(poll_id: UUID, user: CurrentUser, session: SessionDep): - """Delete a poll by its ID.""" - poll = session.get(Poll, poll_id) - if not poll: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="Poll not found") - - if poll.creator_email != user.email: - raise HTTPException( - status_code=403, detail="You are not authorized to delete this poll") - session.delete(poll) - session.commit() - return Message(message="Poll deleted successfully") - - -@ router.get("/{poll_id}/options", response_model=PollOptions) -def get_poll_options(poll_id: UUID, user: CurrentUser, session: SessionDep): - """Get all options of a poll by its ID.""" - poll = session.get(Poll, poll_id) - if not poll: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="Poll not found") - - if poll.is_private and poll.creator_email != user.email and not any(roll_range.start <= user.roll <= roll_range.end for roll_range in poll.roll_ranges): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to view this poll") - - return PollOptions(data=poll.options, count=len(poll.options)) - - -@ router.get("/{poll_id}/roll-ranges", response_model=RollRanges) -def get_roll_ranges(poll_id: UUID, user: CurrentUser, session: SessionDep): - """Get all roll ranges of a poll by its ID.""" - poll = session.get(Poll, poll_id) - if not poll: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="Poll not found") - - if poll.is_private and poll.creator_email != user.email and not any(roll_range.start <= user.roll <= roll_range.end for roll_range in poll.roll_ranges): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to view this poll") - - return RollRanges(data=poll.roll_ranges, count=len(poll.roll_ranges)) - - -@ router.post("/{poll_id}/options", response_model=Message) -def create_poll_option(poll_id: UUID, request: PollOptionsCreate, user: CurrentUser, session: SessionDep): - """Create new poll options of a poll with poll_id.""" - poll = session.get(Poll, poll_id) - - if not poll: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="Poll not found") - - if poll.creator_email != user.email: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to add options to this poll") - - option_texts = request.option_texts - if len(option_texts) < 2: - raise HTTPException( - status_code=400, detail="At least two options is required") - if len(option_texts) + len(poll.options) > 20: - raise HTTPException( - status_code=400, detail="A poll can have at most 20 options") - if len(option_texts) + len(poll.options) != len(set(option_texts + [option.option_text for option in poll.options])): - raise HTTPException( - status_code=400, detail="Options must be unique") - - options = [PollOption(poll_id=poll_id, option_text=option_text) - for option_text in option_texts] - session.add_all(options) - session.commit() - for option in options: - session.refresh(option) - return Message(message="Options added successfully") - - -@ router.post("/{poll_id}/roll-ranges", response_model=Message) -def add_allowed_voters(poll_id: UUID, request: RollRangesCreate, user: CurrentUser, session: SessionDep): - poll = session.get(Poll, poll_id) - if not poll: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="Poll not found") - if poll.creator_email != user.email: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to add roll ranges to this poll") - - roll_ranges = request.roll_ranges - if len(roll_ranges) == 0: - raise HTTPException( - status_code=400, detail="At least one roll range is required") - if len(roll_ranges) + len(poll.roll_ranges) > 20: - raise HTTPException( - status_code=400, detail="A poll can have at most 20 roll ranges") - if len(roll_ranges) + len(poll.roll_ranges) != len(set(roll_ranges + [(roll_range.start, roll_range.end) - for roll_range in poll.roll_ranges])): - raise HTTPException( - status_code=400, detail="Roll ranges must be unique") - - roll_ranges = [RollRange(poll_id=poll_id, start=start, end=end) - for start, end in roll_ranges] - session.add_all(roll_ranges) - session.commit() - for roll_range in roll_ranges: - session.refresh(roll_range) - - return Message(message="Roll ranges added successfully") - - -@ router.get("/{poll_id}/result", response_model=PollResult) -def get_poll_result(poll_id: UUID, user: CurrentUser, session: SessionDep): - """Get the result of a poll.""" - poll = session.get(Poll, poll_id) - - if not poll: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Poll not found") - - if poll.is_private and poll.creator_email != user.email and not any(roll_range.start <= user.roll <= roll_range.end for roll_range in poll.roll_ranges): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to view this poll") - - if poll.end_time > datetime.now(timezone.utc): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Poll has not ended yet") - - results = session.exec( - select(PollOption.option_text, func.coalesce( - func.count(Vote.id), 0).label('votes')) - .outerjoin(Vote, Vote.option_id == PollOption.id) - .where(PollOption.poll_id == poll_id) - .group_by(PollOption.option_text) - ).all() - - total_votes = sum([result.votes for result in results]) - data = [ - PollOptionResult(option_text=result.option_text, votes=result.votes) - for result in results - ] - - return PollResult(data=data, total_votes=total_votes) diff --git a/app/api/routes/user.py b/app/api/routes/user.py deleted file mode 100644 index 6980222b0aac6ea5893887ca4c5a8496a413f691..0000000000000000000000000000000000000000 --- a/app/api/routes/user.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import APIRouter -from api.deps import CurrentUser -from models.common import AuthUser -router = APIRouter() - -@router.get("/current", response_model=AuthUser) -def get_current_user(current_user: CurrentUser): - """ - Get current user. - """ - return current_user \ No newline at end of file diff --git a/app/api/routes/vote.py b/app/api/routes/vote.py deleted file mode 100644 index 0028db20868c4254ac860e33d1cf2da56920c3a3..0000000000000000000000000000000000000000 --- a/app/api/routes/vote.py +++ /dev/null @@ -1,56 +0,0 @@ -from datetime import datetime, timezone -from fastapi import APIRouter, HTTPException, status -from sqlmodel import select, and_ - -from core.security import hash_email -from api.deps import SessionDep, CurrentUser -from models.common import Message -from models.poll import Poll, PollOption -from models.vote import Vote, VoteCreateRequest - - -router = APIRouter() - - -@router.post("/vote", response_model=Message) -def vote(request: VoteCreateRequest, user: CurrentUser, session: SessionDep): - voter_email_hash = hash_email(user.email) - poll_option = session.get(PollOption, request.option_id) - if not poll_option: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="PollOption not found") - - poll = session.get(Poll, poll_option.poll_id) - if (poll.is_private and poll.creator_email != user.email - and not any(roll_range.start <= user.roll <= roll_range.end for roll_range in poll.roll_ranges) - ): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, detail="You are not authorized to vote in this poll") - if poll.start_time > datetime.now(timezone.utc): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Poll not started yet") - if poll.end_time < datetime.now(timezone.utc): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Poll has ended") - - if session.exec( - select(Vote) - .join(PollOption) - .where( - and_( - Vote.voter_email_hash == voter_email_hash, - PollOption.poll_id == poll.id - ) - ) - ).first(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="You have already voted in this poll") - - vote = Vote( - option_id=request.option_id, - voter_email_hash=voter_email_hash - ) - session.add(vote) - session.commit() - session.refresh(vote) - return Message(message="Voted successfully") diff --git a/app/core/__init__.py b/app/core/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/app/core/__pycache__/__init__.cpython-312.pyc b/app/core/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index 47b988ff21a9c19575835bc404f9ec1609553158..0000000000000000000000000000000000000000 Binary files a/app/core/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/core/__pycache__/config.cpython-312.pyc b/app/core/__pycache__/config.cpython-312.pyc deleted file mode 100644 index 0c0cfcafd7022b3e51c3733e6a0cfe850dd16860..0000000000000000000000000000000000000000 Binary files a/app/core/__pycache__/config.cpython-312.pyc and /dev/null differ diff --git a/app/core/__pycache__/db.cpython-312.pyc b/app/core/__pycache__/db.cpython-312.pyc deleted file mode 100644 index bee21cc270f52d4155e718f39fb5fb35c9962371..0000000000000000000000000000000000000000 Binary files a/app/core/__pycache__/db.cpython-312.pyc and /dev/null differ diff --git a/app/core/__pycache__/security.cpython-312.pyc b/app/core/__pycache__/security.cpython-312.pyc deleted file mode 100644 index 2b19dd30f8aaf9690f9be4fb94e3dbe17dbbe637..0000000000000000000000000000000000000000 Binary files a/app/core/__pycache__/security.cpython-312.pyc and /dev/null differ diff --git a/app/core/config.py b/app/core/config.py deleted file mode 100644 index 5d98fa143c5bf5bbdd86f354399a7a59e98b895c..0000000000000000000000000000000000000000 --- a/app/core/config.py +++ /dev/null @@ -1,46 +0,0 @@ -import secrets -from pydantic_settings import BaseSettings -from dotenv import load_dotenv -from typing import Annotated, Any, Literal -from pydantic import ( - AnyUrl, - BeforeValidator, - computed_field, - PostgresDsn -) -load_dotenv() - - -def parse_cors(v: Any) -> list[str] | str: - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, list | str): - return v - raise ValueError(v) - - -class Settings(BaseSettings): - API_V1_STR: str = "/api/v1" - DATABASE_URL: str - PROJECT_NAME: str - - @computed_field # type: ignore[misc] - @property - def SQLALCHEMY_DATABASE_URL(self) -> PostgresDsn: - return self.DATABASE_URL - - SECRET_KEY: str = secrets.token_urlsafe(32) - AUDIENCE: str = "authenticated" - # 60 minutes * 24 hours * 8 days = 8 days - ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 - - DOMAIN: str = "localhost" - ENVIRONMENT: Literal["local", "development", "merge", "staging", "production"] = ( - "local" - ) - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) - - -settings = Settings() diff --git a/app/core/db.py b/app/core/db.py deleted file mode 100644 index 896f2640fccd965db3174bdb26e049bb773a35fb..0000000000000000000000000000000000000000 --- a/app/core/db.py +++ /dev/null @@ -1,14 +0,0 @@ -from sqlmodel import SQLModel, create_engine, Session -from core.config import settings - -# Create the engine for PostgreSQL -engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URL), echo=True) - -# Create a session for the database connection -def get_session(): - with Session(engine) as session: - yield session - -# Function to initialize the database (to be used with Alembic for migrations) -def init_db(): - SQLModel.metadata.create_all(engine) diff --git a/app/core/security.py b/app/core/security.py deleted file mode 100644 index f913e0ba8d5d34e9c96e845c8765b0b3eabc08e6..0000000000000000000000000000000000000000 --- a/app/core/security.py +++ /dev/null @@ -1,8 +0,0 @@ -import hashlib - -def hash_email(email: str) -> str: - """Hash the email using SHA-256.""" - return hashlib.sha256(email.encode()).hexdigest() - - -ALGORITHM = "HS256" diff --git a/app/main.py b/app/main.py deleted file mode 100644 index f81d8609faaa6435af031233903164fae5369b31..0000000000000000000000000000000000000000 --- a/app/main.py +++ /dev/null @@ -1,22 +0,0 @@ -from fastapi import FastAPI -from core.config import settings -from fastapi.middleware.cors import CORSMiddleware -from api.main import api_router - -app = FastAPI( - title=settings.PROJECT_NAME, - openapi_url=f"{settings.API_V1_STR}/openapi.json", -) - -if settings.BACKEND_CORS_ORIGINS: - app.add_middleware( - CORSMiddleware, - allow_origins=[ - str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS - ], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], - ) - -app.include_router(api_router, prefix=settings.API_V1_STR) diff --git a/app/models/__init__.py b/app/models/__init__.py deleted file mode 100644 index 57a63a382489b17110ef5a76251f5b2d34079dc4..0000000000000000000000000000000000000000 --- a/app/models/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -from .vote import Vote -from .poll import( - Poll, - PollCreate, - PollCreateResponse, - PollOption, - PollOptions, - PollOptionsCreate, - PollOptionResult, - PollResponse, - PollsResponse, - RollRange, - RollRanges, - RollRangesCreate, - PollResult -) diff --git a/app/models/__pycache__/__init__.cpython-312.pyc b/app/models/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index aad2b614b92d329034814e51289a2e93e7b7e1d5..0000000000000000000000000000000000000000 Binary files a/app/models/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/models/__pycache__/common.cpython-312.pyc b/app/models/__pycache__/common.cpython-312.pyc deleted file mode 100644 index 46980ca15862bd8cd7507bd92e5d22d1ad22cb3c..0000000000000000000000000000000000000000 Binary files a/app/models/__pycache__/common.cpython-312.pyc and /dev/null differ diff --git a/app/models/__pycache__/poll.cpython-312.pyc b/app/models/__pycache__/poll.cpython-312.pyc deleted file mode 100644 index 7ba3ca8ded47b61a7fa1dc14d4ba89028d36b74d..0000000000000000000000000000000000000000 Binary files a/app/models/__pycache__/poll.cpython-312.pyc and /dev/null differ diff --git a/app/models/__pycache__/vote.cpython-312.pyc b/app/models/__pycache__/vote.cpython-312.pyc deleted file mode 100644 index b892fe825db5fe5a557faeb5c4b469add5eb61d6..0000000000000000000000000000000000000000 Binary files a/app/models/__pycache__/vote.cpython-312.pyc and /dev/null differ diff --git a/app/models/common.py b/app/models/common.py deleted file mode 100644 index ce798ce944cc642e60c13d751a4010b9c178502f..0000000000000000000000000000000000000000 --- a/app/models/common.py +++ /dev/null @@ -1,12 +0,0 @@ -from pydantic import EmailStr, BaseModel - - -class Message(BaseModel): - message: str - - -class AuthUser(BaseModel): - email: EmailStr - full_name: str - roll: int - avatar_url: str = None diff --git a/app/models/poll.py b/app/models/poll.py deleted file mode 100644 index 6e1cbad33f8bde155c25338d760474bc316b82bc..0000000000000000000000000000000000000000 --- a/app/models/poll.py +++ /dev/null @@ -1,110 +0,0 @@ -import uuid -from uuid import UUID -from datetime import datetime, timezone, timedelta -from pydantic import BaseModel -from sqlmodel import SQLModel, Field, Relationship -from typing import TYPE_CHECKING, Optional - -if TYPE_CHECKING: - from models.vote import Vote - - -class RollRange(SQLModel, table=True): - id: UUID = Field(default_factory=uuid.uuid4, primary_key=True) - start: int = Field(default=10 ** 6) - end: int = Field(default=10 ** 7) - poll_id: UUID = Field(foreign_key="poll.id", ondelete="CASCADE") - poll: "Poll" = Relationship(back_populates="roll_ranges") - - -class RollRanges(BaseModel): - data: list[RollRange] - count: int - - -class RollRangesCreate(BaseModel): - roll_ranges: list[tuple[int, int]] - - -class Poll(SQLModel, table=True): - id: UUID = Field(default_factory=uuid.uuid4, primary_key=True) - title: str = Field(max_length=255) - description: str = Field(max_length=1024) - is_private: bool = Field(default=False) - created_at: datetime = Field( - default_factory=lambda: datetime.now(timezone.utc) - ) - creator_email: str = Field(max_length=255) - start_time: datetime = Field( - default_factory=lambda: datetime.now(timezone.utc) - ) - end_time: datetime = Field( - default_factory=lambda: datetime.now(timezone.utc) + timedelta(days=1) - ) - options: list["PollOption"] = Relationship( - back_populates="poll", cascade_delete=True) - roll_ranges: list["RollRange"] = Relationship( - back_populates="poll", cascade_delete=True) - - -class PollCreate(BaseModel): - title: str = Field(max_length=255) - description: str | None = Field(max_length=1024) - is_private: bool = Field(default=False) - start_time: datetime = Field( - default_factory=lambda: datetime.now(timezone.utc)) - end_time: datetime = Field( - default_factory=lambda: datetime.now(timezone.utc) + timedelta(days=1) - ) - - -class PollCreateResponse(BaseModel): - poll_id: UUID - - -class PollResponse(BaseModel): - id: UUID - title: str - description: str - is_private: bool - creator_email: str - created_at: datetime - start_time: datetime - end_time: datetime - roll_ranges: list[RollRange] - options: list["PollOption"] - selected_option: Optional["PollOption"] - total_votes: int - - -class PollsResponse(BaseModel): - data: list[PollResponse] - count: int - - -class PollOption(SQLModel, table=True): - id: UUID = Field(default_factory=uuid.uuid4, primary_key=True) - poll_id: UUID = Field(foreign_key="poll.id", ondelete="CASCADE") - option_text: str = Field(max_length=255) - poll: Poll = Relationship(back_populates="options") - votes: list["Vote"] = Relationship( - back_populates="poll_option", cascade_delete=True) - - -class PollOptions(BaseModel): - data: list[PollOption] - count: int - - -class PollOptionsCreate(BaseModel): - option_texts: list[str] - - -class PollOptionResult(BaseModel): - option_text: str - votes: int - - -class PollResult(BaseModel): - data: list[PollOptionResult] - total_votes: int diff --git a/app/models/vote.py b/app/models/vote.py deleted file mode 100644 index 43bf9dcd43dd660be835228209ae1194a0cc0354..0000000000000000000000000000000000000000 --- a/app/models/vote.py +++ /dev/null @@ -1,23 +0,0 @@ -from sqlmodel import SQLModel, Field, Relationship -from pydantic import BaseModel -from uuid import uuid4, UUID -from datetime import datetime, timezone -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from models.poll import PollOption - - -class Vote(SQLModel, table=True): - id: UUID = Field( - default_factory=uuid4, primary_key=True, index=True) - option_id: UUID = Field(foreign_key="polloption.id", - ondelete="CASCADE", index=True) - voter_email_hash: str = Field(max_length=255) - timestamp: datetime = Field( - default_factory=lambda: datetime.now(timezone.utc)) - poll_option: "PollOption" = Relationship(back_populates="votes") - - -class VoteCreateRequest(BaseModel): - option_id: UUID diff --git a/app/services/__init__.py b/app/services/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/app/services/__pycache__/__init__.cpython-312.pyc b/app/services/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index df6b78a5c12aa5d12a2d4e1fb8346f3eba9d2885..0000000000000000000000000000000000000000 Binary files a/app/services/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/services/__pycache__/otp.cpython-312.pyc b/app/services/__pycache__/otp.cpython-312.pyc deleted file mode 100644 index c7d70b21d27ef246a3d1103ef14021dbfaa64c09..0000000000000000000000000000000000000000 Binary files a/app/services/__pycache__/otp.cpython-312.pyc and /dev/null differ diff --git a/app/services/__pycache__/verification.cpython-312.pyc b/app/services/__pycache__/verification.cpython-312.pyc deleted file mode 100644 index 755946f73960d8b5fa4e04799eab5e31b384c749..0000000000000000000000000000000000000000 Binary files a/app/services/__pycache__/verification.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__init__.py b/app/utils/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/app/utils/__pycache__/__init__.cpython-312.pyc b/app/utils/__pycache__/__init__.cpython-312.pyc deleted file mode 100644 index c3a332e2a5c28e3f40f2abee3ac976c2fc364945..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/__init__.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__pycache__/bst_time.cpython-312.pyc b/app/utils/__pycache__/bst_time.cpython-312.pyc deleted file mode 100644 index 150d8a743db8877725d718d469ec7d48cc401456..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/bst_time.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__pycache__/current_bst_time.cpython-312.pyc b/app/utils/__pycache__/current_bst_time.cpython-312.pyc deleted file mode 100644 index 2bab5e940810211ec69b8c04ad1f0766c1784c27..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/current_bst_time.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__pycache__/email_validator.cpython-312.pyc b/app/utils/__pycache__/email_validator.cpython-312.pyc deleted file mode 100644 index dac9becdad5faf7e517d10541ee9686a62c419d8..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/email_validator.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__pycache__/extract_id.cpython-312.pyc b/app/utils/__pycache__/extract_id.cpython-312.pyc deleted file mode 100644 index a896e5098aa2f799b384bb6009c45497d668a3d7..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/extract_id.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__pycache__/extract_roll.cpython-312.pyc b/app/utils/__pycache__/extract_roll.cpython-312.pyc deleted file mode 100644 index 4593551451d92c2fd5eb9620e5de91ad22e09dce..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/extract_roll.cpython-312.pyc and /dev/null differ diff --git a/app/utils/__pycache__/security.cpython-312.pyc b/app/utils/__pycache__/security.cpython-312.pyc deleted file mode 100644 index 71a7fa5baf73ab52163857aacaae28aae3a9ec59..0000000000000000000000000000000000000000 Binary files a/app/utils/__pycache__/security.cpython-312.pyc and /dev/null differ diff --git a/app/utils/email_validator.py b/app/utils/email_validator.py deleted file mode 100644 index 5ba66d2ec4d8dd522ac0e4812ae0cba44ba7377a..0000000000000000000000000000000000000000 --- a/app/utils/email_validator.py +++ /dev/null @@ -1,8 +0,0 @@ -import re - -CUET_EMAIL_PATTERN = r"^u\d{2}\d{2}\d{3}@student\.cuet\.ac\.bd$" - - -def is_valid_cuet_email(email: str) -> bool: - """Validate if the provided email is a valid CUET student email.""" - return bool(re.match(CUET_EMAIL_PATTERN, email))