3v324v23 commited on
Commit
1f70d93
·
0 Parent(s):

Phase 2 backend Docker deploy

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env +11 -0
  2. .python-version +1 -0
  3. Dockerfile +23 -0
  4. README.md +10 -0
  5. __pycache__/auth_config.cpython-313.pyc +0 -0
  6. __pycache__/main.cpython-312.pyc +0 -0
  7. __pycache__/main.cpython-313.pyc +0 -0
  8. alembic.ini +84 -0
  9. alembic/__pycache__/env.cpython-313.pyc +0 -0
  10. alembic/env.py +114 -0
  11. alembic/versions/20251229_001_initial_todos_table_creation.py +49 -0
  12. alembic/versions/20251230_002_add_users_and_session_tokens.py +78 -0
  13. alembic/versions/20251230_003_add_user_id_to_todos.py +54 -0
  14. alembic/versions/20260105_004_add_priority_tags_due_date_recurrence.py +72 -0
  15. alembic/versions/20260106_005_add_tags_index.py +37 -0
  16. alembic/versions/__pycache__/20251229_001_initial_todos_table_creation.cpython-313.pyc +0 -0
  17. alembic/versions/__pycache__/20251230_002_add_users_and_session_tokens.cpython-313.pyc +0 -0
  18. alembic/versions/__pycache__/20251230_003_add_user_id_to_todos.cpython-313.pyc +0 -0
  19. alembic/versions/__pycache__/20260105_004_add_priority_tags_due_date_recurrence.cpython-313.pyc +0 -0
  20. alembic/versions/__pycache__/20260106_005_add_tags_index.cpython-313.pyc +0 -0
  21. backend.egg-info/PKG-INFO +21 -0
  22. backend.egg-info/SOURCES.txt +32 -0
  23. backend.egg-info/dependency_links.txt +1 -0
  24. backend.egg-info/requires.txt +15 -0
  25. backend.egg-info/top_level.txt +6 -0
  26. core/__init__.py +0 -0
  27. core/__pycache__/__init__.cpython-312.pyc +0 -0
  28. core/__pycache__/__init__.cpython-313.pyc +0 -0
  29. core/__pycache__/config.cpython-312.pyc +0 -0
  30. core/__pycache__/config.cpython-313.pyc +0 -0
  31. core/__pycache__/database.cpython-312.pyc +0 -0
  32. core/__pycache__/database.cpython-313.pyc +0 -0
  33. core/auth_config.py +34 -0
  34. core/config.py +38 -0
  35. core/database.py +66 -0
  36. main.py +86 -0
  37. middleware/__init__.py +1 -0
  38. middleware/__pycache__/__init__.cpython-313.pyc +0 -0
  39. middleware/__pycache__/auth_middleware.cpython-313.pyc +0 -0
  40. middleware/auth_middleware.py +85 -0
  41. models/__init__.py +0 -0
  42. models/__pycache__/__init__.cpython-312.pyc +0 -0
  43. models/__pycache__/__init__.cpython-313.pyc +0 -0
  44. models/__pycache__/auth.cpython-313.pyc +0 -0
  45. models/__pycache__/database_todo.cpython-312.pyc +0 -0
  46. models/__pycache__/database_todo.cpython-313.pyc +0 -0
  47. models/__pycache__/session_token.cpython-313.pyc +0 -0
  48. models/__pycache__/todo.cpython-312.pyc +0 -0
  49. models/__pycache__/todo.cpython-313.pyc +0 -0
  50. models/__pycache__/user.cpython-312.pyc +0 -0
.env ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Database Configuration
2
+ # For Neon PostgreSQL, use connection string from your Neon dashboard
3
+ # Format: postgresql+asyncpg://user:password@host/database?options=project%3Dproject-name
4
+ DATABASE_URL=postgresql+asyncpg://neondb_owner:npg_jtVgLHOo3MG9@ep-mute-mode-a46bgizx-pooler.us-east-1.aws.neon.tech/neondb
5
+ # Example connection strings:
6
+ # Local PostgreSQL: postgresql+asyncpg://postgres:postgres@localhost:5432/tododb
7
+ # Neon Cloud: postgresql+asyncpg://user:password@ep-xxxx.aws.neon.tech/tododb?options=project%3Dmy-project
8
+
9
+ # Additional settings
10
+ # DATABASE_ECHO=false # Set to 'true' for SQL query logging (development only)
11
+ BETTER_AUTH_SECRET=CLhaP1C57JBGqrY4SJu8qG1tx1-Rupdui731EdffD0
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.13
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base image
2
+ FROM python:3.12-alpine
3
+
4
+ # Set working directory
5
+ WORKDIR /app
6
+
7
+ # Install uv package
8
+ RUN pip install uv
9
+
10
+ # Copy dependency files
11
+ COPY pyproject.toml uv.lock ./
12
+
13
+ # Install dependencies in frozen mode
14
+ RUN uv sync --frozen --no-dev
15
+
16
+ # Copy all backend source code
17
+ COPY . .
18
+
19
+ # Expose backend port
20
+ EXPOSE 7860
21
+
22
+ # Run backend app
23
+ CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Phase 2 Backend
3
+ emoji: 🚀
4
+ colorFrom: gray
5
+ colorTo: gray
6
+ sdk: docker
7
+ sdk_version: "1.0.0"
8
+ app_file: main.py
9
+ pinned: false
10
+ ---
__pycache__/auth_config.cpython-313.pyc ADDED
Binary file (3.24 kB). View file
 
