166 lines
6.8 KiB
TypeScript
166 lines
6.8 KiB
TypeScript
/**
|
|
* 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<string>('buyer@alpha.com');
|
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
|
const [errorMessage, setErrorMessage] = useState<string | null>(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<ArrayBuffer> => {
|
|
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 (
|
|
<div className="min-h-screen flex items-center justify-center bg-slate-900 text-slate-100 p-4">
|
|
<div className="max-w-md w-full bg-slate-800 rounded-xl shadow-2xl p-8 border border-slate-700">
|
|
<div className="text-center mb-8">
|
|
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-emerald-500/10 text-emerald-400 mb-4 font-bold text-2xl">
|
|
ATB
|
|
</div>
|
|
<h1 className="text-2xl font-bold tracking-tight text-white">Agriculture Trading Backoffice</h1>
|
|
<p className="text-sm text-slate-400 mt-2">Sign in to your trading desk account</p>
|
|
</div>
|
|
|
|
{errorMessage && (
|
|
<div className="mb-6 p-4 rounded-lg bg-rose-500/10 border border-rose-500/20 text-rose-400 text-sm">
|
|
{errorMessage}
|
|
</div>
|
|
)}
|
|
|
|
<div className="space-y-4">
|
|
<button
|
|
onClick={handleKeycloakLogin}
|
|
disabled={isLoading}
|
|
className="w-full py-3 px-4 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-medium shadow-md transition-colors flex items-center justify-center space-x-2 disabled:opacity-50"
|
|
>
|
|
<span>{isLoading ? 'Redirecting...' : 'Sign In with Keycloak SSO'}</span>
|
|
</button>
|
|
|
|
<div className="relative my-6">
|
|
<div className="absolute inset-0 flex items-center">
|
|
<div className="w-full border-t border-slate-700"></div>
|
|
</div>
|
|
<div className="relative flex justify-center text-xs uppercase">
|
|
<span className="bg-slate-800 px-2 text-slate-400">Offline Sandbox / Dev Mode</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-3">
|
|
<label className="block text-xs font-medium text-slate-400">Select Test Persona:</label>
|
|
<select
|
|
value={selectedPersona}
|
|
onChange={(e) => setSelectedPersona(e.target.value)}
|
|
className="w-full py-2.5 px-3 rounded-lg bg-slate-900 border border-slate-700 text-slate-200 text-sm focus:outline-none focus:border-emerald-500"
|
|
>
|
|
<option value="buyer@alpha.com">Ramesh Kumar — Mandi Buyer</option>
|
|
<option value="qc@alpha.com">Ananya Sharma — Quality Officer (SoD Restriced)</option>
|
|
<option value="yard@alpha.com">Vikram Singh — Yard Supervisor (SoD Restricted)</option>
|
|
<option value="sales@alpha.com">Rohit Verma — Sales Executive (SoD Restricted)</option>
|
|
<option value="finance@alpha.com">Kavita Joshi — Accounts Executive</option>
|
|
<option value="admin@alpha.com">Alpha Admin — Tenant Administrator</option>
|
|
</select>
|
|
|
|
<button
|
|
onClick={handleDevMockLogin}
|
|
disabled={isLoading}
|
|
className="w-full py-2.5 px-4 rounded-lg bg-slate-700 hover:bg-slate-600 text-slate-200 text-sm font-medium transition-colors"
|
|
>
|
|
Mock Authenticate (Offline)
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mt-8 text-center text-xs text-slate-500">
|
|
(C) 2026 Agriculture Trading Backoffice. Multi-Tenant Enterprise Trading.
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|