Skip to content

Commit 9502344

Browse files
authored
Merge pull request #10 from Flashl3opard/feat/keycloak-auth
PHEE-381: implement in-app Keycloak auth using ROPC flow
2 parents 9d6460d + e220f73 commit 9502344

16 files changed

Lines changed: 1001 additions & 34 deletions

‎package-lock.json‎

Lines changed: 256 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
"axios": "^1.18.0",
1717
"class-variance-authority": "^0.7.1",
1818
"clsx": "^2.1.1",
19+
"jspdf": "^4.2.1",
20+
"jspdf-autotable": "^5.0.8",
21+
"keycloak-js": "^26.2.4",
1922
"lucide-react": "^1.18.0",
2023
"radix-ui": "^1.5.0",
2124
"react": "^19.2.6",

‎src/components/shared/AppLayout.tsx‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
2-
import { useState } from 'react'
2+
import { useState, useRef, useEffect } from 'react'
33
import type { LucideIcon } from 'lucide-react'
44
import {
55
ArrowLeftRight,
@@ -9,6 +9,7 @@ import {
99
HelpCircle,
1010
LayoutDashboard,
1111
Landmark,
12+
LogOut,
1213
Search,
1314
Settings,
1415
Shield,
@@ -18,6 +19,7 @@ import {
1819
Users,
1920
} from 'lucide-react'
2021
import { APP_NAME, DEFAULT_TENANT, TENANTS } from '@/config/constants'
22+
import { useAuth } from '@/lib/keycloak/useAuth'
2123

2224
interface NavItem {
2325
label: string
@@ -42,15 +44,29 @@ const navItems: NavItem[] = [
4244
export default function AppLayout() {
4345
const location = useLocation()
4446
const navigate = useNavigate()
47+
const { user, logout } = useAuth()
4548
const [tenant, setTenant] = useState(
4649
localStorage.getItem('tenant') ?? DEFAULT_TENANT
4750
)
51+
const [avatarOpen, setAvatarOpen] = useState(false)
52+
const avatarRef = useRef<HTMLDivElement>(null)
4853

4954
function handleTenantChange(value: string) {
5055
setTenant(value)
5156
localStorage.setItem('tenant', value)
5257
}
5358

59+
// Close dropdown on outside click
60+
useEffect(() => {
61+
function handleClick(e: MouseEvent) {
62+
if (avatarRef.current && !avatarRef.current.contains(e.target as Node)) {
63+
setAvatarOpen(false)
64+
}
65+
}
66+
document.addEventListener('mousedown', handleClick)
67+
return () => document.removeEventListener('mousedown', handleClick)
68+
}, [])
69+
5470
function isActive(item: NavItem) {
5571
return item.exact
5672
? location.pathname === item.path
@@ -138,8 +154,42 @@ export default function AppLayout() {
138154
<HelpCircle size={18} />
139155
</button>
140156

141-
<div className="w-8 h-8 rounded-full bg-[#1565C0] flex items-center justify-center">
142-
<User size={15} className="text-white" />
157+
{/* Avatar dropdown */}
158+
<div className="relative" ref={avatarRef}>
159+
<button
160+
type="button"
161+
aria-label="User menu"
162+
onClick={() => setAvatarOpen((v) => !v)}
163+
className="flex items-center gap-2 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1565C0]"
164+
>
165+
<div className="w-8 h-8 rounded-full bg-[#1565C0] flex items-center justify-center">
166+
<User size={15} className="text-white" />
167+
</div>
168+
{user?.name && (
169+
<span className="text-sm text-gray-700 font-medium max-w-28 truncate hidden lg:block">
170+
{user.name}
171+
</span>
172+
)}
173+
</button>
174+
175+
{avatarOpen && (
176+
<div className="absolute right-0 mt-2 w-56 bg-white rounded-lg shadow-lg border border-gray-100 py-1 z-50">
177+
{user && (
178+
<div className="px-4 py-3 border-b border-gray-100">
179+
<p className="text-sm font-medium text-gray-800 truncate">{user.name}</p>
180+
<p className="text-xs text-gray-500 truncate">{user.email}</p>
181+
</div>
182+
)}
183+
<button
184+
type="button"
185+
onClick={() => { setAvatarOpen(false); logout() }}
186+
className="flex items-center gap-2 w-full px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 transition-colors"
187+
>
188+
<LogOut size={14} />
189+
Sign Out
190+
</button>
191+
</div>
192+
)}
143193
</div>
144194
</header>
145195

‎src/lib/api/client.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ const apiClient = axios.create({
66

77
apiClient.interceptors.request.use((config) => {
88
const tenant = localStorage.getItem('tenant') || 'greenbank'
9-
config.headers.set('X-TenantId', tenant)
9+
config.headers.set('Platform-TenantId', tenant)
10+
11+
const token = localStorage.getItem('kc_token')
12+
if (token) {
13+
config.headers.set('Authorization', `Bearer ${token}`)
14+
}
15+
1016
return config
1117
})
1218

‎src/lib/exportCsv.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export function exportCsv(rows: Record<string, unknown>[], filename: string) {
2+
if (rows.length === 0) return
3+
const headers = Object.keys(rows[0])
4+
const escape = (v: unknown) => {
5+
const s = v == null ? '' : String(v)
6+
return s.includes(',') || s.includes('"') || s.includes('\n')
7+
? `"${s.replace(/"/g, '""')}"`
8+
: s
9+
}
10+
const csv = [
11+
headers.join(','),
12+
...rows.map((r) => headers.map((h) => escape(r[h])).join(',')),
13+
].join('\n')
14+
15+
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
16+
const url = URL.createObjectURL(blob)
17+
const a = document.createElement('a')
18+
a.href = url
19+
a.download = filename
20+
a.click()
21+
URL.revokeObjectURL(url)
22+
}
23+
24+
export function csvDate() {
25+
return new Date().toISOString().slice(0, 10)
26+
}

‎src/lib/exportPdf.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { jsPDF } from 'jspdf'
2+
import autoTable from 'jspdf-autotable'
3+
import { csvDate } from './exportCsv'
4+
5+
export function exportPdf(
6+
title: string,
7+
headers: string[],
8+
rows: (string | number)[][],
9+
filename: string,
10+
) {
11+
const doc = new jsPDF({ orientation: 'landscape', unit: 'pt', format: 'a4' })
12+
doc.setFontSize(13)
13+
doc.text(title, 40, 36)
14+
doc.setFontSize(9)
15+
doc.setTextColor(120)
16+
doc.text(`Generated ${csvDate()}`, 40, 52)
17+
18+
autoTable(doc, {
19+
head: [headers],
20+
body: rows as string[][],
21+
startY: 64,
22+
styles: { fontSize: 8, cellPadding: 4 },
23+
headStyles: { fillColor: [21, 101, 192], textColor: 255, fontStyle: 'bold' },
24+
alternateRowStyles: { fillColor: [245, 247, 250] },
25+
})
26+
27+
doc.save(filename)
28+
}
29+
30+
export { csvDate }
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
2+
import { useNavigate } from 'react-router-dom'
3+
import keycloak from './keycloak'
4+
5+
interface KeycloakContextValue {
6+
keycloak: typeof keycloak
7+
authenticated: boolean
8+
token: string | undefined
9+
logout: () => void
10+
}
11+
12+
const KeycloakContext = createContext<KeycloakContextValue | null>(null)
13+
14+
export function useKeycloak() {
15+
const ctx = useContext(KeycloakContext)
16+
if (!ctx) throw new Error('useKeycloak must be used inside KeycloakProvider')
17+
return ctx
18+
}
19+
20+
export default function KeycloakProvider({ children }: { children: ReactNode }) {
21+
const navigate = useNavigate()
22+
const [initialized, setInitialized] = useState(false)
23+
const [authenticated, setAuthenticated] = useState(false)
24+
25+
useEffect(() => {
26+
if (keycloak.didInitialize) {
27+
setAuthenticated(keycloak.authenticated ?? false)
28+
if (keycloak.token) localStorage.setItem('kc_token', keycloak.token)
29+
setInitialized(true)
30+
return
31+
}
32+
33+
keycloak
34+
.init({
35+
onLoad: 'check-sso',
36+
checkLoginIframe: false,
37+
pkceMethod: 'S256',
38+
})
39+
.then((auth) => {
40+
console.log('Auth status:', auth)
41+
setAuthenticated(auth)
42+
if (auth && keycloak.token) {
43+
localStorage.setItem('kc_token', keycloak.token)
44+
} else {
45+
localStorage.removeItem('kc_token')
46+
navigate('/login', { replace: true })
47+
}
48+
setInitialized(true)
49+
})
50+
.catch((err) => {
51+
console.error('Keycloak init error:', err)
52+
setInitialized(true)
53+
navigate('/login', { replace: true })
54+
})
55+
56+
keycloak.onTokenExpired = () => {
57+
keycloak.updateToken(60).then((refreshed) => {
58+
if (refreshed && keycloak.token) {
59+
localStorage.setItem('kc_token', keycloak.token)
60+
}
61+
}).catch(() => {
62+
localStorage.removeItem('kc_token')
63+
keycloak.logout()
64+
})
65+
}
66+
// eslint-disable-next-line react-hooks/exhaustive-deps
67+
}, [])
68+
69+
function logout() {
70+
localStorage.removeItem('kc_token')
71+
keycloak.logout({ redirectUri: `${window.location.origin}/login` })
72+
}
73+
74+
if (!initialized) {
75+
return (
76+
<div className="min-h-screen flex items-center justify-center bg-[#F5F7FA]">
77+
<div className="flex flex-col items-center gap-4">
78+
<div className="w-8 h-8 rounded-full border-2 border-[#1565C0] border-t-transparent animate-spin" />
79+
<p className="text-sm text-gray-500">Initializing session…</p>
80+
</div>
81+
</div>
82+
)
83+
}
84+
85+
return (
86+
<KeycloakContext.Provider value={{ keycloak, authenticated, token: keycloak.token, logout }}>
87+
{children}
88+
</KeycloakContext.Provider>
89+
)
90+
}

‎src/lib/keycloak/keycloak.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import Keycloak from 'keycloak-js'
2+
3+
const keycloak = new Keycloak({
4+
url: import.meta.env.VITE_KEYCLOAK_URL,
5+
realm: import.meta.env.VITE_KEYCLOAK_REALM,
6+
clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID,
7+
})
8+
9+
export default keycloak

‎src/lib/keycloak/useAuth.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { useKeycloak } from './KeycloakProvider'
2+
3+
interface AuthUser {
4+
name: string
5+
email: string
6+
username: string
7+
}
8+
9+
interface UseAuthReturn {
10+
authenticated: boolean
11+
token: string | undefined
12+
user: AuthUser | null
13+
logout: () => void
14+
hasRole: (role: string) => boolean
15+
}
16+
17+
export function useAuth(): UseAuthReturn {
18+
const { keycloak, authenticated, token, logout } = useKeycloak()
19+
20+
const tokenParsed = keycloak.tokenParsed as Record<string, unknown> | undefined
21+
22+
const user: AuthUser | null = tokenParsed
23+
? {
24+
name: (tokenParsed['name'] as string) ?? (tokenParsed['preferred_username'] as string) ?? '',
25+
email: (tokenParsed['email'] as string) ?? '',
26+
username: (tokenParsed['preferred_username'] as string) ?? '',
27+
}
28+
: null
29+
30+
function hasRole(role: string): boolean {
31+
return keycloak.hasRealmRole(role) || keycloak.hasResourceRole(role)
32+
}
33+
34+
return { authenticated, token, user, logout, hasRole }
35+
}

‎src/main.tsx‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { StrictMode } from 'react'
22
import { createRoot } from 'react-dom/client'
3-
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
3+
import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom'
44
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
55
import './index.css'
6+
import KeycloakProvider from '@/lib/keycloak/KeycloakProvider'
67
import AppLayout from '@/components/shared/AppLayout'
78
import SplashScreen from '@/pages/SplashScreen'
89
import LoginPage from '@/pages/LoginPage'
@@ -16,28 +17,48 @@ import RBACConfig from '@/pages/RBACConfig'
1617
import Reporting from '@/pages/Reporting'
1718
import Visualizations from '@/pages/Visualizations'
1819
import NotFound from '@/pages/NotFound'
20+
import AccountMapperSelfService from '@/pages/AccountMapperSelfService'
21+
22+
// Thin root wrapper: supplies KeycloakProvider inside the router tree
23+
// so useNavigate is available to the provider.
24+
function AuthRoot() {
25+
return (
26+
<KeycloakProvider>
27+
<Outlet />
28+
</KeycloakProvider>
29+
)
30+
}
1931

2032
const queryClient = new QueryClient()
2133

2234
const router = createBrowserRouter([
35+
// Public routes — no Keycloak wrapper (Keycloak handles its own redirect)
2336
{ path: '/splash', element: <SplashScreen /> },
2437
{ path: '/login', element: <LoginPage /> },
38+
{ path: '/account-mapper/self-service', element: <AccountMapperSelfService /> },
39+
40+
// Protected routes — wrapped by KeycloakProvider
2541
{
26-
path: '/',
27-
element: <AppLayout />,
42+
element: <AuthRoot />,
2843
children: [
29-
{ index: true, element: <Dashboard /> },
30-
{ path: 'payment-hub', element: <PaymentHub /> },
31-
{ path: 'vouchers', element: <Vouchers /> },
32-
{ path: 'account-mapper', element: <AccountMapper /> },
33-
{ path: 'g2p-config', element: <G2PConfig /> },
34-
{ path: 'settings', element: <Settings /> },
35-
{ path: 'rbac', element: <RBACConfig /> },
36-
{ path: 'reporting', element: <Reporting /> },
37-
{ path: 'visualizations', element: <Visualizations /> },
44+
{
45+
path: '/',
46+
element: <AppLayout />,
47+
children: [
48+
{ index: true, element: <Dashboard /> },
49+
{ path: 'payment-hub', element: <PaymentHub /> },
50+
{ path: 'vouchers', element: <Vouchers /> },
51+
{ path: 'account-mapper', element: <AccountMapper /> },
52+
{ path: 'g2p-config', element: <G2PConfig /> },
53+
{ path: 'settings', element: <Settings /> },
54+
{ path: 'rbac', element: <RBACConfig /> },
55+
{ path: 'reporting', element: <Reporting /> },
56+
{ path: 'visualizations', element: <Visualizations /> },
57+
],
58+
},
59+
{ path: '*', element: <NotFound /> },
3860
],
3961
},
40-
{ path: '*', element: <NotFound /> },
4162
])
4263

4364
createRoot(document.getElementById('root')!).render(

0 commit comments

Comments
 (0)