__pycache__/main.cpython-312.pyc ADDED
Binary file (3.37 kB). View file
 
__pycache__/main.cpython-313.pyc ADDED
Binary file (3.18 kB). View file
 
alembic.ini ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # Path to migration scripts
5
+ script_location = alembic
6
+ # Template used to generate migration file names
7
+ file_template = %%(year)d_%%(month)02d_%%(day)02d_%%(hour)02d_%%(minute)02d_%%(rev)s_%%(slug)s
8
+ # sys.path path, will be prepended to sys.path if present.
9
+ prepend_sys_path = .
10
+ # timezone to use when rendering the date within the migration file
11
+ # as well as the filename.
12
+ # leave blank for localtime
13
+ # timezone =
14
+
15
+ # max length of characters to apply to the "slug" field
16
+ truncate_slug_length = 40
17
+
18
+ # Set to 'true' to run the environment during
19
+ # the 'revision' command, regardless of autogenerate
20
+ revision_environment = false
21
+
22
+ # Set to 'true' to allow .pyc and .pyo files without
23
+ # a source .py file to be detected as revisions in the
24
+ # versions/ directory
25
+ sourceless = false
26
+
27
+ # Version location specification; This defaults
28
+ # to alembic/versions. When using multiple version
29
+ # directories, initial revisions must be specified with --version-path
30
+ version_locations = %(here)s/alembic/versions
31
+
32
+ # Version path separator; As mentioned above, this is the character used to split
33
+ # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
34
+ version_path_separator = os
35
+
36
+ # Set to 'true' to search source files recursively
37
+ # in each "version_locations" directory
38
+ recursive_version_locations = false
39
+
40
+ # The output encoding used when revision files
41
+ # are written from script.py.mako
42
+ output_encoding = utf-8
43
+
44
+ # sqlalchemy.url = postgresql+asyncpg://username:password@ep-cool-region-123456.us-east-2.aws.neon.tech/tododb
45
+
46
+ [post_write_hooks]
47
+ # post_write_hooks defines scripts or Python functions that are run
48
+ # on newly generated revision scripts. See documentation for further
49
+ # detail and examples
50
+
51
+ # Logging configuration
52
+ [loggers]
53
+ keys = root,sqlalchemy,alembic
54
+
55
+ [handlers]
56
+ keys = console
57
+
58
+ [formatters]
59
+ keys = generic
60
+
61
+ [logger_root]
62
+ level = WARN
63
+ handlers = console
64
+ qualname =
65
+
66
+ [logger_sqlalchemy]
67
+ level = WARN
68
+ handlers =
69
+ qualname = sqlalchemy.engine
70
+
71
+ [logger_alembic]
72
+ level = INFO
73
+ handlers =
74
+ qualname = alembic
75
+
76
+ [handler_console]
77
+ class = StreamHandler
78
+ args = (sys.stderr,)
79
+ level = NOTSET
80
+ formatter = generic
81
+
82
+ [formatter_generic]
83
+ format = %(levelname)-5.5s [%(name)s] %(message)s
84
+ datefmt = %H:%M:%S
alembic/__pycache__/env.cpython-313.pyc ADDED
Binary file (4.36 kB). View file
 
