Fixed for mock login
This commit is contained in:
parent
39165008c5
commit
05ea1decb9
|
|
@ -4,6 +4,7 @@ Fulfills FR-AUTH-001 (OIDC Authentication) & LLD-001.
|
|||
Validates incoming JWT bearer tokens, enforces token signatures and claims,
|
||||
and synchronizes with SessionManager for revocation checking.
|
||||
"""
|
||||
import time
|
||||
from typing import Any, Dict, Optional
|
||||
try:
|
||||
import jwt
|
||||
|
|
@ -12,7 +13,7 @@ except ImportError:
|
|||
import requests
|
||||
from backend.app.core.config import settings
|
||||
from backend.app.auth.session import session_manager
|
||||
from sandbox.identity_mock import mock_idp
|
||||
from sandbox.identity_mock import mock_idp, TEST_PERSONAS
|
||||
|
||||
|
||||
class OIDCAuthService:
|
||||
|
|
@ -51,6 +52,44 @@ class OIDCAuthService:
|
|||
|
||||
# In offline or mock mode, verify with deterministic identity mock
|
||||
if self.settings.USE_IDENTITY_MOCK:
|
||||
if token.startswith("mock_token_"):
|
||||
email = token[len("mock_token_"):]
|
||||
persona = TEST_PERSONAS.get(email)
|
||||
if not persona:
|
||||
is_demo = email.endswith("@malwa-agri.demo")
|
||||
tenant_id = "demo-malwa-agri" if is_demo else "tenant-alpha"
|
||||
role = (
|
||||
"Mandi Buyer" if "buyer" in email else
|
||||
"Purchase Manager" if "pmgr" in email else
|
||||
"Quality Officer" if "qc" in email else
|
||||
"Yard Supervisor" if ("yard" in email or "whmgr" in email) else
|
||||
"Sales Manager" if "smgr" in email else
|
||||
"Sales Executive" if "sales" in email else
|
||||
"Logistics Coordinator" if "logistics" in email else
|
||||
"Accounts Executive" if "finance" in email else
|
||||
"Partner / MD" if "director" in email else "Tenant Administrator"
|
||||
)
|
||||
persona = {
|
||||
"sub": f"usr_{email}",
|
||||
"email": email,
|
||||
"name": email.split("@")[0].replace(".", " ").title(),
|
||||
"roles": [role],
|
||||
"tenant_id": tenant_id
|
||||
}
|
||||
payload = {
|
||||
"sub": persona.get("sub", f"usr_{email}"),
|
||||
"email": persona.get("email", email),
|
||||
"name": persona.get("name", email.split("@")[0].title()),
|
||||
"roles": persona.get("roles", ["Mandi Buyer"]),
|
||||
"tenant_id": persona.get("tenant_id", "demo-malwa-agri"),
|
||||
"realm_access": {"roles": persona.get("roles", ["Mandi Buyer"])},
|
||||
"exp": time.time() + 86400,
|
||||
"iss": "mock-idp",
|
||||
"aud": "atb-web-portal"
|
||||
}
|
||||
session_manager.register_session(token, payload)
|
||||
return payload
|
||||
|
||||
payload = mock_idp.decode_and_verify_jwt(token)
|
||||
session_manager.register_session(token, payload)
|
||||
return payload
|
||||
|
|
|
|||
|
|
@ -42,6 +42,34 @@ class InMemoryTenantStorage:
|
|||
self._collections: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
||||
self.active_tenant_id: Optional[str] = None
|
||||
self._pool_connection_id: str = "conn_pool_01"
|
||||
self._seed_fixtures()
|
||||
|
||||
def _seed_fixtures(self) -> None:
|
||||
"""Seeds baseline fixtures so mock auth and tenants work out of the box."""
|
||||
try:
|
||||
from sandbox.identity_mock import TEST_TENANTS, TEST_MEMBERSHIPS
|
||||
for t_id, data in TEST_TENANTS.items():
|
||||
self.tenants[t_id] = Tenant(
|
||||
tenant_id=t_id,
|
||||
business_name=data["business_name"],
|
||||
legal_identifier=data.get("legal_identifier", f"GSTIN_{t_id}"),
|
||||
contact_email=data.get("contact_email", f"admin@{t_id}.com"),
|
||||
primary_mandi=data.get("primary_mandi", "APMC-PUN-01"),
|
||||
status=data.get("status", "ACTIVE"),
|
||||
created_at=data.get("created_at")
|
||||
)
|
||||
for m in TEST_MEMBERSHIPS:
|
||||
mem_id = m["membership_id"]
|
||||
self.memberships[mem_id] = TenantMembership(
|
||||
membership_id=mem_id,
|
||||
tenant_id=m["tenant_id"],
|
||||
user_id=m["user_id"],
|
||||
email=m["email"],
|
||||
role=m["role"],
|
||||
status=m.get("status", "ACTIVE")
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Could not auto-seed baseline fixtures: %s", exc)
|
||||
|
||||
def set_tenant_context(self, tenant_id: Optional[str]) -> None:
|
||||
"""Sets transaction-local tenant isolation context (SET LOCAL app.current_tenant_id)."""
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
*/
|
||||
import React, { useState } from 'react';
|
||||
import { authStore } from '../../stores/authStore';
|
||||
import { tenantStore } from '../../stores/tenantStore';
|
||||
import { Button } from '../../components/ui/Button';
|
||||
import { ShieldCheck, LogIn } from 'lucide-react';
|
||||
|
||||
|
|
@ -93,6 +94,11 @@ export const LoginView: React.FC = () => {
|
|||
roles: [role],
|
||||
tenant_id: tenantId
|
||||
});
|
||||
tenantStore.setActiveTenant(
|
||||
tenantId,
|
||||
isDemo ? 'Malwa Agri Trading Corp Pvt Ltd' : 'Alpha Agro Traders',
|
||||
[role]
|
||||
);
|
||||
window.location.href = '/';
|
||||
} catch (err: any) {
|
||||
setErrorMessage(`Mock login failed: ${err.message}`);
|
||||
|
|
|
|||
|
|
@ -110,11 +110,97 @@ TEST_PERSONAS: Dict[str, Dict[str, Any]] = {
|
|||
"name": "Arjun Sharma (Multi-Trader)",
|
||||
"roles": ["Mandi Buyer"],
|
||||
"tenant_id": "tenant-alpha"
|
||||
},
|
||||
"buyer@malwa-agri.demo": {
|
||||
"sub": "usr_demo_buyer",
|
||||
"email": "buyer@malwa-agri.demo",
|
||||
"name": "Rajesh Patidar (Buyer)",
|
||||
"roles": ["Mandi Buyer"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"pmgr@malwa-agri.demo": {
|
||||
"sub": "usr_demo_pmgr",
|
||||
"email": "pmgr@malwa-agri.demo",
|
||||
"name": "Suresh Sharma (Purchase Mgr)",
|
||||
"roles": ["Purchase Manager"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"yard@malwa-agri.demo": {
|
||||
"sub": "usr_demo_yard",
|
||||
"email": "yard@malwa-agri.demo",
|
||||
"name": "Vikram Singh (Yard Sup)",
|
||||
"roles": ["Yard Supervisor"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"qc@malwa-agri.demo": {
|
||||
"sub": "usr_demo_qc",
|
||||
"email": "qc@malwa-agri.demo",
|
||||
"name": "Dr. Ananya Joshi (Quality)",
|
||||
"roles": ["Quality Officer"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"whmgr@malwa-agri.demo": {
|
||||
"sub": "usr_demo_whmgr",
|
||||
"email": "whmgr@malwa-agri.demo",
|
||||
"name": "Gopal Verma (Godown Mgr)",
|
||||
"roles": ["Yard Supervisor"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"sales@malwa-agri.demo": {
|
||||
"sub": "usr_demo_sales",
|
||||
"email": "sales@malwa-agri.demo",
|
||||
"name": "Rohit Agrawal (Sales Exec)",
|
||||
"roles": ["Sales Executive"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"smgr@malwa-agri.demo": {
|
||||
"sub": "usr_demo_smgr",
|
||||
"email": "smgr@malwa-agri.demo",
|
||||
"name": "Meera Nair (Sales Mgr)",
|
||||
"roles": ["Sales Manager"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"logistics@malwa-agri.demo": {
|
||||
"sub": "usr_demo_logistics",
|
||||
"email": "logistics@malwa-agri.demo",
|
||||
"name": "Dinesh Rao (Logistics)",
|
||||
"roles": ["Logistics Coordinator"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"finance@malwa-agri.demo": {
|
||||
"sub": "usr_demo_finance",
|
||||
"email": "finance@malwa-agri.demo",
|
||||
"name": "Kavita Maheshwari (Accounts)",
|
||||
"roles": ["Accounts Executive"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"director@malwa-agri.demo": {
|
||||
"sub": "usr_demo_director",
|
||||
"email": "director@malwa-agri.demo",
|
||||
"name": "Harish Patel (Managing Director)",
|
||||
"roles": ["Partner / MD"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
},
|
||||
"admin@malwa-agri.demo": {
|
||||
"sub": "usr_demo_admin",
|
||||
"email": "admin@malwa-agri.demo",
|
||||
"name": "Platform Admin (Malwa)",
|
||||
"roles": ["Tenant Administrator"],
|
||||
"tenant_id": "demo-malwa-agri"
|
||||
}
|
||||
}
|
||||
|
||||
# Pre-seeded disposable tenant fixtures
|
||||
TEST_TENANTS: Dict[str, Dict[str, Any]] = {
|
||||
"demo-malwa-agri": {
|
||||
"tenant_id": "demo-malwa-agri",
|
||||
"business_name": "Malwa Agri Trading Corp Pvt Ltd",
|
||||
"legal_identifier": "23AABCM1234F1Z1",
|
||||
"contact_email": "admin@malwa-agri.demo",
|
||||
"primary_mandi": "Indore APMC Yard (MP-IND-01)",
|
||||
"status": "ACTIVE",
|
||||
"created_at": "2026-01-01T00:00:00Z"
|
||||
},
|
||||
"tenant-alpha": {
|
||||
"tenant_id": "tenant-alpha",
|
||||
"business_name": "Alpha Agro Traders",
|
||||
|
|
@ -162,6 +248,17 @@ TEST_MEMBERSHIPS: List[Dict[str, Any]] = [
|
|||
{"membership_id": "mem_005", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_006", "tenant_id": "tenant-beta", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Partner / MD", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_007", "tenant_id": "tenant-gamma", "user_id": "usr_01J8K92GAM001", "email": "user@gamma.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_001", "tenant_id": "demo-malwa-agri", "user_id": "buyer@malwa-agri.demo", "email": "buyer@malwa-agri.demo", "role": "Mandi Buyer", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_002", "tenant_id": "demo-malwa-agri", "user_id": "pmgr@malwa-agri.demo", "email": "pmgr@malwa-agri.demo", "role": "Purchase Manager", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_003", "tenant_id": "demo-malwa-agri", "user_id": "yard@malwa-agri.demo", "email": "yard@malwa-agri.demo", "role": "Yard Supervisor", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_004", "tenant_id": "demo-malwa-agri", "user_id": "qc@malwa-agri.demo", "email": "qc@malwa-agri.demo", "role": "Quality Officer", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_005", "tenant_id": "demo-malwa-agri", "user_id": "whmgr@malwa-agri.demo", "email": "whmgr@malwa-agri.demo", "role": "Yard Supervisor", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_006", "tenant_id": "demo-malwa-agri", "user_id": "sales@malwa-agri.demo", "email": "sales@malwa-agri.demo", "role": "Sales Executive", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_007", "tenant_id": "demo-malwa-agri", "user_id": "smgr@malwa-agri.demo", "email": "smgr@malwa-agri.demo", "role": "Sales Manager", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_008", "tenant_id": "demo-malwa-agri", "user_id": "logistics@malwa-agri.demo", "email": "logistics@malwa-agri.demo", "role": "Logistics Coordinator", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_009", "tenant_id": "demo-malwa-agri", "user_id": "finance@malwa-agri.demo", "email": "finance@malwa-agri.demo", "role": "Accounts Executive", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_010", "tenant_id": "demo-malwa-agri", "user_id": "director@malwa-agri.demo", "email": "director@malwa-agri.demo", "role": "Partner / MD", "status": "ACTIVE"},
|
||||
{"membership_id": "mem_demo_011", "tenant_id": "demo-malwa-agri", "user_id": "admin@malwa-agri.demo", "email": "admin@malwa-agri.demo", "role": "Tenant Administrator", "status": "ACTIVE"},
|
||||
]
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -132,3 +132,35 @@ Provided a comprehensive, structured breakdown of all front-end assets requiring
|
|||
- Clarified that Keycloak seeding is NOT required for the application to render or for running the sales demo.
|
||||
- Confirmed that "Mock Authenticate (Dev/Demo Mode)" provides immediate, self-contained multi-tenant authentication for all 10 `demo-malwa-agri` personas.
|
||||
|
||||
|
||||
## Turn 6: 2026-10-15T11:39:10Z — Mock Token Authentication & Keycloak Realm Seeding Resolution
|
||||
|
||||
### User Request
|
||||
> When we do Mock Authentication, we get logged out immediately and url in browser becomes http://localhost:3000/login?error=SESSION_EXPIRED.
|
||||
> If we try Keycloak OIDC it shows keycloak page with 'We are sorry' message. So cannot enter the system
|
||||
|
||||
### Actions & Discovery
|
||||
1. Root cause analysis for `SESSION_EXPIRED` redirect:
|
||||
- `handleDevMockLogin` created `mock_token_${selectedPersona}`.
|
||||
- On mounting, `HeaderTenantSwitcher` called `/api/v1/auth/my-tenants`.
|
||||
- The backend `OIDCAuthService.verify_token` forwarded `mock_token_...` to `mock_idp.decode_and_verify_jwt`, which rejected it with `ValueError("Malformed JWT token structure.")` because it was not a 3-part dot-separated JWT.
|
||||
- The resulting HTTP 401 triggered `apiClient`'s 401 boundary interceptor, which called `authStore.logout()` and redirected to `/login?error=SESSION_EXPIRED`.
|
||||
- In addition, the running backend container's `InMemoryTenantStorage` had not auto-seeded the `demo-malwa-agri` tenant and memberships in that container process.
|
||||
2. Root cause analysis for Keycloak 'We are sorry' message:
|
||||
- The Keycloak container was started with standard base configuration; the realm `atb-realm` and client `atb-web-portal` had not yet been provisioned in Keycloak.
|
||||
3. Implemented resolutions:
|
||||
- Updated `project_code/backend/app/auth/oidc.py`: Extended `verify_token` under `USE_IDENTITY_MOCK` to recognize and unpack `mock_token_<email>`, resolving claims, assigning RBAC roles, registering server-side session, and returning HTTP 200.
|
||||
- Updated `project_code/sandbox/identity_mock.py`: Added all 11 Malwa Agri Trading Corp personas to `TEST_PERSONAS`, added `demo-malwa-agri` to `TEST_TENANTS`, and added active memberships to `TEST_MEMBERSHIPS`.
|
||||
- Updated `project_code/backend/app/db/session.py`: Added automatic baseline fixture seeding in `InMemoryTenantStorage.__init__` so container instances boot with `demo-malwa-agri` and its active memberships.
|
||||
- Updated `project_code/frontend/src/features/auth/LoginView.tsx`: Explicitly set active tenant in `tenantStore` during mock login.
|
||||
- Seeded Keycloak container via `kcadm.sh`: Created realm `atb-realm`, created client `atb-web-portal` (with PKCE, standard flow, and redirect URIs `http://localhost:3000/*`), and seeded users `buyer@malwa-agri.demo` and `admin@malwa-agri.demo` with password `password`.
|
||||
4. Verification:
|
||||
- Verified `/api/v1/auth/session` returns HTTP 200 with subject and roles for `mock_token_buyer@malwa-agri.demo`.
|
||||
- Verified `/api/v1/auth/my-tenants` returns HTTP 200 with `demo-malwa-agri` membership.
|
||||
- Verified `/api/v1/session/active-tenant` returns HTTP 200 for tenant context switching.
|
||||
- Verified `/realms/atb-realm/protocol/openid-connect/certs` returns valid Keycloak JWKS keys.
|
||||
- Recompiled and hot-copied updated frontend bundle to `atb-local-frontend-1`.
|
||||
- Quality gates 5.1, 9.1, and 14.1 all PASSED with 0 issues.
|
||||
- Test suite passed 197/197 tests.
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue