All files / frontend/src/store authStore.ts

97.75% Statements 87/89
68.42% Branches 13/19
100% Functions 6/6
97.75% Lines 87/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 1341x 1x                                           1x     1x   1x 1x 1x 1x 1x 1x 1x   1x 3x         3x   3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 1x 1x 1x   2x         2x 3x       2x     2x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 1x 1x 1x  
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
 
interface User {
    id: string;
    email: string;
    name: string;
    role: 'admin' | 'user' | 'viewer';
    avatar?: string;
}
 
interface AuthStore {
    user: User | null;
    token: string | null;
    refreshToken: string | null;
    isAuthenticated: boolean;
    login: (email: string, password: string) => Promise<void>;
    logout: () => void;
    setUser: (user: User | null) => void;
    setToken: (token: string | null) => void;
}
 
// API Gateway configuration (reads from .env)
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
 
// Keycloak OAuth2/OIDC configuration
const KEYCLOAK_CLIENT_ID = import.meta.env.VITE_KEYCLOAK_CLIENT_ID || 'heimdall-frontend';
 
export const useAuthStore = create<AuthStore>()(
    persist(
        (set) => ({
            user: null,
            token: null,
            refreshToken: null,
            isAuthenticated: false,
 
            login: async (email: string, password: string) => {
                try {
                    // Use API Gateway as proxy to Keycloak (CORS-enabled)
                    // This avoids direct CORS requests to Keycloak
                    // Endpoint: POST /api/v1/auth/login (proxies to Keycloak internally)
                    // Base URL comes from VITE_API_URL environment variable
                    const tokenUrl = `${API_URL}/api/v1/auth/login`;
 
                    const params = new URLSearchParams();
                    params.append('grant_type', 'password');
                    params.append('client_id', KEYCLOAK_CLIENT_ID);
                    params.append('username', email);
                    params.append('password', password);
 
                    const response = await fetch(tokenUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        credentials: 'omit',
                        mode: 'cors',
                        cache: 'no-cache',
                        body: params.toString(),
                    });
 
                    if (!response.ok) {
                        const errorData = await response.json().catch(() => ({}));
                        throw new Error(errorData.error_description || 'Invalid email or password');
                    }
 
                    const data = await response.json();
 
                    // Decode JWT access token to extract user information
                    // Note: This is safe for client-side as we don't verify signature here
                    // Backend services verify JWT signature using Keycloak public keys
                    const tokenParts = data.access_token.split('.');
                    if (tokenParts.length !== 3) {
                        throw new Error('Invalid JWT token format');
                    }
 
                    const payload = JSON.parse(atob(tokenParts[1]));
 
                    // Extract user information from JWT claims
                    const user: User = {
                        id: payload.sub || '1',
                        email: payload.email || email,
                        name: payload.name || payload.preferred_username || email.split('@')[0],
                        role: payload.realm_access?.roles?.includes('admin') ? 'admin' : 'user',
                        avatar: payload.picture,
                    };
 
                    set({
                        user,
                        token: data.access_token,
                        refreshToken: data.refresh_token,
                        isAuthenticated: true,
                    });
                } catch (error) {
                    console.error('Login failed:', error);
                    set({
                        user: null,
                        token: null,
                        refreshToken: null,
                        isAuthenticated: false,
                    });
                    throw error;
                }
            },
 
            logout: () => {
                set({
                    user: null,
                    token: null,
                    refreshToken: null,
                    isAuthenticated: false,
                });
            },
 
            setUser: (user) => {
                set({ user, isAuthenticated: !!user });
            },
 
            setToken: (token) => {
                set({ token });
            },
        }),
        {
            name: 'auth-store',
            partialize: (state) => ({
                user: state.user,
                token: state.token,
                refreshToken: state.refreshToken,
                isAuthenticated: state.isAuthenticated,
            }),
        }
    )
);