alembic/env.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Alembic environment configuration for database migrations.
3
+
4
+ This module sets up migration environment for SQLAlchemy async models.
5
+ It handles database connection, target metadata, and online vs offline migrations.
6
+ """
7
+ import asyncio
8
+ from logging.config import fileConfig
9
+
10
+ from sqlalchemy import pool
11
+ from sqlalchemy.engine import Connection
12
+ from sqlalchemy.ext.asyncio import async_engine_from_config
13
+ from alembic import context
14
+
15
+ # Import your Base and models here
16
+ # This is where Alembic will find all SQLAlchemy models
17
+ from core.database import Base
18
+ from models.database_todo import Todo # Import all models to ensure they're registered
19
+ from models.user import User # Import User model
20
+ from models.session_token import SessionToken # Import SessionToken model
21
+ from core.config import settings
22
+
23
+
24
+ # this is the Alembic Config object, which provides
25
+ # access to the values within the .ini file in use.
26
+ config = context.config
27
+
28
+ # Override sqlalchemy.url from environment variable (via core.config.settings)
29
+ config.set_main_option("sqlalchemy.url", settings.database_url)
30
+
31
+ # Interpret the config file for Python logging.
32
+ # This line sets up loggers basically.
33
+ if config.config_file_name is not None:
34
+ fileConfig(config.config_file_name)
35
+
36
+ # add your model's MetaData object here
37
+ # for 'autogenerate' support
38
+ target_metadata = Base.metadata
39
+
40
+
41
+ def run_migrations_offline() -> None:
42
+ """
43
+ Run migrations in 'offline' mode.
44
+
45
+ This configures the context with just a URL
46
+ and not an Engine, though an Engine is acceptable here as well.
47
+ By skipping the Engine creation we don't even need a DBAPI to be available.
48
+ Calls to context.execute() here emit the given string to the script output.
49
+ """
50
+ url = config.get_main_option("sqlalchemy.url")
51
+ context.configure(
52
+ url=url,
53
+ target_metadata=target_metadata,
54
+ literal_binds=True,
55
+ dialect_opts={"paramstyle": "named"},
56
+ compare_type=True, # Detect column type changes
57
+ compare_server_default=True, # Detect default value changes
58
+ )
59
+
60
+ with context.begin_transaction():
61
+ context.run_migrations()
62
+
63
+
64
+ def do_run_migrations(connection: Connection) -> None:
65
+ """
66
+ Run migrations for a given connection.
67
+
68
+ Args:
69
+ connection: SQLAlchemy connection to use for migrations
70
+ """
71
+ context.configure(
72
+ connection=connection,
73
+ target_metadata=target_metadata,
74
+ compare_type=True,
75
+ compare_server_default=True,
76
+ )
77
+
78
+ with context.begin_transaction():
79
+ context.run_migrations()
80
+
81
+
82
+ async def run_async_migrations() -> None:
83
+ """
84
+ Run migrations in 'online' mode with async support.
85
+
86
+ In this scenario we need to create an Engine and associate a connection
87
+ with the context. Uses async engine for asyncpg support.
88
+ """
89
+ connectable = async_engine_from_config(
90
+ config.get_section(config.config_ini_section, {}),
91
+ prefix="sqlalchemy.",
92
+ poolclass=pool.NullPool,
93
+ )
94
+
95
+ async with connectable.connect() as connection:
96
+ await connection.run_sync(do_run_migrations)
97
+
98
+ await connectable.dispose()
99
+
100
+
101
+ def run_migrations_online() -> None:
102
+ """
103
+ Run migrations in 'online' mode.
104
+
105
+ In this scenario we need to create an Engine and associate a connection
106
+ with the context. Uses async engine for PostgreSQL asyncpg support.
107
+ """
108
+ asyncio.run(run_async_migrations())
109
+
110
+
111
+ if context.is_offline_mode():
112
+ run_migrations_offline()
113
+ else:
114
+ run_migrations_online()
alembic/versions/20251229_001_initial_todos_table_creation.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Initial todos table creation
2
+
3
+ Revision ID: 001
4
+ Revises:
5
+ Create Date: 2025-12-29
6
+ """
7
+ from typing import Sequence, Union
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+
11
+ # revision identifiers, used by Alembic.
12
+ revision: str = "001"
13
+ down_revision: Union[str, None] = None
14
+ branch_labels: Union[str, Sequence[str], None] = None
15
+ depends_on: Union[str, Sequence[str], None] = None
16
+
17
+
18
+ def upgrade() -> None:
19
+ """
20
+ Apply migration to upgrade database schema.
21
+
22
+ Creates the todos table with:
23
+ - Primary key (id)
24
+ - Description field with NOT NULL constraint
25
+ - Completed boolean field with default False
26
+ - Created_at timestamp (auto-generated)
27
+ - Updated_at timestamp (auto-generated and updated)
28
+ """
29
+ op.create_table(
30
+ "todos",
31
+ sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
32
+ sa.Column("description", sa.String(length=500), nullable=False),
33
+ sa.Column("completed", sa.Boolean(), nullable=False, server_default="false"),
34
+ sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.text("now()")),
35
+ sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.text("now()"), onupdate=sa.text("now()")),
36
+ sa.PrimaryKeyConstraint("id", name="pk_todos_id"),
37
+ )
38
+ op.create_index("ix_todos_id", "todos", ["id"], unique=False)
39
+
40
+
41
+ def downgrade() -> None:
42
+ """
43
+ Apply migration to downgrade database schema.
44
+
45
+ Drops the todos table and all associated indexes.
46
+ This is a destructive operation that will delete all todo data.
47
+ """
48
+ op.drop_index("ix_todos_id", table_name="todos")
49
+ op.drop_table("todos")
alembic/versions/20251230_002_add_users_and_session_tokens.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add users and session_tokens tables
2
+
3
+ Revision ID: 002
4
+ Revises: 001
5
+ Create Date: 2025-12-30
6
+ """
7
+ from typing import Sequence, Union
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+
11
+ # revision identifiers, used by Alembic.
12
+ revision: str = "002"
13
+ down_revision: Union[str, None] = "001"
14
+ branch_labels: Union[str, Sequence[str], None] = None
15
+ depends_on: Union[str, Sequence[str], None] = None
16
+
17
+
18
+ def upgrade() -> None:
19
+ """
20
+ Apply migration to upgrade database schema.
21
+
22
+ Creates the users and session_tokens tables with indexes.
23
+ """
24
+ # Create users table
25
+ op.create_table(
26
+ "users",
27
+ sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
28
+ sa.Column("email", sa.String(length=255), nullable=False),
29
+ sa.Column("password_hash", sa.String(length=255), nullable=False),
30
+ sa.Column("google_id", sa.String(length=255), nullable=True),
31
+ sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.text("now()")),
32
+ sa.Column("updated_at", sa.DateTime(), nullable=False, server_default=sa.text("now()")),
33
+ sa.PrimaryKeyConstraint("id", name="pk_users_id"),
34
+ sa.UniqueConstraint("email", name="uq_users_email"),
35
+ sa.UniqueConstraint("google_id", name="uq_users_google_id"),
36
+ )
37
+ op.create_index("ix_users_id", "users", ["id"], unique=False)
38
+ op.create_index("ix_users_email", "users", ["email"], unique=False)
39
+ op.create_index("ix_users_google_id", "users", ["google_id"], unique=False)
40
+
41
+ # Create session_tokens table
42
+ op.create_table(
43
+ "session_tokens",
44
+ sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
45
+ sa.Column("user_id", sa.Integer(), nullable=False),
46
+ sa.Column("token", sa.Text(), nullable=False),
47
+ sa.Column("expires_at", sa.DateTime(), nullable=False),
48
+ sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.text("now()")),
49
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"], name="fk_session_tokens_user_id", ondelete="CASCADE"),
50
+ sa.PrimaryKeyConstraint("id", name="pk_session_tokens_id"),
51
+ sa.UniqueConstraint("token", name="uq_session_tokens_token"),
52
+ )
53
+ op.create_index("ix_session_tokens_user_id", "session_tokens", ["user_id"], unique=False)
54
+ op.create_index("ix_session_tokens_token", "session_tokens", ["token"], unique=False)
55
+ op.create_index("ix_session_tokens_expires_at", "session_tokens", ["expires_at"], unique=False)
56
+
57
+
58
+ def downgrade() -> None:
59
+ """
60
+ Apply migration to downgrade database schema.
61
+
62
+ Drops the session_tokens and users tables and all associated indexes.
63
+ """
64
+ # Drop indexes first
65
+ op.drop_index("ix_session_tokens_expires_at", table_name="session_tokens")
66
+ op.drop_index("ix_session_tokens_token", table_name="session_tokens")
67
+ op.drop_index("ix_session_tokens_user_id", table_name="session_tokens")
68
+
69
+ # Drop session_tokens table
70
+ op.drop_table("session_tokens")
71
+
72
+ # Drop users indexes
73
+ op.drop_index("ix_users_google_id", table_name="users")
74
+ op.drop_index("ix_users_email", table_name="users")
75
+ op.drop_index("ix_users_id", table_name="users")
76
+
77
+ # Drop users table
78
+ op.drop_table("users")
alembic/versions/20251230_003_add_user_id_to_todos.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add user_id to todos table
2
+
3
+ Revision ID: 003
4
+ Revises: 002
5
+ Create Date: 2025-12-30
6
+ """
7
+ from typing import Sequence, Union
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+
11
+ # revision identifiers, used by Alembic.
12
+ revision: str = "003"
13
+ down_revision: Union[str, None] = "002"
14
+ branch_labels: Union[str, Sequence[str], None] = None
15
+ depends_on: Union[str, Sequence[str], None] = None
16
+
17
+
18
+ def upgrade() -> None:
19
+ """
20
+ Apply migration to upgrade database schema.
21
+
22
+ Adds user_id foreign key column to todos table.
23
+ """
24
+ # Add user_id column (nullable for backward compatibility)
25
+ op.add_column("todos", sa.Column("user_id", sa.Integer(), nullable=True))
26
+
27
+ # Add foreign key constraint
28
+ op.create_foreign_key(
29
+ "fk_todos_user_id",
30
+ "todos",
31
+ "users",
32
+ ["user_id"],
33
+ ["id"],
34
+ ondelete="CASCADE"
35
+ )
36
+
37
+ # Add index on user_id for query performance
38
+ op.create_index("ix_todos_user_id", "todos", ["user_id"], unique=False)
39
+
40
+
41
+ def downgrade() -> None:
42
+ """
43
+ Apply migration to downgrade database schema.
44
+
45
+ Removes user_id column and foreign key from todos table.
46
+ """
47
+ # Drop index first
48
+ op.drop_index("ix_todos_user_id", table_name="todos")
49
+
50
+ # Drop foreign key constraint
51
+ op.drop_constraint("fk_todos_user_id", "todos", type_="foreignkey")
52
+
53
+ # Drop column
54
+ op.drop_column("todos", "user_id")
alembic/versions/20260105_004_add_priority_tags_due_date_recurrence.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add priority, tags, due_date, recurrence_type, and reminder_time to todos table
2
+
3
+ Revision ID: 004
4
+ Revises: 003
5
+ Create Date: 2026-01-05
6
+ """
7
+ from typing import Sequence, Union
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+
11
+
12
+ # revision identifiers, used by Alembic.
13
+ revision: str = "004"
14
+ down_revision: Union[str, None] = "003"
15
+ branch_labels: Union[str, Sequence[str], None] = None
16
+ depends_on: Union[str, Sequence[str], None] = None
17
+
18
+
19
+ def upgrade() -> None:
20
+ """
21
+ Apply migration to upgrade database schema.
22
+
23
+ Adds priority, tags, due_date, recurrence_type, and reminder_time columns to todos table.
24
+ """
25
+ # Add priority column (ENUM: HIGH, MEDIUM, LOW with default MEDIUM)
26
+ op.execute("CREATE TYPE priority_enum AS ENUM ('HIGH', 'MEDIUM', 'LOW')")
27
+ op.add_column("todos", sa.Column("priority", sa.Enum("HIGH", "MEDIUM", "LOW", name="priority_enum"), nullable=False, server_default="MEDIUM"))
28
+
29
+ # Add tags column (JSON for storing array of tags)
30
+ op.add_column("todos", sa.Column("tags", sa.JSON(), nullable=False, server_default="[]"))
31
+
32
+ # Add due_date column (TIMESTAMP NULL)
33
+ op.add_column("todos", sa.Column("due_date", sa.DateTime(), nullable=True))
34
+
35
+ # Add recurrence_type column (ENUM: NONE, DAILY, WEEKLY, MONTHLY with default NONE)
36
+ op.execute("CREATE TYPE recurrence_enum AS ENUM ('NONE', 'DAILY', 'WEEKLY', 'MONTHLY')")
37
+ op.add_column("todos", sa.Column("recurrence_type", sa.Enum("NONE", "DAILY", "WEEKLY", "MONTHLY", name="recurrence_enum"), nullable=False, server_default="NONE"))
38
+
39
+ # Add reminder_time column (INTEGER for minutes before due time, default 10)
40
+ op.add_column("todos", sa.Column("reminder_time", sa.Integer(), nullable=False, server_default="10"))
41
+
42
+ # Add indexes for performance
43
+ op.create_index("ix_todos_priority", "todos", ["priority"], unique=False)
44
+ op.create_index("ix_todos_due_date", "todos", ["due_date"], unique=False)
45
+ op.create_index("ix_todos_user_priority", "todos", ["user_id", "priority"], unique=False)
46
+ op.create_index("ix_todos_user_due_date", "todos", ["user_id", "due_date"], unique=False)
47
+ op.create_index("ix_todos_user_completed", "todos", ["user_id", "completed"], unique=False)
48
+
49
+
50
+ def downgrade() -> None:
51
+ """
52
+ Apply migration to downgrade database schema.
53
+
54
+ Removes priority, tags, due_date, recurrence_type, and reminder_time columns from todos table.
55
+ """
56
+ # Drop indexes first
57
+ op.drop_index("ix_todos_user_completed", table_name="todos")
58
+ op.drop_index("ix_todos_user_due_date", table_name="todos")
59
+ op.drop_index("ix_todos_user_priority", table_name="todos")
60
+ op.drop_index("ix_todos_due_date", table_name="todos")
61
+ op.drop_index("ix_todos_priority", table_name="todos")
62
+
63
+ # Drop columns
64
+ op.drop_column("todos", "reminder_time")
65
+ op.drop_column("todos", "recurrence_type")
66
+ op.drop_column("todos", "due_date")
67
+ op.drop_column("todos", "tags")
68
+ op.drop_column("todos", "priority")
69
+
70
+ # Drop enums
71
+ op.execute("DROP TYPE IF EXISTS recurrence_enum")
72
+ op.execute("DROP TYPE IF EXISTS priority_enum")
alembic/versions/20260106_005_add_tags_index.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add index for tags field
2
+
3
+ Revision ID: 005
4
+ Revises: 004
5
+ Create Date: 2026-01-06
6
+ """
7
+ from typing import Sequence, Union
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+
11
+
12
+ # revision identifiers, used by Alembic.
13
+ revision: str = "005"
14
+ down_revision: Union[str, None] = "004"
15
+ branch_labels: Union[str, Sequence[str], None] = None
16
+ depends_on: Union[str, Sequence[str], None] = None
17
+
18
+
19
+ def upgrade() -> None:
20
+ """
21
+ Apply migration to upgrade database schema.
22
+
23
+ Adds index for tags column to optimize search performance.
24
+ """
25
+ # Add GIN index for tags field to optimize JSON array operations
26
+ # GIN (Generalized Inverted Index) is the appropriate index type for JSON fields
27
+ op.execute("CREATE INDEX ix_todos_tags ON todos USING GIN (tags)")
28
+
29
+
30
+ def downgrade() -> None:
31
+ """
32
+ Apply migration to downgrade database schema.
33
+
34
+ Removes index for tags column.
35
+ """
36
+ # Drop the index
37
+ op.drop_index("ix_todos_tags", table_name="todos")
alembic/versions/__pycache__/20251229_001_initial_todos_table_creation.cpython-313.pyc ADDED
Binary file (2.74 kB). View file
 
alembic/versions/__pycache__/20251230_002_add_users_and_session_tokens.cpython-313.pyc ADDED
Binary file (4.57 kB). View file
 
alembic/versions/__pycache__/20251230_003_add_user_id_to_todos.cpython-313.pyc ADDED
Binary file (1.92 kB). View file
 
alembic/versions/__pycache__/20260105_004_add_priority_tags_due_date_recurrence.cpython-313.pyc ADDED
Binary file (4.08 kB). View file
 
alembic/versions/__pycache__/20260106_005_add_tags_index.cpython-313.pyc ADDED
Binary file (1.35 kB). View file
 
backend.egg-info/PKG-INFO ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: backend
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.13
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: alembic>=1.17.2
8
+ Requires-Dist: asyncpg>=0.31.0
9
+ Requires-Dist: email-validator>=2.3.0
10
+ Requires-Dist: fastapi>=0.128.0
11
+ Requires-Dist: httpx>=0.27.0
12
+ Requires-Dist: passlib[bcrypt]>=1.7.4
13
+ Requires-Dist: psycopg2-binary>=2.9.11
14
+ Requires-Dist: pydantic>=2.12.5
15
+ Requires-Dist: pydantic-settings>=2.12.0
16
+ Requires-Dist: pydentic>=0.0.1.dev3
17
+ Requires-Dist: python-dotenv>=1.2.1
18
+ Requires-Dist: python-jose[cryptography]>=3.5.0
19
+ Requires-Dist: python-multipart>=0.0.21
20
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.45
21
+ Requires-Dist: uvicorn>=0.40.0
backend.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ README.md
2
+ pyproject.toml
3
+ alembic/env.py
4
+ alembic/versions/20251229_001_initial_todos_table_creation.py
5
+ alembic/versions/20251230_002_add_users_and_session_tokens.py
6
+ alembic/versions/20251230_003_add_user_id_to_todos.py
7
+ alembic/versions/20260105_004_add_priority_tags_due_date_recurrence.py
8
+ alembic/versions/20260106_005_add_tags_index.py
9
+ backend.egg-info/PKG-INFO
10
+ backend.egg-info/SOURCES.txt
11
+ backend.egg-info/dependency_links.txt
12
+ backend.egg-info/requires.txt
13
+ backend.egg-info/top_level.txt
14
+ core/__init__.py
15
+ core/auth_config.py
16
+ core/config.py
17
+ core/database.py
18
+ middleware/__init__.py
19
+ middleware/auth_middleware.py
20
+ models/__init__.py
21
+ models/auth.py
22
+ models/database_todo.py
23
+ models/session_token.py
24
+ models/todo.py
25
+ models/user.py
26
+ routes/__init__.py
27
+ routes/auth.py
28
+ routes/todos.py
29
+ services/__init__.py
30
+ services/auth_service.py
31
+ services/jwt_service.py
32
+ services/todo_service.py
backend.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
backend.egg-info/requires.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alembic>=1.17.2
2
+ asyncpg>=0.31.0
3
+ email-validator>=2.3.0
4
+ fastapi>=0.128.0
5
+ httpx>=0.27.0
6
+ passlib[bcrypt]>=1.7.4
7
+ psycopg2-binary>=2.9.11
8
+ pydantic>=2.12.5
9
+ pydantic-settings>=2.12.0
10
+ pydentic>=0.0.1.dev3
11
+ python-dotenv>=1.2.1
12
+ python-jose[cryptography]>=3.5.0
13
+ python-multipart>=0.0.21
14
+ sqlalchemy[asyncio]>=2.0.45
15
+ uvicorn>=0.40.0
backend.egg-info/top_level.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ alembic
2
+ core
3
+ middleware
4
+ models
5
+ routes
6
+ services
core/__init__.py ADDED
File without changes
core/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (163 Bytes). View file
 
