File size: 8,215 Bytes
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c49624
 
 
 
 
 
 
 
 
c6abe34
 
 
 
 
 
 
9ab3de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
035d434
 
 
 
9ab3de6
035d434
 
 
 
 
 
 
 
9ab3de6
 
c6abe34
 
9ab3de6
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ab3de6
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
9ab3de6
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
9ab3de6
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45dcdd6
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""
FastAPI dependency injection functions.

Provides common dependencies for authentication, authorization, 
and service access across all API endpoints.
"""
from typing import Optional
from fastapi import Depends, HTTPException, status, Query
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from app.config import get_settings, Settings
from app.core.security import decode_access_token
from app.core import AuthenticationError, AuthorizationError
from app.models.user import AccountType, TokenPayload
from app.services.supabase_client import SupabaseService, get_supabase_service


# OAuth2 bearer scheme for JWT tokens
security = HTTPBearer(auto_error=False)


async def get_settings_dep() -> Settings:
    """Dependency to get application settings."""
    return get_settings()


async def get_supabase(
    settings: Settings = Depends(get_settings_dep)
) -> SupabaseService:
    """Dependency to get Supabase service instance."""
    return get_supabase_service()


async def get_current_user_optional(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
) -> Optional[dict]:
    """
    Get current user from JWT token if present.
    Returns None if no token provided (for public endpoints).
    """
    if not credentials:
        return None
    
    token = credentials.credentials
    payload = decode_access_token(token)
    
    if not payload:
        return None
    
    return {
        "id": payload.get("sub"),
        "email": payload.get("email"),
        "account_type": payload.get("account_type"),
        "organization_id": payload.get("organization_id")
    }




async def get_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
    token_query: Optional[str] = Query(None, alias="token")
) -> dict:
    """
    Get current authenticated user from JWT token (Header or Query param).
    Raises HTTPException if not authenticated.
    """
    token = None
    if credentials:
        token = credentials.credentials
    elif token_query:
        token = token_query
        
    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    payload = decode_access_token(token)
    if not payload:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired token",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return {
        "id": payload.get("sub"),
        "email": payload.get("email"),
        "account_type": payload.get("account_type"),
        "organization_id": payload.get("organization_id")
    }

async def get_current_user_with_db(
    current_user: dict = Depends(get_current_user),
    supabase: SupabaseService = Depends(get_supabase)
) -> dict:
    """
    Enhanced version of get_current_user that fetches organization_id from DB 
    if it's missing in the JWT payload (e.g. newly linked account).
    """
    if current_user.get("organization_id"):
        return current_user
        
    # If missing, check database
    user_id = current_user["id"]
    account_type = current_user["account_type"]
    
    if account_type == AccountType.TEAM.value:
        orgs = await supabase.select("organizations", filters={"owner_id": user_id})
        if orgs:
            current_user["organization_id"] = orgs[0]["id"]
    elif account_type == AccountType.COACH.value:
        # Coaches are in organizations_staff
        staff = await supabase.select("organizations_staff", filters={"user_id": user_id})
        if staff:
            current_user["organization_id"] = staff[0]["organization_id"]
    elif account_type == AccountType.PLAYER.value:
        # Players are in players table
        players = await supabase.select("players", filters={"user_id": user_id})
        if players:
            # Only use if they are part of an organization (not personal profile)
            org_players = [p for p in players if p.get("organization_id")]
            if org_players:
                current_user["organization_id"] = org_players[0]["organization_id"]

    return current_user


async def require_team_account(
    current_user: dict = Depends(get_current_user_with_db),
) -> dict:
    """
    Dependency that requires a TEAM or COACH account type.
    Use for team-only endpoints.
    """
    allowed_types = [AccountType.TEAM.value, AccountType.COACH.value]
    if current_user.get("account_type") not in allowed_types:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This endpoint requires a TEAM or COACH account",
        )
    return current_user


async def require_organization_admin(
    current_user: dict = Depends(get_current_user_with_db),
) -> dict:
    """
    Dependency that requires a TEAM account type (Organization Owner).
    Use for critical administrative tasks like staff linking and settings.
    """
    if current_user.get("account_type") != AccountType.TEAM.value:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This operation requires organization owner administrative privileges",
        )
    return current_user

async def require_personal_account(
    current_user: dict = Depends(get_current_user_with_db),
) -> dict:
    """
    Dependency that requires a PERSONAL account type.
    Use for personal-only endpoints.
    """
    if current_user.get("account_type") != AccountType.PERSONAL.value:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This endpoint requires a PERSONAL account",
        )
    return current_user


async def require_linked_account(
    current_user: dict = Depends(get_current_user_with_db),
) -> dict:
    """
    Dependency that requires the user to be linked to an organization.
    """
    if not current_user.get("organization_id"):
        # For TEAM accounts, they might not have organization_id in token yet if just created,
        # but for players/coaches, they MUST be linked.
        if current_user.get("account_type") != AccountType.TEAM.value:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You must be linked to a team to access this feature",
            )
    return current_user


async def require_staff_member(
    current_user: dict = Depends(get_current_user_with_db),
) -> dict:
    """
    Dependency that requires the user to be a COACH or TEAM owner who is linked to an organization.
    Used for features delegated to coaching staff (match upload, scheduling, stats).
    """
    allowed_types = [AccountType.COACH.value, AccountType.TEAM.value]
    if current_user.get("account_type") not in allowed_types:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This feature is managed by the Team Owner or Coaching Staff",
        )
    if not current_user.get("organization_id"):
        # For TEAM accounts, we might need to fetch the org_id if not in token
        # but the check below is a safe guard.
        if current_user.get("account_type") != AccountType.TEAM.value:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Your account has not been linked to a team yet.",
            )
    return current_user

def require_owner_or_admin(resource_owner_id: str):
    """
    Factory for dependency that checks if user owns a resource.
    
    Usage:
        @router.delete("/items/{item_id}")
        async def delete_item(
            item_id: str,
            _: dict = Depends(require_owner_or_admin(item.owner_id))
        ):
            ...
    """
    async def dependency(current_user: dict = Depends(get_current_user)) -> dict:
        if current_user.get("id") != resource_owner_id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You don't have permission to access this resource",
            )
        return current_user
    return dependency