Added ref login
This commit is contained in:
Vendored
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"python.testing.pytestArgs": [
|
||||||
|
"backend"
|
||||||
|
],
|
||||||
|
"python.testing.unittestEnabled": false,
|
||||||
|
"python.testing.pytestEnabled": true
|
||||||
|
}
|
||||||
+19
-15
@@ -6,7 +6,7 @@ from fastapi.security import OAuth2PasswordBearer
|
|||||||
import jwt
|
import jwt
|
||||||
from jwt.exceptions import PyJWTError
|
from jwt.exceptions import PyJWTError
|
||||||
|
|
||||||
from .config import SECRET_KEY, ALGORITHM, ADMIN_USER
|
from .config import SECRET_KEY, ALGORITHM
|
||||||
|
|
||||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
|
||||||
oauth2_scheme_optional = OAuth2PasswordBearer(tokenUrl="auth/token", auto_error=False)
|
oauth2_scheme_optional = OAuth2PasswordBearer(tokenUrl="auth/token", auto_error=False)
|
||||||
@@ -20,43 +20,47 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
|||||||
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
|
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
|
||||||
|
|
||||||
to_encode.update({"exp": expire})
|
to_encode.update({"exp": expire})
|
||||||
|
|
||||||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||||
return encoded_jwt
|
return encoded_jwt
|
||||||
|
|
||||||
|
|
||||||
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
async def get_authenticated_user(token: str = Depends(oauth2_scheme)):
|
||||||
|
"""Allows both Admins and Refs"""
|
||||||
credentials_exception = HTTPException(
|
credentials_exception = HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Could not validate credentials",
|
detail="Could not validate credentials",
|
||||||
headers={"WWW-Authenticate": "Bearer"},
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
username = payload.get("sub")
|
role = payload.get("role")
|
||||||
|
if role not in ["admin", "ref"]:
|
||||||
if username is None or username != ADMIN_USER:
|
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
|
return payload
|
||||||
except PyJWTError:
|
except PyJWTError:
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
|
|
||||||
return username
|
|
||||||
|
async def get_admin_user(token: str = Depends(oauth2_scheme)):
|
||||||
|
"""Strictly allows ONLY Admins"""
|
||||||
|
user = await get_authenticated_user(token)
|
||||||
|
if user.get("role") != "admin":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required"
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
async def get_optional_user(
|
async def get_optional_user(
|
||||||
token: Optional[str] = Depends(oauth2_scheme_optional),
|
token: Optional[str] = Depends(oauth2_scheme_optional),
|
||||||
) -> Optional[str]:
|
) -> Optional[dict]:
|
||||||
|
"""Returns user payload if valid token exists, else None"""
|
||||||
if not token:
|
if not token:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
username = payload.get("sub")
|
if payload.get("role") in ["admin", "ref"]:
|
||||||
if username == ADMIN_USER:
|
return payload
|
||||||
return username
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -13,8 +13,13 @@ ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours
|
|||||||
ADMIN_USER = os.getenv("ADMIN_USER", "admin")
|
ADMIN_USER = os.getenv("ADMIN_USER", "admin")
|
||||||
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin")
|
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin")
|
||||||
|
|
||||||
|
# Ref Credentials
|
||||||
|
REF_USER = os.getenv("REF_USER", "ref")
|
||||||
|
REF_PASSWORD = os.getenv("REF_PASSWORD", "ref")
|
||||||
|
|
||||||
password_hash = PasswordHash.recommended()
|
password_hash = PasswordHash.recommended()
|
||||||
ADMIN_HASH = password_hash.hash(ADMIN_PASSWORD)
|
ADMIN_HASH = password_hash.hash(ADMIN_PASSWORD)
|
||||||
|
REF_HASH = password_hash.hash(REF_PASSWORD)
|
||||||
|
|
||||||
|
|
||||||
def verify_password(plain_password, hashed_password):
|
def verify_password(plain_password, hashed_password):
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
# backend/app/core/utils.py
|
|
||||||
from .brackets import Match
|
|
||||||
|
|
||||||
|
|
||||||
class MermaidLive:
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _get_visual_target(match: Match, is_win=True) -> Match | None:
|
|
||||||
current = match.next_win if is_win else match.next_loss
|
|
||||||
while current and current.is_bye:
|
|
||||||
current = current.next_win
|
|
||||||
return current
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def export(cls, matches: list[Match]) -> None:
|
|
||||||
print("\n--- COPY TO MERMAID.LIVE ---")
|
|
||||||
print("graph LR")
|
|
||||||
print(" classDef wb stroke:#01579b,stroke-width:2px;")
|
|
||||||
print(" classDef lb stroke:#b71c1c,stroke-width:2px,stroke-dasharray: 5 5;")
|
|
||||||
print(" classDef final stroke:#e65100,stroke-width:4px;")
|
|
||||||
|
|
||||||
wb_nodes = [
|
|
||||||
m
|
|
||||||
for m in matches
|
|
||||||
if "WB" in m.name or "Semifinal" in m.name or "Winners Final" in m.name
|
|
||||||
]
|
|
||||||
|
|
||||||
lb_nodes = [m for m in matches if "LB" in m.name or "Losers Final" in m.name]
|
|
||||||
final_nodes = [
|
|
||||||
m for m in matches if "Grand Final" in m.name or "3rd Place" in m.name
|
|
||||||
]
|
|
||||||
|
|
||||||
print(" subgraph Winners Bracket")
|
|
||||||
for m in wb_nodes:
|
|
||||||
cls._print_node(m, "wb")
|
|
||||||
print(" end")
|
|
||||||
|
|
||||||
if lb_nodes:
|
|
||||||
print(" subgraph Losers Bracket")
|
|
||||||
for m in lb_nodes:
|
|
||||||
cls._print_node(m, "lb")
|
|
||||||
print(" end")
|
|
||||||
|
|
||||||
print(" subgraph Championship / 3rd Place")
|
|
||||||
for m in final_nodes:
|
|
||||||
cls._print_node(m, "final")
|
|
||||||
print(" end")
|
|
||||||
|
|
||||||
for m in matches:
|
|
||||||
target_win = cls._get_visual_target(m, is_win=True)
|
|
||||||
if target_win:
|
|
||||||
print(f" M{m.id} --> M{target_win.id}")
|
|
||||||
|
|
||||||
target_loss = cls._get_visual_target(m, is_win=False)
|
|
||||||
if target_loss:
|
|
||||||
print(f" M{m.id} -.-> M{target_loss.id}")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _print_node(m: Match, style: str) -> None:
|
|
||||||
label = m.name
|
|
||||||
if m.teams[0] and m.teams[1]:
|
|
||||||
label += f" ({m.teams[0]} vs {m.teams[1]})"
|
|
||||||
print(f' M{m.id}["{label}"]:::{style}')
|
|
||||||
+19
-12
@@ -6,11 +6,13 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
|||||||
from fastapi.security import OAuth2PasswordRequestForm
|
from fastapi.security import OAuth2PasswordRequestForm
|
||||||
|
|
||||||
from ..schemas import Token
|
from ..schemas import Token
|
||||||
from ..core.auth import create_access_token, get_current_user
|
from ..core.auth import create_access_token, get_authenticated_user
|
||||||
from ..core.config import (
|
from ..core.config import (
|
||||||
ACCESS_TOKEN_EXPIRE_MINUTES,
|
ACCESS_TOKEN_EXPIRE_MINUTES,
|
||||||
ADMIN_HASH,
|
ADMIN_HASH,
|
||||||
ADMIN_USER,
|
ADMIN_USER,
|
||||||
|
REF_HASH,
|
||||||
|
REF_USER,
|
||||||
verify_password,
|
verify_password,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -21,14 +23,18 @@ router = APIRouter(prefix="/auth", tags=["Auth"])
|
|||||||
async def login_for_access_token(
|
async def login_for_access_token(
|
||||||
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
|
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
|
||||||
):
|
):
|
||||||
if form_data.username != ADMIN_USER:
|
role = None
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="Incorrect username or password",
|
|
||||||
headers={"WWW-Authenticate": "Bearer"},
|
|
||||||
)
|
|
||||||
|
|
||||||
if not verify_password(form_data.password, ADMIN_HASH):
|
if form_data.username == ADMIN_USER and verify_password(
|
||||||
|
form_data.password, ADMIN_HASH
|
||||||
|
):
|
||||||
|
role = "admin"
|
||||||
|
elif form_data.username == REF_USER and verify_password(
|
||||||
|
form_data.password, REF_HASH
|
||||||
|
):
|
||||||
|
role = "ref"
|
||||||
|
|
||||||
|
if not role:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Incorrect username or password",
|
detail="Incorrect username or password",
|
||||||
@@ -37,12 +43,13 @@ async def login_for_access_token(
|
|||||||
|
|
||||||
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
access_token = create_access_token(
|
access_token = create_access_token(
|
||||||
data={"sub": form_data.username}, expires_delta=access_token_expires
|
data={"sub": form_data.username, "role": role},
|
||||||
|
expires_delta=access_token_expires,
|
||||||
)
|
)
|
||||||
|
|
||||||
return {"access_token": access_token, "token_type": "bearer"}
|
return {"access_token": access_token, "token_type": "bearer", "role": role}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/check")
|
@router.get("/check")
|
||||||
async def check_auth(user: str = Depends(get_current_user)):
|
async def check_auth(user: dict = Depends(get_authenticated_user)):
|
||||||
return {"is_admin": True, "user": user}
|
return {"role": user.get("role"), "user": user.get("sub")}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from sqlalchemy.orm import Session
|
|||||||
|
|
||||||
from ... import crud, schemas
|
from ... import crud, schemas
|
||||||
from ...constants import SUCCESS
|
from ...constants import SUCCESS
|
||||||
from ...core.auth import get_current_user
|
from ...core.auth import get_admin_user
|
||||||
from ...core.websocket_manager import send_ws_update
|
from ...core.websocket_manager import send_ws_update
|
||||||
from ...database import get_db
|
from ...database import get_db
|
||||||
from . import router
|
from . import router
|
||||||
@@ -20,7 +20,7 @@ async def create_court(
|
|||||||
id: str,
|
id: str,
|
||||||
court: schemas.CourtCreate,
|
court: schemas.CourtCreate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
new_court = crud.create_court(db, id, court)
|
new_court = crud.create_court(db, id, court)
|
||||||
if not new_court:
|
if not new_court:
|
||||||
@@ -35,7 +35,7 @@ async def update_courts(
|
|||||||
id: str,
|
id: str,
|
||||||
courts: list[str],
|
courts: list[str],
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
t = crud.update_tournament_courts(db, id, courts)
|
t = crud.update_tournament_courts(db, id, courts)
|
||||||
if not t:
|
if not t:
|
||||||
@@ -50,7 +50,7 @@ async def delete_court(
|
|||||||
id: str,
|
id: str,
|
||||||
court_id: int,
|
court_id: int,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
success = crud.delete_court(db, id, court_id)
|
success = crud.delete_court(db, id, court_id)
|
||||||
if not success:
|
if not success:
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ from sqlalchemy.orm import Session
|
|||||||
|
|
||||||
from ... import crud, schemas
|
from ... import crud, schemas
|
||||||
from ...database import get_db
|
from ...database import get_db
|
||||||
from ...core.auth import get_current_user
|
from ...core.auth import get_admin_user
|
||||||
from . import router
|
from . import router
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{id}/settings", response_model=schemas.TournamentSettingsResponse)
|
@router.get("/{id}/settings", response_model=schemas.TournamentSettingsResponse)
|
||||||
def get_tournament(
|
def get_tournament(
|
||||||
id: str, db: Session = Depends(get_db), user: str = Depends(get_current_user)
|
id: str, db: Session = Depends(get_db), user: dict = Depends(get_admin_user)
|
||||||
):
|
):
|
||||||
t = crud.get_tournament(db, id)
|
t = crud.get_tournament(db, id)
|
||||||
if not t:
|
if not t:
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from sqlalchemy.orm import Session
|
|||||||
|
|
||||||
from ... import crud, schemas
|
from ... import crud, schemas
|
||||||
from ...constants import SUCCESS
|
from ...constants import SUCCESS
|
||||||
from ...core.auth import get_current_user
|
from ...core.auth import get_admin_user
|
||||||
from ...core.websocket_manager import send_ws_update
|
from ...core.websocket_manager import send_ws_update
|
||||||
from ...database import get_db
|
from ...database import get_db
|
||||||
from . import router
|
from . import router
|
||||||
@@ -20,7 +20,7 @@ async def create_team(
|
|||||||
id: str,
|
id: str,
|
||||||
team: schemas.TeamCreate,
|
team: schemas.TeamCreate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
new_team = crud.create_team(db, id, team)
|
new_team = crud.create_team(db, id, team)
|
||||||
if not new_team:
|
if not new_team:
|
||||||
@@ -35,7 +35,7 @@ async def update_teams(
|
|||||||
id: str,
|
id: str,
|
||||||
teams: list[str],
|
teams: list[str],
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
t = crud.update_tournament_teams(db, id, teams)
|
t = crud.update_tournament_teams(db, id, teams)
|
||||||
if not t:
|
if not t:
|
||||||
@@ -50,7 +50,7 @@ async def delete_team(
|
|||||||
id: str,
|
id: str,
|
||||||
team_id: int,
|
team_id: int,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
success = crud.delete_team(db, id, team_id)
|
success = crud.delete_team(db, id, team_id)
|
||||||
if not success:
|
if not success:
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from ... import crud, schemas
|
|||||||
from ...constants import SUCCESS
|
from ...constants import SUCCESS
|
||||||
from ...core.websocket_manager import send_ws_update
|
from ...core.websocket_manager import send_ws_update
|
||||||
from ...database import get_db
|
from ...database import get_db
|
||||||
from ...core.auth import get_current_user
|
from ...core.auth import get_admin_user
|
||||||
from . import router
|
from . import router
|
||||||
|
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ from . import router
|
|||||||
async def create_tournament(
|
async def create_tournament(
|
||||||
data: schemas.TournamentCreate,
|
data: schemas.TournamentCreate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
new_t = crud.create_tournament(db, data)
|
new_t = crud.create_tournament(db, data)
|
||||||
await send_ws_update(new_t.id)
|
await send_ws_update(new_t.id)
|
||||||
@@ -39,7 +39,7 @@ async def update_settings(
|
|||||||
id: str,
|
id: str,
|
||||||
data: schemas.TournamentUpdate,
|
data: schemas.TournamentUpdate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: str = Depends(get_current_user),
|
user: dict = Depends(get_admin_user),
|
||||||
):
|
):
|
||||||
t = crud.update_tournament_details(db, id, data)
|
t = crud.update_tournament_details(db, id, data)
|
||||||
if not t:
|
if not t:
|
||||||
@@ -51,7 +51,7 @@ async def update_settings(
|
|||||||
|
|
||||||
@router.delete("/{id}")
|
@router.delete("/{id}")
|
||||||
async def delete_tournament(
|
async def delete_tournament(
|
||||||
id: str, db: Session = Depends(get_db), user: str = Depends(get_current_user)
|
id: str, db: Session = Depends(get_db), user: dict = Depends(get_admin_user)
|
||||||
):
|
):
|
||||||
success = crud.delete_tournament(db, id)
|
success = crud.delete_tournament(db, id)
|
||||||
if not success:
|
if not success:
|
||||||
|
|||||||
@@ -110,3 +110,4 @@ class TournamentSettingsResponse(TournamentOut):
|
|||||||
class Token(BaseModel):
|
class Token(BaseModel):
|
||||||
access_token: str
|
access_token: str
|
||||||
token_type: str
|
token_type: str
|
||||||
|
role: str | None
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
from typing import AsyncGenerator, Generator
|
from typing import AsyncGenerator, Generator
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from app.core.auth import get_current_user, get_optional_user
|
from app.core.auth import get_admin_user, get_optional_user
|
||||||
from app.database import Base, get_db
|
from app.database import Base, get_db
|
||||||
|
|
||||||
# Import your app and models
|
# Import your app and models
|
||||||
@@ -52,7 +52,7 @@ async def client(db: Session) -> AsyncGenerator[AsyncClient, None]:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# Strict Auth: Always requires a token (simulated by header presence)
|
# Strict Auth: Always requires a token (simulated by header presence)
|
||||||
def override_get_current_user(request: Request):
|
def override_get_admin_user(request: Request):
|
||||||
if "Authorization" not in request.headers:
|
if "Authorization" not in request.headers:
|
||||||
# Let FastAPI raise the 401 naturally if header is missing
|
# Let FastAPI raise the 401 naturally if header is missing
|
||||||
raise pytest.skip("Auth header missing in strict auth test")
|
raise pytest.skip("Auth header missing in strict auth test")
|
||||||
@@ -65,7 +65,7 @@ async def client(db: Session) -> AsyncGenerator[AsyncClient, None]:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
app.dependency_overrides[get_db] = override_get_db
|
app.dependency_overrides[get_db] = override_get_db
|
||||||
app.dependency_overrides[get_current_user] = override_get_current_user
|
app.dependency_overrides[get_admin_user] = override_get_admin_user
|
||||||
app.dependency_overrides[get_optional_user] = override_get_optional_user
|
app.dependency_overrides[get_optional_user] = override_get_optional_user
|
||||||
|
|
||||||
async with AsyncClient(
|
async with AsyncClient(
|
||||||
|
|||||||
Generated
+3
-3
@@ -5029,9 +5029,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/undici": {
|
"node_modules/undici": {
|
||||||
"version": "7.22.0",
|
"version": "7.24.3",
|
||||||
"resolved": "https://registry.npmjs.org/undici/-/undici-7.22.0.tgz",
|
"resolved": "https://registry.npmjs.org/undici/-/undici-7.24.3.tgz",
|
||||||
"integrity": "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg==",
|
"integrity": "sha512-eJdUmK/Wrx2d+mnWWmwwLRyA7OQCkLap60sk3dOK4ViZR7DKwwptwuIvFBg2HaiP9ESaEdhtpSymQPvytpmkCA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Outlet } from 'react-router-dom';
|
import { Outlet } from 'react-router-dom';
|
||||||
import { getToken } from '../../services/api';
|
import api, { getToken } from '../../services/api';
|
||||||
import ThemeButton from "../UI/ThemeButton";
|
import ThemeButton from "../UI/ThemeButton";
|
||||||
import Navbar from './Navbar';
|
import Navbar from './Navbar';
|
||||||
|
|
||||||
@@ -14,17 +14,32 @@ interface LayoutProps {
|
|||||||
export interface OutletContextType {
|
export interface OutletContextType {
|
||||||
setNavTitle: React.Dispatch<React.SetStateAction<string>>;
|
setNavTitle: React.Dispatch<React.SetStateAction<string>>;
|
||||||
setNavSubtitle: React.Dispatch<React.SetStateAction<string>>;
|
setNavSubtitle: React.Dispatch<React.SetStateAction<string>>;
|
||||||
isAdmin: boolean;
|
role: 'admin' | 'ref' | null;
|
||||||
showSettings: boolean;
|
showSettings: boolean;
|
||||||
setShowSettings: React.Dispatch<React.SetStateAction<boolean>>;
|
setShowSettings: React.Dispatch<React.SetStateAction<boolean>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Layout({ darkMode, setDarkMode }: LayoutProps) {
|
export default function Layout({ darkMode, setDarkMode }: LayoutProps) {
|
||||||
const [isAdmin] = useState<boolean>(!!getToken());
|
const [role, setRole] = useState<'admin' | 'ref' | null>(null);
|
||||||
const [navTitle, setNavTitle] = useState<string>('');
|
const [navTitle, setNavTitle] = useState<string>('');
|
||||||
const [navSubtitle, setNavSubtitle] = useState<string>('');
|
const [navSubtitle, setNavSubtitle] = useState<string>('');
|
||||||
const [showSettings, setShowSettings] = useState<boolean>(false);
|
const [showSettings, setShowSettings] = useState<boolean>(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const verifyAuth = async () => {
|
||||||
|
if (getToken()) {
|
||||||
|
try {
|
||||||
|
const res = await api.get<{ role: 'admin' | 'ref' }>('/auth/check');
|
||||||
|
setRole(res.role);
|
||||||
|
} catch {
|
||||||
|
setRole(null);
|
||||||
|
localStorage.removeItem('volleyToken');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
verifyAuth();
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (navTitle) {
|
if (navTitle) {
|
||||||
document.title = `${navTitle} | VolleyManager`;
|
document.title = `${navTitle} | VolleyManager`;
|
||||||
@@ -41,7 +56,7 @@ export default function Layout({ darkMode, setDarkMode }: LayoutProps) {
|
|||||||
const contextValue: OutletContextType = {
|
const contextValue: OutletContextType = {
|
||||||
setNavTitle,
|
setNavTitle,
|
||||||
setNavSubtitle,
|
setNavSubtitle,
|
||||||
isAdmin,
|
role,
|
||||||
showSettings,
|
showSettings,
|
||||||
setShowSettings
|
setShowSettings
|
||||||
};
|
};
|
||||||
@@ -52,7 +67,7 @@ export default function Layout({ darkMode, setDarkMode }: LayoutProps) {
|
|||||||
<Navbar
|
<Navbar
|
||||||
title={navTitle}
|
title={navTitle}
|
||||||
subtitle={navSubtitle}
|
subtitle={navSubtitle}
|
||||||
isAdmin={isAdmin}
|
isAuthenticated={!!role}
|
||||||
onLogout={handleLogout}
|
onLogout={handleLogout}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ import { Link } from 'react-router-dom';
|
|||||||
interface NavbarProps {
|
interface NavbarProps {
|
||||||
title: string;
|
title: string;
|
||||||
subtitle: string;
|
subtitle: string;
|
||||||
isAdmin: boolean;
|
isAuthenticated: boolean;
|
||||||
onLogout: () => void;
|
onLogout: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Navbar({ title, subtitle, isAdmin, onLogout }: NavbarProps) {
|
export default function Navbar({ title, subtitle, isAuthenticated, onLogout }: NavbarProps) {
|
||||||
return (
|
return (
|
||||||
<nav className="transition-colors bg-zinc-50 dark:bg-zinc-900 border-b border-zinc-300 dark:border-zinc-800 sticky top-0 z-100 px-3 sm:px-6 py-3 sm:py-4 flex justify-between items-center shadow-md shrink-0">
|
<nav className="transition-colors bg-zinc-50 dark:bg-zinc-900 border-b border-zinc-300 dark:border-zinc-800 sticky top-0 z-100 px-3 sm:px-6 py-3 sm:py-4 flex justify-between items-center shadow-md shrink-0">
|
||||||
<Link to="/" className="flex items-center gap-2 sm:gap-4 cursor-pointer group select-none shrink-0">
|
<Link to="/" className="flex items-center gap-2 sm:gap-4 cursor-pointer group select-none shrink-0">
|
||||||
@@ -35,7 +35,7 @@ export default function Navbar({ title, subtitle, isAdmin, onLogout }: NavbarPro
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-2 sm:gap-4 items-center shrink-0">
|
<div className="flex gap-2 sm:gap-4 items-center shrink-0">
|
||||||
{isAdmin ? (
|
{isAuthenticated ? (
|
||||||
<>
|
<>
|
||||||
<button onClick={onLogout} title="Sign Out" className="text-zinc-400 hover:text-red-500 transition active:scale-90 shrink-0">
|
<button onClick={onLogout} title="Sign Out" className="text-zinc-400 hover:text-red-500 transition active:scale-90 shrink-0">
|
||||||
<LogOut size={18} className="sm:size-5.5" />
|
<LogOut size={18} className="sm:size-5.5" />
|
||||||
|
|||||||
@@ -21,12 +21,12 @@ interface MatchData {
|
|||||||
|
|
||||||
interface ScoreFormProps {
|
interface ScoreFormProps {
|
||||||
match: MatchData;
|
match: MatchData;
|
||||||
isAdmin: boolean;
|
isAuthenticated: boolean;
|
||||||
onSubmit: (id: string | number, sets: SetData[], code: string) => Promise<void>;
|
onSubmit: (id: string | number, sets: SetData[], code: string) => Promise<void>;
|
||||||
onClear: (id: string | number, code: string) => Promise<void>;
|
onClear: (id: string | number, code: string) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ScoreForm = ({ match, isAdmin, onSubmit, onClear }: ScoreFormProps) => {
|
const ScoreForm = ({ match, isAuthenticated, onSubmit, onClear }: ScoreFormProps) => {
|
||||||
const [sets, setSets] = useState<SetData[]>(match.sets && match.sets.length ? match.sets : [{ p1: '', p2: '' }]);
|
const [sets, setSets] = useState<SetData[]>(match.sets && match.sets.length ? match.sets : [{ p1: '', p2: '' }]);
|
||||||
const [code, setCode] = useState<string>('');
|
const [code, setCode] = useState<string>('');
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -71,7 +71,7 @@ const ScoreForm = ({ match, isAdmin, onSubmit, onClear }: ScoreFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isAdmin && (
|
{!isAuthenticated && (
|
||||||
<div className="bg-zinc-50 dark:bg-zinc-950 p-4 rounded-lg border border-gray-200 dark:border-zinc-800">
|
<div className="bg-zinc-50 dark:bg-zinc-950 p-4 rounded-lg border border-gray-200 dark:border-zinc-800">
|
||||||
<label className="block text-xs font-bold text-orange-500 uppercase mb-2">Tournament Code</label>
|
<label className="block text-xs font-bold text-orange-500 uppercase mb-2">Tournament Code</label>
|
||||||
<input
|
<input
|
||||||
@@ -163,19 +163,19 @@ interface ScoreModalProps {
|
|||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
match: MatchData | null;
|
match: MatchData | null;
|
||||||
isAdmin: boolean;
|
isAuthenticated: boolean;
|
||||||
onSubmit: (id: string | number, sets: SetData[], code: string) => Promise<void>;
|
onSubmit: (id: string | number, sets: SetData[], code: string) => Promise<void>;
|
||||||
onClear: (id: string | number, code: string) => Promise<void>;
|
onClear: (id: string | number, code: string) => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function ScoreModal({ isOpen, onClose, match, isAdmin, onSubmit, onClear }: ScoreModalProps) {
|
export default function ScoreModal({ isOpen, onClose, match, isAuthenticated, onSubmit, onClear }: ScoreModalProps) {
|
||||||
if (!isOpen || !match) return null;
|
if (!isOpen || !match) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal isOpen={isOpen} onClose={onClose} title={`Match #${match.number}`} icon={Trophy}>
|
<Modal isOpen={isOpen} onClose={onClose} title={`Match #${match.number}`} icon={Trophy}>
|
||||||
<ScoreForm
|
<ScoreForm
|
||||||
match={match}
|
match={match}
|
||||||
isAdmin={isAdmin}
|
isAuthenticated={isAuthenticated}
|
||||||
onSubmit={async (id, sets, code) => {
|
onSubmit={async (id, sets, code) => {
|
||||||
await onSubmit(id, sets, code);
|
await onSubmit(id, sets, code);
|
||||||
onClose();
|
onClose();
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import TournamentForm from '../components/Forms/TournamentForm';
|
|||||||
import Modal from '../components/UI/Modal';
|
import Modal from '../components/UI/Modal';
|
||||||
import api, { WS_URL } from '../services/api';
|
import api, { WS_URL } from '../services/api';
|
||||||
|
|
||||||
|
|
||||||
export interface TournamentType {
|
export interface TournamentType {
|
||||||
id: string | number;
|
id: string | number;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -21,13 +20,13 @@ export interface TournamentType {
|
|||||||
interface OutletContextType {
|
interface OutletContextType {
|
||||||
setNavTitle: (title: string) => void;
|
setNavTitle: (title: string) => void;
|
||||||
setNavSubtitle: (subtitle: string) => void;
|
setNavSubtitle: (subtitle: string) => void;
|
||||||
isAdmin: boolean;
|
role: 'admin' | 'ref' | null;
|
||||||
showSettings: boolean;
|
showSettings: boolean;
|
||||||
setShowSettings: (show: boolean) => void;
|
setShowSettings: (show: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
const { setNavTitle, setNavSubtitle, isAdmin, showSettings, setShowSettings } = useOutletContext<OutletContextType>();
|
const { setNavTitle, setNavSubtitle, role, showSettings, setShowSettings } = useOutletContext<OutletContextType>();
|
||||||
|
|
||||||
const [tournaments, setTournaments] = useState<TournamentType[]>([]);
|
const [tournaments, setTournaments] = useState<TournamentType[]>([]);
|
||||||
const [editTarget, setEditTarget] = useState<TournamentType | null>(null);
|
const [editTarget, setEditTarget] = useState<TournamentType | null>(null);
|
||||||
@@ -48,7 +47,6 @@ export default function Dashboard() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setNavTitle('Dashboard');
|
setNavTitle('Dashboard');
|
||||||
setNavSubtitle('');
|
setNavSubtitle('');
|
||||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
|
||||||
void loadDashboard();
|
void loadDashboard();
|
||||||
|
|
||||||
localStorage.removeItem('volley_view');
|
localStorage.removeItem('volley_view');
|
||||||
@@ -114,7 +112,7 @@ export default function Dashboard() {
|
|||||||
<div className="h-full overflow-y-auto pt-8 sm:pt-12 pb-32">
|
<div className="h-full overflow-y-auto pt-8 sm:pt-12 pb-32">
|
||||||
<div className="container mx-auto max-w-5xl px-4 space-y-12">
|
<div className="container mx-auto max-w-5xl px-4 space-y-12">
|
||||||
|
|
||||||
{isAdmin && (
|
{role === 'admin' && (
|
||||||
<div className="flex justify-center md:justify-end">
|
<div className="flex justify-center md:justify-end">
|
||||||
<button onClick={() => { setEditTarget(null); setShowSettings(true); }} className="bg-orange-600 hover:bg-orange-500 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 text-[10px] font-black uppercase tracking-wider shadow-xl shadow-orange-600/20 active:scale-95 transition">
|
<button onClick={() => { setEditTarget(null); setShowSettings(true); }} className="bg-orange-600 hover:bg-orange-500 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 text-[10px] font-black uppercase tracking-wider shadow-xl shadow-orange-600/20 active:scale-95 transition">
|
||||||
<Plus size={16} strokeWidth={4} /> Create
|
<Plus size={16} strokeWidth={4} /> Create
|
||||||
@@ -131,7 +129,7 @@ export default function Dashboard() {
|
|||||||
</span> Live Events
|
</span> Live Events
|
||||||
</h2>
|
</h2>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
{groups.live.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
|
{groups.live.map(t => <DashCard key={t.id} t={t} isAdmin={role === 'admin'} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
@@ -143,7 +141,7 @@ export default function Dashboard() {
|
|||||||
{groups.future.length > 0 ? (
|
{groups.future.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
{futureShow.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
|
{futureShow.map(t => <DashCard key={t.id} t={t} isAdmin={role === 'admin'} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
|
||||||
</div>
|
</div>
|
||||||
{groups.future.length > 4 && (
|
{groups.future.length > 4 && (
|
||||||
<div className="mt-8 text-center">
|
<div className="mt-8 text-center">
|
||||||
@@ -165,7 +163,7 @@ export default function Dashboard() {
|
|||||||
</button>
|
</button>
|
||||||
{showPast && (
|
{showPast && (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 opacity-75 hover:opacity-100 transition-opacity">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 opacity-75 hover:opacity-100 transition-opacity">
|
||||||
{groups.past.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
|
{groups.past.map(t => <DashCard key={t.id} t={t} isAdmin={role === 'admin'} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -43,8 +43,12 @@ export default function Login() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h1 className="text-2xl font-black text-center text-zinc-900 dark:text-white tracking-tight mb-2">Admin Access</h1>
|
<h1 className="text-2xl font-black text-center text-zinc-900 dark:text-white tracking-tight mb-2">
|
||||||
<p className="text-center text-zinc-500 text-sm font-medium mb-8">Enter administrative credentials</p>
|
Staff Login
|
||||||
|
</h1>
|
||||||
|
<p className="text-center text-zinc-500 text-sm font-medium mb-8">
|
||||||
|
Enter staff credentials
|
||||||
|
</p>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-bold uppercase tracking-wide rounded-xl text-center border border-red-100 dark:border-red-900/50">
|
<div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-bold uppercase tracking-wide rounded-xl text-center border border-red-100 dark:border-red-900/50">
|
||||||
|
|||||||
@@ -52,12 +52,12 @@ export interface ProcessedMatch extends RawMatch {
|
|||||||
interface OutletContextType {
|
interface OutletContextType {
|
||||||
setNavTitle: (title: string) => void;
|
setNavTitle: (title: string) => void;
|
||||||
setNavSubtitle: (subtitle: string) => void;
|
setNavSubtitle: (subtitle: string) => void;
|
||||||
isAdmin: boolean;
|
role: 'admin' | 'ref' | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Tournament() {
|
export default function Tournament() {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
const { setNavTitle, setNavSubtitle, isAdmin } = useOutletContext<OutletContextType>();
|
const { setNavTitle, setNavSubtitle, role } = useOutletContext<OutletContextType>();
|
||||||
|
|
||||||
const [matches, setMatches] = useState<ProcessedMatch[]>([]);
|
const [matches, setMatches] = useState<ProcessedMatch[]>([]);
|
||||||
const [view, setView] = useState<string>(() => localStorage.getItem('volley_view') || 'bracket');
|
const [view, setView] = useState<string>(() => localStorage.getItem('volley_view') || 'bracket');
|
||||||
@@ -190,7 +190,11 @@ export default function Tournament() {
|
|||||||
<CalendarDays size={16} /> Schedule
|
<CalendarDays size={16} /> Schedule
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{isAdmin && <button onClick={() => setShowSettings(true)} className="p-2 text-zinc-400 hover:text-orange-600 transition rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800"><SlidersHorizontal size={20} /></button>}
|
{role === 'admin' && (
|
||||||
|
<button onClick={() => setShowSettings(true)} className="p-2 text-zinc-400 hover:text-orange-600 transition rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800">
|
||||||
|
<SlidersHorizontal size={20} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex-1 overflow-hidden relative print:overflow-visible print:h-auto print:block">
|
<div className="flex-1 overflow-hidden relative print:overflow-visible print:h-auto print:block">
|
||||||
@@ -205,7 +209,7 @@ export default function Tournament() {
|
|||||||
isOpen={!!scoreMatch}
|
isOpen={!!scoreMatch}
|
||||||
onClose={() => setScoreMatch(null)}
|
onClose={() => setScoreMatch(null)}
|
||||||
match={scoreMatch}
|
match={scoreMatch}
|
||||||
isAdmin={isAdmin}
|
isAuthenticated={!!role}
|
||||||
onClear={async (mid: string | number, c: string) => {
|
onClear={async (mid: string | number, c: string) => {
|
||||||
await api.delete(`/tournaments/${id}/matches/${mid}/score?code=${encodeURIComponent(c || '')}`);
|
await api.delete(`/tournaments/${id}/matches/${mid}/score?code=${encodeURIComponent(c || '')}`);
|
||||||
setScoreMatch(null);
|
setScoreMatch(null);
|
||||||
|
|||||||
Reference in New Issue
Block a user