core/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (214 Bytes). View file
 
core/__pycache__/config.cpython-312.pyc ADDED
Binary file (1.45 kB). View file
 
core/__pycache__/config.cpython-313.pyc ADDED
Binary file (1.56 kB). View file
 
core/__pycache__/database.cpython-312.pyc ADDED
Binary file (2.48 kB). View file
 
core/__pycache__/database.cpython-313.pyc ADDED
Binary file (2.51 kB). View file
 
core/auth_config.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication configuration settings
3
+
4
+ Manages JWT and OAuth configuration with environment variable support.
5
+ All secrets loaded from environment variables, never hardcoded.
6
+ """
7
+
8
+ from typing import Optional
9
+ from pydantic_settings import BaseSettings
10
+
11
+
12
+ class AuthSettings(BaseSettings):
13
+ """Authentication settings with environment variable support"""
14
+
15
+ # JWT Configuration
16
+ jwt_secret_key: str = "your-secret-key-min-32-characters-change-in-production"
17
+ jwt_algorithm: str = "HS256"
18
+ jwt_expiration_hours: int = 24
19
+
20
+ # Password Hashing Configuration
21
+ bcrypt_rounds: int = 12
22
+
23
+ # OAuth Configuration (Not used - Supabase handles OAuth)
24
+ # Google OAuth configuration has been removed as Supabase handles OAuth
25
+
26
+ model_config = {
27
+ "env_file": ".env",
28
+ "env_file_encoding": "utf-8",
29
+ "case_sensitive": False
30
+ }
31
+
32
+
33
+ # Global auth settings instance
34
+ auth_settings = AuthSettings()
core/config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration settings for Todo API
3
+
4
+ Manages application configuration with environment variable support.
5
+ Settings can be overridden via .env file.
6
+ """
7
+
8
+ from pydantic_settings import BaseSettings
9
+ import os
10
+ from dotenv import load_dotenv
11
+
12
+ load_dotenv()
13
+
14
+ class Settings(BaseSettings):
15
+ """Application settings with environment variable support"""
16
+
17
+ app_name: str = "Todo API"
18
+ port: int = 8000
19
+ log_level: str = "info"
20
+ database_url: str = "postgresql+asyncpg://user:password@localhost:5432/tododb"
21
+
22
+ # JWT Authentication Settings
23
+ jwt_secret_key: str = "your-secret-key-min-32-characters-change-in-production"
24
+ jwt_algorithm: str = "HS256"
25
+ jwt_expiration_hours: int = 24
26
+
27
+ # Better Auth Settings
28
+ better_auth_secret: str = os.getenv("BETTER_AUTH_SECRET")
29
+
30
+ model_config = {
31
+ "env_file": ".env",
32
+ "env_file_encoding": "utf-8",
33
+ "case_sensitive": False
34
+ }
35
+
36
+
37
+ # Global settings instance
38
+ settings = Settings()
core/database.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database connection and session management for PostgreSQL integration.
3
+
4
+ Provides SQLAlchemy async engine, session factory, and dependency injection
5
+ for FastAPI route handlers. This module centralizes all database connection logic.
6
+
7
+ Configuration:
8
+ - Database URL from environment variable (DATABASE_URL)
9
+ - Async engine with asyncpg driver for PostgreSQL
10
+ - Session management with automatic cleanup
11
+ """
12
+
13
+ from typing import AsyncGenerator
14
+ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
15
+ from sqlalchemy.orm import DeclarativeBase
16
+ from core.config import settings
17
+
18
+
19
+ # SQLAlchemy async engine
20
+ # Uses asyncpg driver for optimal PostgreSQL performance with FastAPI
21
+ engine = create_async_engine(
22
+ settings.database_url,
23
+ echo=False, # Set to True for SQL query logging during development
24
+ pool_pre_ping=True, # Verify connections before using them
25
+ )
26
+
27
+
28
+ # Async session factory
29
+ # Creates new sessions for each request
30
+ AsyncSessionLocal = async_sessionmaker(
31
+ engine,
32
+ class_=AsyncSession,
33
+ expire_on_commit=False, # Prevent lazy loading issues after commit
34
+ )
35
+
36
+
37
+ # Base declarative class
38
+ # All ORM models inherit from this class
39
+ class Base(DeclarativeBase):
40
+ """Base class for SQLAlchemy ORM models"""
41
+ pass
42
+
43
+
44
+ async def get_db() -> AsyncGenerator[AsyncSession, None]:
45
+ """
46
+ FastAPI dependency injection for database sessions.
47
+
48
+ Yields an async database session and ensures proper cleanup
49
+ after the request completes. This follows FastAPI's dependency
50
+ injection pattern for database access.
51
+
52
+ Yields:
53
+ AsyncSession: Database session for the current request
54
+
55
+ Example:
56
+ @router.get("/todos")
57
+ async def list_todos(db: AsyncSession = Depends(get_db)):
58
+ # Use db to query database
59
+ result = await db.execute(select(Todo))
60
+ return result.scalars().all()
61
+ """
62
+ async with AsyncSessionLocal() as session:
63
+ try:
64
+ yield session
65
+ finally:
66
+ await session.close()
main.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Todo API - Main application entry point
3
+
4
+ FastAPI application providing RESTful todo management with JWT authentication.
5
+ Features:
6
+ - Create, read, update, delete todos
7
+ - JWT-based authentication with user sessions
8
+ - Google OAuth integration
9
+ - Health check endpoint for monitoring
10
+ - Auto-generated interactive API docs at /docs
11
+ """
12
+
13
+ import logging
14
+ from fastapi import FastAPI
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ from routes import todos, auth
17
+
18
+ # Configure logging
19
+ logging.basicConfig(
20
+ level=logging.INFO,
21
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
22
+ )
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Create FastAPI application instance
26
+ app = FastAPI(
27
+ title="Todo API",
28
+ description="RESTful API for managing todo items with JWT authentication",
29
+ version="1.0.0",
30
+ docs_url="/docs",
31
+ redoc_url="/redoc"
32
+ )
33
+
34
+
35
+ # Configure CORS middleware to allow frontend access
36
+ app.add_middleware(
37
+ CORSMiddleware,
38
+ allow_origins=[
39
+ "http://localhost:3000", # Next.js development server
40
+ "http://127.0.0.1:3000", # Alternative localhost format
41
+ "http://localhost:3001", # Alternative port for Next.js
42
+ "http://127.0.0.1:3001", # Alternative localhost with port 3001
43
+ "http://localhost:3002", # Additional port for Next.js
44
+ "http://127.0.0.1:3002", # Alternative localhost with port 3002
45
+ "http://0.0.0.0:3000", # Docker/WSL compatibility
46
+ "http://0.0.0.0:3001", # Docker/WSL compatibility
47
+ "http://0.0.0.0:3002", # Docker/WSL compatibility
48
+ ],
49
+ allow_credentials=True,
50
+ allow_methods=["*"], # Allow all HTTP methods (GET, POST, PATCH, DELETE, etc.)
51
+ allow_headers=["*"], # Allow all headers
52
+ )
53
+
54
+ # Include auth routes
55
+ app.include_router(auth.router)
56
+
57
+ # Include todo routes (protected)
58
+ app.include_router(todos.router)
59
+
60
+ @app.on_event("startup")
61
+ async def startup_event():
62
+ """Application startup event handler"""
63
+ logger.info("Todo API starting up with JWT authentication...")
64
+ logger.info("Server running on http://localhost:8000")
65
+ logger.info("Interactive API docs available at http://localhost:8000/docs")
66
+ logger.info("API endpoints available at /api")
67
+
68
+
69
+ @app.on_event("shutdown")
70
+ async def shutdown_event():
71
+ """Application shutdown event handler"""
72
+ logger.info("Todo API shutting down...")
73
+
74
+
75
+ @app.get("/health", tags=["health"], summary="Health check")
76
+ async def health_check():
77
+ """
78
+ Health check endpoint for monitoring
79
+
80
+ Returns:
81
+ dict: Server health status
82
+
83
+ This endpoint is used by monitoring systems and deployment tools
84
+ to verify the API server is running and responsive.
85
+ """
86
+ return {"status": "healthy"}
middleware/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Authentication middleware package"""
middleware/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (268 Bytes). View file
 
middleware/__pycache__/auth_middleware.cpython-313.pyc ADDED
Binary file (3.32 kB). View file
 
middleware/auth_middleware.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication middleware - JWT token validation
3
+
4
+ Provides FastAPI dependency for extracting and validating JWT tokens.
5
+ Used to protect API endpoints requiring authentication.
6
+ """
7
+
8
+ from fastapi import Depends, Header, HTTPException
9
+ from jose import JWTError, jwt
10
+ from sqlalchemy.ext.asyncio import AsyncSession
11
+ from sqlalchemy import select
12
+
13
+ from core.database import get_db
14
+ from core.config import settings
15
+ from models.user import User
16
+
17
+
18
+ async def get_current_user(
19
+ authorization: str = Header(None),
20
+ db: AsyncSession = Depends(get_db)
21
+ ) -> User:
22
+ """
23
+ FastAPI dependency to extract and validate current user from JWT token
24
+
25
+ Args:
26
+ authorization: Authorization header containing "Bearer <token>"
27
+ db: Async database session from dependency injection
28
+
29
+ Returns:
30
+ User object for the authenticated user
31
+
32
+ Raises:
33
+ HTTPException 401: Missing, invalid, or expired token
34
+ HTTPException 401: User not found in database
35
+
36
+ Business Rules:
37
+ - Token must be in "Bearer <token>" format
38
+ - Token signature validated using JWT_SECRET_KEY
39
+ - Token expiration checked
40
+ - User must exist in database
41
+ - Used as dependency: current_user = Depends(get_current_user)
42
+
43
+ Example:
44
+ @router.get("/protected")
45
+ async def protected_endpoint(current_user: User = Depends(get_current_user)):
46
+ return {"user_id": current_user.id}
47
+ """
48
+ if not authorization or not authorization.startswith("Bearer "):
49
+ raise HTTPException(
50
+ status_code=401,
51
+ detail="Missing or invalid Authorization header"
52
+ )
53
+
54
+ token = authorization.split(" ")[1]
55
+
56
+ try:
57
+ # Decode and validate JWT token
58
+ payload = jwt.decode(
59
+ token,
60
+ settings.jwt_secret_key,
61
+ algorithms=[settings.jwt_algorithm]
62
+ )
63
+
64
+ # Extract user ID from token
65
+ user_id_str = payload.get("sub")
66
+ if user_id_str is None:
67
+ raise HTTPException(status_code=401, detail="Invalid token payload")
68
+
69
+ user_id = int(user_id_str)
70
+
71
+ except jwt.ExpiredSignatureError:
72
+ raise HTTPException(status_code=401, detail="Token expired")
73
+ except jwt.JWTError:
74
+ raise HTTPException(status_code=401, detail="Invalid token")
75
+ except ValueError:
76
+ raise HTTPException(status_code=401, detail="Invalid user ID in token")
77
+
78
+ # Query user from database
79
+ result = await db.execute(select(User).where(User.id == user_id))
80
+ user = result.scalar_one_or_none()
81
+
82
+ if user is None:
83
+ raise HTTPException(status_code=401, detail="User not found")
84
+
85
+ return user
models/__init__.py ADDED
File without changes
models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (165 Bytes). View file
 
models/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (216 Bytes). View file
 
models/__pycache__/auth.cpython-313.pyc ADDED
Binary file (2.97 kB). View file
 
models/__pycache__/database_todo.cpython-312.pyc ADDED
Binary file (2.41 kB). View file
 
models/__pycache__/database_todo.cpython-313.pyc ADDED
Binary file (4.43 kB). View file
 
models/__pycache__/session_token.cpython-313.pyc ADDED
Binary file (2.38 kB). View file
 
models/__pycache__/todo.cpython-312.pyc ADDED
Binary file (5.24 kB). View file
 
models/__pycache__/todo.cpython-313.pyc ADDED
Binary file (5.32 kB). View file
 
models/__pycache__/user.cpython-312.pyc ADDED
Binary file (2.49 kB). View file