feat: add calendar subscription token functionality and ICS generation
- Introduced a new database model for calendar subscription tokens, allowing users to generate unique tokens for accessing their personal calendar. - Implemented API endpoint to return ICS files containing only the subscribing user's duties, enhancing user experience with personalized calendar access. - Added utility functions for generating ICS files from user duties, ensuring proper formatting and timezone handling. - Updated command handlers to support the new calendar link feature, providing users with easy access to their personal calendar subscriptions. - Included unit tests for the new functionality, ensuring reliability and correctness of token generation and ICS file creation.
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
"""Repository: get_or_create_user, get_duties, insert_duty, get_current_duty, group_duty_pins."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from duty_teller.db.models import User, Duty, GroupDutyPin
|
||||
from duty_teller.db.models import User, Duty, GroupDutyPin, CalendarSubscriptionToken
|
||||
|
||||
|
||||
def get_user_by_telegram_id(session: Session, telegram_user_id: int) -> User | None:
|
||||
@@ -98,6 +101,74 @@ def get_duties(
|
||||
return list(q.all())
|
||||
|
||||
|
||||
def get_duties_for_user(
|
||||
session: Session,
|
||||
user_id: int,
|
||||
from_date: str,
|
||||
to_date: str,
|
||||
) -> list[tuple[Duty, str]]:
|
||||
"""Return list of (Duty, full_name) for the given user overlapping the date range."""
|
||||
to_date_next = (
|
||||
datetime.fromisoformat(to_date + "T00:00:00") + timedelta(days=1)
|
||||
).strftime("%Y-%m-%d")
|
||||
q = (
|
||||
session.query(Duty, User.full_name)
|
||||
.join(User, Duty.user_id == User.id)
|
||||
.filter(
|
||||
Duty.user_id == user_id,
|
||||
Duty.start_at < to_date_next,
|
||||
Duty.end_at >= from_date,
|
||||
)
|
||||
)
|
||||
return list(q.all())
|
||||
|
||||
|
||||
def _token_hash(token: str) -> str:
|
||||
"""Return SHA256 hex digest of the token (constant-time comparison via hmac)."""
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def create_calendar_token(session: Session, user_id: int) -> str:
|
||||
"""
|
||||
Create a new calendar subscription token for the user.
|
||||
Removes any existing tokens for this user. Returns the raw token string.
|
||||
"""
|
||||
session.query(CalendarSubscriptionToken).filter(
|
||||
CalendarSubscriptionToken.user_id == user_id
|
||||
).delete(synchronize_session=False)
|
||||
raw_token = secrets.token_urlsafe(32)
|
||||
token_hash_val = _token_hash(raw_token)
|
||||
now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
record = CalendarSubscriptionToken(
|
||||
user_id=user_id,
|
||||
token_hash=token_hash_val,
|
||||
created_at=now_iso,
|
||||
)
|
||||
session.add(record)
|
||||
session.commit()
|
||||
return raw_token
|
||||
|
||||
|
||||
def get_user_by_calendar_token(session: Session, token: str) -> User | None:
|
||||
"""
|
||||
Find user by calendar subscription token. Uses constant-time comparison.
|
||||
Returns None if token is invalid or not found.
|
||||
"""
|
||||
token_hash_val = _token_hash(token)
|
||||
row = (
|
||||
session.query(CalendarSubscriptionToken, User)
|
||||
.join(User, CalendarSubscriptionToken.user_id == User.id)
|
||||
.filter(CalendarSubscriptionToken.token_hash == token_hash_val)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
# Constant-time compare to avoid timing leaks (token_hash is already hashed).
|
||||
if not hmac.compare_digest(row[0].token_hash, token_hash_val):
|
||||
return None
|
||||
return row[1]
|
||||
|
||||
|
||||
def insert_duty(
|
||||
session: Session,
|
||||
user_id: int,
|
||||
|
||||
Reference in New Issue
Block a user