feat: wire real auth — login returns user profile with role from platform, remove mock users and role selector tabs

This commit is contained in:
2026-03-18 10:42:54 +05:30
parent 832fa31597
commit 66ad398b81
4 changed files with 82 additions and 72 deletions

View File

@@ -14,6 +14,7 @@ import {
import { Button } from '@/components/base/buttons/button'; import { Button } from '@/components/base/buttons/button';
import { TextArea } from '@/components/base/textarea/textarea'; import { TextArea } from '@/components/base/textarea/textarea';
import { useSip } from '@/providers/sip-provider'; import { useSip } from '@/providers/sip-provider';
import { useAuth } from '@/providers/auth-provider';
import { cx } from '@/utils/cx'; import { cx } from '@/utils/cx';
import type { CallDisposition } from '@/types/entities'; import type { CallDisposition } from '@/types/entities';
@@ -97,6 +98,7 @@ export const CallWidget = () => {
toggleMute, toggleMute,
toggleHold, toggleHold,
} = useSip(); } = useSip();
const { user } = useAuth();
const [disposition, setDisposition] = useState<CallDisposition | null>(null); const [disposition, setDisposition] = useState<CallDisposition | null>(null);
const [notes, setNotes] = useState(''); const [notes, setNotes] = useState('');
@@ -180,7 +182,7 @@ export const CallWidget = () => {
data: { data: {
callDirection: 'INBOUND', callDirection: 'INBOUND',
callStatus: 'COMPLETED', callStatus: 'COMPLETED',
agentName: 'Rekha S.', agentName: user.name,
startedAt: callStartTimeRef.current, startedAt: callStartTimeRef.current,
endedAt: new Date().toISOString(), endedAt: new Date().toISOString(),
durationSeconds: callDuration, durationSeconds: callDuration,
@@ -228,7 +230,7 @@ export const CallWidget = () => {
activityType: 'CALL_RECEIVED', activityType: 'CALL_RECEIVED',
summary: `Inbound call — ${disposition.replace(/_/g, ' ')}`, summary: `Inbound call — ${disposition.replace(/_/g, ' ')}`,
occurredAt: new Date().toISOString(), occurredAt: new Date().toISOString(),
performedBy: 'Rekha S.', performedBy: user.name,
channel: 'PHONE', channel: 'PHONE',
durationSeconds: callDuration, durationSeconds: callDuration,
leadId: matchedLead.id, leadId: matchedLead.id,

View File

@@ -21,7 +21,19 @@ const clearTokens = () => {
}; };
export const apiClient = { export const apiClient = {
async login(email: string, password: string): Promise<{ accessToken: string; refreshToken: string }> { async login(email: string, password: string): Promise<{
accessToken: string;
refreshToken: string;
user?: {
id?: string;
email?: string;
firstName?: string;
lastName?: string;
avatarUrl?: string;
role?: string;
platformRoles?: string[];
};
}> {
const response = await fetch(`${API_URL}/auth/login`, { const response = await fetch(`${API_URL}/auth/login`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -33,9 +45,9 @@ export const apiClient = {
throw new Error(data.message ?? 'Login failed'); throw new Error(data.message ?? 'Login failed');
} }
const tokens = await response.json(); const data = await response.json();
storeTokens(tokens.accessToken, tokens.refreshToken); storeTokens(data.accessToken, data.refreshToken);
return tokens; return data;
}, },
async graphql<T>(query: string, variables?: Record<string, unknown>): Promise<T> { async graphql<T>(query: string, variables?: Record<string, unknown>): Promise<T> {

View File

@@ -20,24 +20,16 @@ const features = [
}, },
]; ];
type RoleTab = 'executive' | 'cc-agent' | 'admin';
export const LoginPage = () => { export const LoginPage = () => {
const { login, setRole } = useAuth(); const { loginWithUser } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const [activeTab, setActiveTab] = useState<RoleTab>('executive');
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const handleTabChange = (tab: RoleTab) => {
setActiveTab(tab);
setRole(tab);
setError(null);
};
const handleSubmit = async (event: React.FormEvent) => { const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault(); event.preventDefault();
setError(null); setError(null);
@@ -50,8 +42,25 @@ export const LoginPage = () => {
setIsLoading(true); setIsLoading(true);
try { try {
const { apiClient } = await import('@/lib/api-client'); const { apiClient } = await import('@/lib/api-client');
await apiClient.login(email, password); const response = await apiClient.login(email, password);
login();
// Build user from sidecar response
const u = response.user;
const firstName = u?.firstName ?? '';
const lastName = u?.lastName ?? '';
const name = `${firstName} ${lastName}`.trim() || email;
const initials = `${firstName[0] ?? ''}${lastName[0] ?? ''}`.toUpperCase() || email[0].toUpperCase();
loginWithUser({
id: u?.id,
name,
initials,
role: (u?.role ?? 'executive') as 'executive' | 'admin' | 'cc-agent',
email: u?.email ?? email,
avatarUrl: u?.avatarUrl,
platformRoles: u?.platformRoles,
});
navigate('/'); navigate('/');
} catch (err: any) { } catch (err: any) {
setError(err.message); setError(err.message);
@@ -60,7 +69,6 @@ export const LoginPage = () => {
}; };
const handleGoogleSignIn = () => { const handleGoogleSignIn = () => {
// TODO: implement Google OAuth via sidecar
setError('Google sign-in not yet configured'); setError('Google sign-in not yet configured');
}; };
@@ -138,30 +146,7 @@ export const LoginPage = () => {
<h2 className="text-display-xs font-bold text-primary font-display">Sign in to Helix Engage</h2> <h2 className="text-display-xs font-bold text-primary font-display">Sign in to Helix Engage</h2>
<p className="mt-1 text-sm text-tertiary">Global Hospital</p> <p className="mt-1 text-sm text-tertiary">Global Hospital</p>
{/* Role selector tabs */} {/* Role is determined by platform — no selector needed */}
<div
className="mt-8 flex items-center gap-1 rounded-xl p-1 bg-secondary"
>
{([
{ key: 'executive' as const, label: 'Marketing Executive' },
{ key: 'cc-agent' as const, label: 'Call Center' },
{ key: 'admin' as const, label: 'Admin' },
]).map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => handleTabChange(tab.key)}
className={[
'flex-1 rounded-lg px-3 py-2 text-sm font-semibold transition duration-300 ease-[cubic-bezier(0.4,0,0.2,1)]',
activeTab === tab.key
? 'bg-primary text-brand-secondary shadow-sm'
: 'text-tertiary hover:text-secondary',
].join(' ')}
>
{tab.label}
</button>
))}
</div>
{/* Google sign-in */} {/* Google sign-in */}
<div className="mt-6"> <div className="mt-6">

View File

@@ -1,55 +1,46 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { createContext, useContext, useState } from 'react'; import { createContext, useCallback, useContext, useState } from 'react';
export type Role = 'executive' | 'admin' | 'cc-agent'; export type Role = 'executive' | 'admin' | 'cc-agent';
type User = { type User = {
id?: string;
name: string; name: string;
initials: string; initials: string;
role: Role; role: Role;
email: string; email: string;
avatarUrl?: string;
platformRoles?: string[];
}; };
type AuthContextType = { type AuthContextType = {
user: User; user: User;
setRole: (role: Role) => void;
isAdmin: boolean; isAdmin: boolean;
isCCAgent: boolean; isCCAgent: boolean;
isAuthenticated: boolean; isAuthenticated: boolean;
loginWithUser: (userData: User) => void;
login: () => void; login: () => void;
logout: () => void; logout: () => void;
setRole: (role: Role) => void;
}; };
const USERS: Record<Role, User> = { const DEFAULT_USER: User = {
admin: { name: '',
name: 'Admin User', initials: '',
initials: 'AU', role: 'executive',
role: 'admin', email: '',
email: 'admin@globalhospital.com',
},
executive: {
name: 'Sanjay M.',
initials: 'SM',
role: 'executive',
email: 'sanjay@globalhospital.com',
},
'cc-agent': {
name: 'Rekha S.',
initials: 'RS',
role: 'cc-agent' as const,
email: 'rekha@globalhospital.com',
},
}; };
const getInitials = (firstName: string, lastName: string): string =>
`${firstName[0] ?? ''}${lastName[0] ?? ''}`.toUpperCase();
const AuthContext = createContext<AuthContextType | undefined>(undefined); const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = (): AuthContextType => { export const useAuth = (): AuthContextType => {
const context = useContext(AuthContext); const context = useContext(AuthContext);
if (context === undefined) { if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider'); throw new Error('useAuth must be used within an AuthProvider');
} }
return context; return context;
}; };
@@ -58,19 +49,39 @@ interface AuthProviderProps {
} }
export const AuthProvider = ({ children }: AuthProviderProps) => { export const AuthProvider = ({ children }: AuthProviderProps) => {
const [role, setRole] = useState<Role>('executive'); const [user, setUser] = useState<User>(DEFAULT_USER);
const [isAuthenticated, setIsAuthenticated] = useState(false); const [isAuthenticated, setIsAuthenticated] = useState(false);
const user = USERS[role]; const isAdmin = user.role === 'admin';
const isAdmin = role === 'admin'; const isCCAgent = user.role === 'cc-agent';
const isCCAgent = role === 'cc-agent';
const login = () => setIsAuthenticated(true); // Real login — receives user profile from sidecar auth response
const logout = () => setIsAuthenticated(false); const loginWithUser = useCallback((userData: User) => {
setUser(userData);
setIsAuthenticated(true);
}, []);
// Simple login (for backward compat)
const login = useCallback(() => {
setIsAuthenticated(true);
}, []);
const logout = useCallback(() => {
setUser(DEFAULT_USER);
setIsAuthenticated(false);
localStorage.removeItem('helix_access_token');
localStorage.removeItem('helix_refresh_token');
}, []);
const setRole = useCallback((role: Role) => {
setUser(prev => ({ ...prev, role }));
}, []);
return ( return (
<AuthContext.Provider value={{ user, setRole, isAdmin, isCCAgent, isAuthenticated, login, logout }}> <AuthContext.Provider value={{ user, isAdmin, isCCAgent, isAuthenticated, loginWithUser, login, logout, setRole }}>
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>
); );
}; };
export { getInitials };