File size: 9,064 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4598c11
 
2756f0f
4598c11
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""Registration, password and social sign-in, refresh-token rotation and the password reset flow."""

import logging
import uuid
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime, timedelta
from functools import lru_cache

from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.config import get_settings
from app.core.errors import Conflict, Unauthenticated, ValidationFailed
from app.core.rate_limit import RateLimiter
from app.core.security import create_access_token, hash_password, hash_token, new_opaque_token, verify_password
from app.integrations.email import EmailClient
from app.integrations.social_auth import InvalidSocialToken, SocialTokenVerifier
from app.modules.accounts.models import Account
from app.modules.accounts.schemas import UserOut
from app.modules.auth.repository import (
    AuthAccountRepository,
    AuthIdentityRepository,
    PasswordResetRepository,
    RefreshTokenRepository,
)
from app.modules.auth.schemas import AuthOut, SocialAuthOut, TokensOut

log = logging.getLogger(__name__)


@lru_cache
def _dummy_hash() -> str:
    return hash_password("timing-equaliser-password")


def _email_taken() -> Conflict:
    return Conflict("An account with this email already exists.", code="EMAIL_TAKEN")


def _token_revoked() -> Unauthenticated:
    return Unauthenticated("Your session has ended. Please sign in again.", code="TOKEN_REVOKED")


def _invalid_token(message: str = "We couldn't verify that sign-in. Please try again.") -> Unauthenticated:
    return Unauthenticated(message, code="INVALID_TOKEN")


class AuthService:
    def __init__(self, db: AsyncSession, limiter: RateLimiter, email: EmailClient | None = None,
                 verifier: SocialTokenVerifier | None = None):
        self.db = db
        self.limiter = limiter
        self.email = email
        self.verifier = verifier
        self.accounts = AuthAccountRepository(db)
        self.refresh_tokens = RefreshTokenRepository(db)
        self.resets = PasswordResetRepository(db)
        self.identities = AuthIdentityRepository(db)

    # Sign-up and sign-in

    async def register(self, email: str, password: str, role: str) -> AuthOut:
        if await self.accounts.by_email(email):
            raise _email_taken()
        account = await self._create_account(email=email, password_hash=hash_password(password), role=role)
        return await self._auth_body(account)

    async def login(self, email: str, password: str, client_ip: str) -> AuthOut:
        """Only failed attempts count. Limits are per (email, IP) and per IP, never per email alone,
        so failing logins from elsewhere cannot lock the real user out of their account."""
        email = email.strip().lower()
        keys = (f"login:email_ip:{email}:{client_ip}", f"login:ip:{client_ip}")
        self.limiter.check(*keys)
        account = await self.accounts.by_email(email)
        valid = verify_password(password, account.password_hash if account else _dummy_hash())
        if account is None or not valid:
            self.limiter.record(*keys)
            raise Unauthenticated("Wrong email or password.", code="INVALID_CREDENTIALS")
        return await self._auth_body(account)

    async def social(self, provider: str, id_token: str, role: str) -> SocialAuthOut:
        assert self.verifier is not None
        try:
            identity = await self.verifier.verify(provider, id_token)
        except InvalidSocialToken as exc:
            log.info("social token rejected: provider=%s reason=%s", provider, exc)
            raise _invalid_token() from exc

        is_new = False
        linked = await self.identities.first_by(provider=provider, subject=identity.subject)
        account = await self.accounts.get(linked.account_id) if linked else None
        if account is None:
            if not identity.email or not identity.email_verified:
                raise _invalid_token("This sign-in did not share a verified email address.")
            email = identity.email.strip().lower()
            account = await self.accounts.by_email(email)
            if account is None:
                account = await self._create_account(email=email, password_hash=None, role=role)
                is_new = True
            await self.identities.create(account_id=account.id, provider=provider, subject=identity.subject)
        body = await self._auth_body(account)
        return SocialAuthOut(user=body.user, tokens=body.tokens, is_new=is_new)

    # Refresh tokens

    async def refresh(self, refresh_token: str) -> TokensOut:
        now = datetime.now(UTC)
        token = await self.refresh_tokens.by_hash_for_update(hash_token(refresh_token))
        if token is None:
            raise _token_revoked()
        if token.revoked_at is not None:
            # A revoked token was replayed: assume theft and end the whole sign-in. Commit before raising,
            # because the request's unit of work rolls back on errors.
            await self.refresh_tokens.revoke_family(token.family_id, now)
            await self.db.commit()
            raise _token_revoked()
        if token.expires_at <= now:
            raise _token_revoked()
        await self.refresh_tokens.update(token, revoked_at=now)
        return await self._issue_tokens(token.account_id, token.family_id)

    async def logout(self, account: Account, refresh_token: str) -> None:
        token = await self.refresh_tokens.by_hash_for_update(hash_token(refresh_token))
        if token is not None and token.account_id == account.id and token.revoked_at is None:
            await self.refresh_tokens.update(token, revoked_at=datetime.now(UTC))

    # Password reset

    async def forgot_password(self, email: str, client_ip: str) -> Callable[[], Awaitable[None]] | None:
        """Always succeeds from the caller's view so the endpoint cannot be used to find accounts.

        Returns the email job for the controller to run after the response, so known and unknown
        addresses answer in the same time.
        """
        self.limiter.hit(f"forgot:email:{email}", f"forgot:ip:{client_ip}")
        account = await self.accounts.by_email(email)
        if account is None or not account.password_hash or self.email is None:
            return None
        settings = get_settings()
        token = new_opaque_token()
        await self.resets.create(account_id=account.id, token_hash=hash_token(token),
                                 expires_at=datetime.now(UTC) + timedelta(seconds=settings.password_reset_ttl_s))
        minutes = settings.password_reset_ttl_s // 60
        link = f"{settings.password_reset_url}?token={token}"
        sender, to = self.email, account.email

        async def send() -> None:
            try:
                await sender.send(
                    to, "Reset your Cognivision password",
                    f"Someone asked to reset the password for this account.\n\nSet a new password here: {link}\n\n"
                    f"The link works once and expires in {minutes} minutes. If it wasn't you, ignore this email.",
                )
            except Exception:  # the reset row stays; the user can ask again
                log.exception("password reset email failed")

        return send

    async def reset_password(self, token: str, password: str) -> None:
        now = datetime.now(UTC)
        reset = await self.resets.by_hash_for_update(hash_token(token))
        if reset is None or reset.used_at is not None or reset.expires_at <= now:
            raise ValidationFailed("This reset link is invalid or has expired.", code="TOKEN_INVALID")
        account = await self.accounts.get_or_404(reset.account_id)
        await self.resets.update(reset, used_at=now)
        await self.accounts.update(account, password_hash=hash_password(password))
        await self.refresh_tokens.revoke_all(account.id, now)

    # Helpers

    async def _create_account(self, **values) -> Account:
        try:
            async with self.db.begin_nested():
                return await self.accounts.create(**values)
        except IntegrityError as exc:  # a concurrent sign-up took the email
            raise _email_taken() from exc

    async def _issue_tokens(self, account_id: uuid.UUID, family_id: uuid.UUID | None = None) -> TokensOut:
        refresh = new_opaque_token()
        await self.refresh_tokens.create(
            account_id=account_id, token_hash=hash_token(refresh), family_id=family_id or uuid.uuid4(),
            expires_at=datetime.now(UTC) + timedelta(days=get_settings().refresh_token_ttl_days))
        access, expires_in = create_access_token(account_id)
        return TokensOut(access_token=access, refresh_token=refresh, expires_in=expires_in)

    async def _auth_body(self, account: Account) -> AuthOut:
        team_code = await self.accounts.team_code(account.team_id) if account.role == "player" else None
        return AuthOut(user=UserOut.build(account, team_code), tokens=await self._issue_tokens(account.id))