/** * SCREEN-AUTH-001: Trading Portal Login & OIDC Callback View. * * Fulfills FR-AUTH-001 & SCREEN-AUTH-001.md. */ import React, { useState } from 'react'; import { authStore } from '../../stores/authStore'; export const LoginView: React.FC = () => { const [selectedPersona, setSelectedPersona] = useState('buyer@alpha.com'); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(null); // PKCE Code Verifier generator const generateRandomString = (length: number): string => { const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; let result = ''; const values = new Uint8Array(length); crypto.getRandomValues(values); for (let i = 0; i < length; i++) { result += charset[values[i] % charset.length]; } return result; }; const sha256 = async (plain: string): Promise => { const encoder = new TextEncoder(); const data = encoder.encode(plain); return crypto.subtle.digest('SHA-256', data); }; const base64UrlEncode = (buffer: ArrayBuffer): string => { const bytes = new Uint8Array(buffer); let str = ''; for (let i = 0; i < bytes.byteLength; i++) { str += String.fromCharCode(bytes[i]); } return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; const handleKeycloakLogin = async () => { setIsLoading(true); setErrorMessage(null); try { const verifier = generateRandomString(64); const challengeBuffer = await sha256(verifier); const challenge = base64UrlEncode(challengeBuffer); const state = generateRandomString(32); sessionStorage.setItem('pkce_code_verifier', verifier); sessionStorage.setItem('oauth_state', state); const keycloakUrl = process.env.VITE_KEYCLOAK_URL || 'http://localhost:8080'; const realm = process.env.VITE_KEYCLOAK_REALM || 'atb-realm'; const clientId = process.env.VITE_KEYCLOAK_CLIENT_ID || 'atb-web-portal'; const redirectUri = encodeURIComponent(`${window.location.origin}/auth/callback`); const authEndpoint = `${keycloakUrl}/realms/${realm}/protocol/openid-connect/auth?` + `client_id=${clientId}&response_type=code&scope=openid%20profile%20email&` + `redirect_uri=${redirectUri}&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`; window.location.href = authEndpoint; } catch (err: any) { setErrorMessage(`Failed to initiate Keycloak login: ${err.message}`); setIsLoading(false); } }; const handleDevMockLogin = async () => { setIsLoading(true); setErrorMessage(null); try { // Direct offline deterministic mock login const res = await fetch(`http://localhost:8000/api/v1/auth/session`, { headers: { 'Authorization': `Bearer mock_jwt_for_${selectedPersona}` } }); // Set session directly in mock development mode authStore.setSession(`mock_token_${selectedPersona}`, { sub: `usr_${selectedPersona}`, email: selectedPersona, name: selectedPersona.split('@')[0], roles: selectedPersona.includes('buyer') ? ['Mandi Buyer'] : selectedPersona.includes('qc') ? ['Quality Officer'] : selectedPersona.includes('yard') ? ['Yard Supervisor'] : selectedPersona.includes('sales') ? ['Sales Executive'] : ['Tenant Administrator'], tenant_id: 'tenant-alpha' }); window.location.href = '/'; } catch (err: any) { setErrorMessage(`Mock login failed: ${err.message}`); } finally { setIsLoading(false); } }; return (
ATB

Agriculture Trading Backoffice

Sign in to your trading desk account

{errorMessage && (
{errorMessage}
)}
Offline Sandbox / Dev Mode
(C) 2026 Agriculture Trading Backoffice. Multi-Tenant Enterprise Trading.
); };