Commit c5585aed authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Switch primary login to username/password, repurpose Telegram auth as account linking

Adds POST /auth/register and POST /auth/login (username/password, PBKDF2-hashed
stdlib-only, no new dependency). The former phone/code Telegram flow moves to
/auth/telegram/{request_code,login,chats,chats/{id}/music} - it now links a
Telegram account (for the chat-scanning music-tagging feature) to an
already-authenticated user rather than being the identity mechanism itself.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 5bbe811c
Pipeline #1080 passed with stage
in 3 minutes and 35 seconds
"""add password_hash to users
Revision ID: 348a47d4b742
Revises: 6015f865f019
Create Date: 2026-08-15 12:31:18.213454
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '348a47d4b742'
down_revision: Union[str, Sequence[str], None] = '6015f865f019'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.add_column("users", sa.Column("password_hash", sa.String(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column("users", "password_hash")
import uuid
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from src.core.database import AuthAttempt, RefreshToken, User, get_db
......@@ -10,7 +11,9 @@ from src.core.security import (
create_refresh_token,
decode_token,
get_current_user,
hash_password,
hash_token,
verify_password,
)
import src.telegram_worker.telegram_auth as telegram_auth
......@@ -26,7 +29,7 @@ def _utcnow() -> datetime:
# Our own Telegram API credentials are shared across every user, so a client hammering
# /auth/request_code with arbitrary numbers could get them flagged. Cheap DB-backed limit,
# /auth/telegram/request_code with arbitrary numbers could get them flagged. Cheap DB-backed limit,
# no Redis required.
MAX_REQUESTS_PER_PHONE = 5
PHONE_WINDOW = timedelta(minutes=10)
......@@ -38,12 +41,22 @@ class RequestCodeReq(BaseModel):
phone_number: str
class LoginReq(BaseModel):
class TelegramLoginReq(BaseModel):
phone_number: str
phone_code_hash: str
code: str
class RegisterReq(BaseModel):
username: str = Field(min_length=3, max_length=32, regex=r"^[a-zA-Z0-9_]+$")
password: str = Field(min_length=8, max_length=200)
class UsernameLoginReq(BaseModel):
username: str
password: str
class RefreshReq(BaseModel):
refresh_token: str
......@@ -85,8 +98,34 @@ def _issue_tokens(db: Session, user_id: int) -> TokenResponse:
return TokenResponse(access_token=access, refresh_token=refresh)
@router.post("/request_code")
async def auth_request_code(req: RequestCodeReq, request: Request, db: Session = Depends(get_db)):
@router.post("/register", response_model=TokenResponse)
async def auth_register(req: RegisterReq, db: Session = Depends(get_db)):
if db.query(User).filter(User.username == req.username).first():
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken")
user = User(username=req.username, password_hash=hash_password(req.password))
db.add(user)
db.commit()
db.refresh(user)
return _issue_tokens(db, user.id)
# Constant dummy hash so a login attempt for a username that doesn't exist still runs a
# PBKDF2 compare - without this, "no such user" would return faster than "wrong password"
# and leak which usernames are registered via response timing.
_DUMMY_PASSWORD_HASH = hash_password(uuid.uuid4().hex)
@router.post("/login", response_model=TokenResponse)
async def auth_login(req: UsernameLoginReq, db: Session = Depends(get_db)):
user = db.query(User).filter(User.username == req.username).first()
password_ok = verify_password(req.password, (user.password_hash if user else None) or _DUMMY_PASSWORD_HASH)
if not user or not user.password_hash or not password_ok:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password")
return _issue_tokens(db, user.id)
@router.post("/telegram/request_code")
async def auth_telegram_request_code(req: RequestCodeReq, request: Request, db: Session = Depends(get_db)):
client_ip = request.client.host if request.client else "unknown"
_check_rate_limit(db, req.phone_number, client_ip)
db.add(AuthAttempt(phone_number=req.phone_number, ip_address=client_ip))
......@@ -98,8 +137,12 @@ async def auth_request_code(req: RequestCodeReq, request: Request, db: Session =
raise HTTPException(status_code=400, detail=str(e))
@router.post("/login", response_model=TokenResponse)
async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
@router.post("/telegram/login", response_model=TokenResponse)
async def auth_telegram_login(req: TelegramLoginReq, db: Session = Depends(get_db)):
"""Links a Telegram account (for the chat-scanning music-tagging feature) rather than
being the primary login path - see /auth/register and /auth/login for that. Still
issues our own tokens too, since a Telegram-only user (no username/password set) needs
some way to authenticate."""
try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
except Exception as e:
......@@ -155,7 +198,7 @@ async def auth_me(current_user: User = Depends(get_current_user)):
}
@router.get("/chats")
@router.get("/telegram/chats")
async def get_chats(current_user: User = Depends(get_current_user)):
if not current_user.telegram_session_string:
raise HTTPException(status_code=400, detail="No linked Telegram session")
......@@ -166,7 +209,7 @@ async def get_chats(current_user: User = Depends(get_current_user)):
raise HTTPException(status_code=500, detail=str(e))
@router.get("/chats/{chat_id}/music")
@router.get("/telegram/chats/{chat_id}/music")
async def get_chat_music(chat_id: int, current_user: User = Depends(get_current_user)):
if not current_user.telegram_session_string:
raise HTTPException(status_code=400, detail="No linked Telegram session")
......
......@@ -27,9 +27,14 @@ class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True, nullable=True)
# PBKDF2 hash ("salt_hex$digest_hex") for the primary username/password login. Nullable
# since Telegram-linked users created before this existed (or via /auth/telegram/login)
# have no password of their own.
password_hash = Column(String, nullable=True)
phone_number = Column(String, unique=True, index=True, nullable=True)
# Pyrogram session string for this user's linked Telegram account. Set on /auth/login,
# used server-side only (by telegram_sync calls) - never serialized back to a client.
# Pyrogram session string for this user's linked Telegram account, set via
# /auth/telegram/login. Used server-side only (by telegram_sync calls) to scan the user's
# chats for music - never serialized back to a client, and no longer the primary login path.
telegram_session_string = Column(String, nullable=True)
# "user" | "business_admin" | "super_admin" - kept as a plain string rather than a DB enum
# so adding a role later doesn't need a migration to alter the enum type (sqlite's enum
......@@ -46,7 +51,7 @@ class RefreshToken(Base):
revoked_at = Column(DateTime, nullable=True)
class AuthAttempt(Base):
"""Logged on every /auth/request_code call to rate-limit our own Telegram API usage."""
"""Logged on every /auth/telegram/request_code call to rate-limit our own Telegram API usage."""
__tablename__ = "auth_attempts"
id = Column(Integer, primary_key=True, index=True)
phone_number = Column(String, index=True)
......
import hashlib
import hmac
import os
import uuid
from datetime import datetime, timedelta, timezone
......@@ -40,6 +42,28 @@ def hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
PASSWORD_HASH_ITERATIONS = 200_000
def hash_password(password: str) -> str:
"""PBKDF2-HMAC-SHA256 with a random salt, stored as "salt_hex$digest_hex" - stdlib only
(no bcrypt/passlib dependency), unlike hash_token this is deliberately slow/tunable since
passwords (unlike our own random tokens) are guessable and need brute-force resistance."""
salt = os.urandom(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, PASSWORD_HASH_ITERATIONS)
return f"{salt.hex()}${digest.hex()}"
def verify_password(password: str, stored_hash: str) -> bool:
try:
salt_hex, digest_hex = stored_hash.split("$", 1)
salt, expected = bytes.fromhex(salt_hex), bytes.fromhex(digest_hex)
except (ValueError, AttributeError):
return False
actual = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, PASSWORD_HASH_ITERATIONS)
return hmac.compare_digest(actual, expected)
def decode_token(token: str, expected_type: str) -> dict:
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
......
......@@ -2,58 +2,126 @@ from src.api.routers.auth import MAX_REQUESTS_PER_PHONE
from src.core.database import User
def test_auth_request_code(client, mocker):
# --- username/password (primary login) ---
def test_auth_register_creates_user_and_issues_tokens(client, db_session):
response = client.post("/auth/register", json={"username": "newuser1", "password": "correcthorse"})
assert response.status_code == 200
body = response.json()
assert "access_token" in body and "refresh_token" in body
user = db_session.query(User).filter(User.username == "newuser1").first()
assert user is not None
assert user.password_hash is not None
assert "correcthorse" not in response.text
def test_auth_register_rejects_duplicate_username(client):
client.post("/auth/register", json={"username": "dupeuser", "password": "correcthorse"})
response = client.post("/auth/register", json={"username": "dupeuser", "password": "differentpass"})
assert response.status_code == 409
def test_auth_register_rejects_short_password(client):
response = client.post("/auth/register", json={"username": "shortpassuser", "password": "short"})
assert response.status_code == 422
def test_auth_register_rejects_invalid_username(client):
response = client.post("/auth/register", json={"username": "has space", "password": "correcthorse"})
assert response.status_code == 422
def test_auth_login_with_correct_credentials(client):
client.post("/auth/register", json={"username": "loginuser1", "password": "correcthorse"})
response = client.post("/auth/login", json={"username": "loginuser1", "password": "correcthorse"})
assert response.status_code == 200
body = response.json()
assert "access_token" in body and "refresh_token" in body
def test_auth_login_rejects_wrong_password(client):
client.post("/auth/register", json={"username": "loginuser2", "password": "correcthorse"})
response = client.post("/auth/login", json={"username": "loginuser2", "password": "wrongpassword"})
assert response.status_code == 401
def test_auth_login_rejects_unknown_username(client):
response = client.post("/auth/login", json={"username": "nosuchuser", "password": "whatever1"})
assert response.status_code == 401
def test_auth_login_rejects_user_with_no_password_set(client, db_session):
# e.g. a user who only ever linked Telegram (via /auth/telegram/login) and never
# registered a username/password of their own.
user = User(id=918280, username="telegramonly", phone_number="+15550009999")
db_session.add(user)
db_session.commit()
response = client.post("/auth/login", json={"username": "telegramonly", "password": "whatever1"})
assert response.status_code == 401
def test_auth_login_missing_fields(client):
response = client.post("/auth/login", json={"username": "someone"})
assert response.status_code == 422
# --- Telegram (account linking / chat scanning, not primary auth) ---
def test_auth_telegram_request_code(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
return_value={"phone_code_hash": "hash123", "is_registered": True},
)
response = client.post("/auth/request_code", json={"phone_number": "+15550001111"})
response = client.post("/auth/telegram/request_code", json={"phone_number": "+15550001111"})
assert response.status_code == 200
assert response.json()["status"] == "success"
assert response.json()["data"]["phone_code_hash"] == "hash123"
def test_auth_request_code_upstream_failure_returns_400(client, mocker):
def test_auth_telegram_request_code_upstream_failure_returns_400(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
side_effect=Exception("Telegram flood wait"),
)
response = client.post("/auth/request_code", json={"phone_number": "+15550002222"})
response = client.post("/auth/telegram/request_code", json={"phone_number": "+15550002222"})
assert response.status_code == 400
def test_auth_request_code_missing_field(client):
response = client.post("/auth/request_code", json={})
def test_auth_telegram_request_code_missing_field(client):
response = client.post("/auth/telegram/request_code", json={})
assert response.status_code == 422
def test_auth_request_code_rate_limited_per_phone(client, mocker):
def test_auth_telegram_request_code_rate_limited_per_phone(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
return_value={"phone_code_hash": "hash123", "is_registered": True},
)
phone = "+15550003333"
for _ in range(MAX_REQUESTS_PER_PHONE):
response = client.post("/auth/request_code", json={"phone_number": phone})
response = client.post("/auth/telegram/request_code", json={"phone_number": phone})
assert response.status_code == 200
response = client.post("/auth/request_code", json={"phone_number": phone})
response = client.post("/auth/telegram/request_code", json={"phone_number": phone})
assert response.status_code == 429
def test_auth_login_missing_fields(client):
response = client.post("/auth/login", json={"phone_number": "+1234567890"})
def test_auth_telegram_login_missing_fields(client):
response = client.post("/auth/telegram/login", json={"phone_number": "+1234567890"})
assert response.status_code == 422
def test_auth_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker):
def test_auth_telegram_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.login",
return_value={"session_string": "super-secret-telegram-session", "user_id": 918273},
)
response = client.post(
"/auth/login",
"/auth/telegram/login",
json={"phone_number": "+15550004444", "phone_code_hash": "hash123", "code": "11111"},
)
assert response.status_code == 200
......@@ -72,7 +140,7 @@ def test_auth_refresh_and_logout(client, mocker):
return_value={"session_string": "sess-abc", "user_id": 918274},
)
login_res = client.post(
"/auth/login",
"/auth/telegram/login",
json={"phone_number": "+15550005555", "phone_code_hash": "hash123", "code": "11111"},
)
refresh_token = login_res.json()["refresh_token"]
......@@ -93,12 +161,12 @@ def test_auth_refresh_and_logout(client, mocker):
def test_auth_chats_no_token(client):
response = client.get("/auth/chats")
response = client.get("/auth/telegram/chats")
assert response.status_code == 401
def test_auth_chats_music_no_token(client):
response = client.get("/auth/chats/123/music")
response = client.get("/auth/telegram/chats/123/music")
assert response.status_code == 401
......@@ -108,7 +176,7 @@ def test_auth_chats_with_token(client, auth_as, mocker):
"src.telegram_worker.telegram_sync.get_chats",
return_value=[{"id": 1, "title": "Test Chat", "type": "private"}],
)
response = client.get("/auth/chats", headers=headers)
response = client.get("/auth/telegram/chats", headers=headers)
assert response.status_code == 200
assert response.json()["chats"][0]["title"] == "Test Chat"
......@@ -119,7 +187,7 @@ def test_auth_chats_music_with_token(client, auth_as, mocker):
"src.telegram_worker.telegram_sync.get_chat_music",
return_value=[{"message_id": 1, "title": "Song", "artist": "Someone", "duration": 180, "file_name": "song.mp3"}],
)
response = client.get("/auth/chats/123/music", headers=headers)
response = client.get("/auth/telegram/chats/123/music", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment