Get user details
Header
- Composable Action:
composables/useDjustAuth/useAuthApi.ts
- API Route:
GET /api/auth/get-authenticated-user
Detailed Description
The getAuthenticatedUser
action is a core authentication function that retrieves the current authenticated user's profile data, account information, and associated accounts. It serves as the primary method for obtaining comprehensive user information after authentication has been established.
This action is essential for initializing user state, verifying authentication status, and loading user-specific data. It automatically updates the Pinia store with the retrieved information and provides a seamless way to access current user context throughout the application.
The function is commonly used during application initialization, after login completion, for session restoration, and when user data needs to be refreshed or validated.
Process Flow
sequenceDiagram participant U as User participant C as Vue Component participant UA as useDjustAuth participant S as User Store participant API as Auth API participant Auth as Auth Service U->>C: Request user data C->>UA: getAuthenticatedUser(useStore?) UA->>Auth: Check authentication Auth-->>UA: Authenticated UA->>API: GET /auth/get-authenticated-user API-->>UA: User data response UA->>S: Update store (if useStore=true) S-->>C: State updated C-->>U: User data available alt Not Authenticated Auth-->>UA: Not authenticated UA-->>C: Return null C-->>U: Redirect to login else API Error API-->>UA: Error response UA-->>C: Return null C-->>U: Show error message end
Call Parameters
Main Interface
const getAuthenticatedUser = async (useStore?: boolean) => Promise<any | null>;
Detailed Parameters
Parameter | Type | Required | Default | Example | Impact |
---|---|---|---|---|---|
useStore | boolean | ❌ | true | false | Controls automatic Pinia store updates |
Example Call
const { getAuthenticatedUser } = useDjustAuth();
try {
// Get user data and update store
const userData = await getAuthenticatedUser();
if (userData) {
console.log("User loaded:", userData.user.email);
console.log("Current account:", userData.account.name);
} else {
console.log("User not authenticated");
// Redirect to login
}
} catch (error) {
console.error("Failed to get user data:", error);
}
// Get user data without updating store
const userData = await getAuthenticatedUser(false);
Returns from Composable
Success Response Format
interface AuthenticatedUserResponse {
success: boolean;
user: CustomerUser;
account: CustomerAccountNameDto;
accounts: CustomerAccountNameDto[];
}
interface CustomerUser {
id: string;
email: string;
firstName: string;
lastName: string;
phoneNumber?: string;
preferences?: UserPreferences;
lastLoginAt?: string;
createdAt: string;
updatedAt: string;
}
interface CustomerAccountNameDto {
id: string;
name: string;
externalId: string;
}
Example Success Response
{
"success": true,
"user": {
"id": "user_123",
"email": "[email protected]",
"firstName": "John",
"lastName": "Doe",
"phoneNumber": "+1234567890",
"preferences": {
"language": "en",
"currency": "EUR",
"notifications": {
"email": true,
"push": false,
"sms": true
}
},
"lastLoginAt": "2024-01-15T10:30:00Z",
"createdAt": "2023-06-01T08:00:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
},
"account": {
"id": "account_456",
"name": "Company Ltd",
"externalId": "COMP001"
},
"accounts": [
{
"id": "account_456",
"name": "Company Ltd",
"externalId": "COMP001"
},
{
"id": "account_789",
"name": "Subsidiary Corp",
"externalId": "SUB002"
}
]
}
Null Response
// Returns null when:
// - User is not authenticated
// - Authentication tokens are invalid/expired
// - API call fails
const result = null;
Error Management
Error Types and Returns
HTTP Code | Error Type | Cause | System Action | User Message |
---|---|---|---|---|
401 | Unauthorized | Invalid or expired tokens | Return null, clear auth | "Please log in again" |
403 | Forbidden | Account access restricted | Return null | "Account access denied" |
404 | Not Found | User account not found | Return null | "User account not found" |
500 | Internal Server Error | Server or database issues | Return null, log error | "Service temporarily unavailable" |
Error Handling Code Example
const { getAuthenticatedUser } = useDjustAuth();
const { $toast } = useNuxtApp();
const router = useRouter();
try {
const userData = await getAuthenticatedUser();
if (userData) {
// Success: User data loaded
console.log("Welcome back,", userData.user.firstName);
} else {
// Authentication failed or user not found
$toast.warning("Please log in to continue");
await router.push("/auth/login");
}
} catch (error) {
console.error("Authentication check failed:", error);
// Handle specific error scenarios
if (error.statusCode === 401) {
$toast.error("Your session has expired. Please log in again.");
await router.push("/auth/login");
} else if (error.statusCode === 403) {
$toast.error("Account access is restricted.");
} else {
$toast.error("Unable to load user data. Please try again.");
}
}
Use Cases
-
Application Initialization
- Load user data on app startup
- Restore user session from stored tokens
- Initialize user-specific application state
- Set up user preferences and settings
-
Session Validation
- Verify authentication status before sensitive operations
- Refresh user data after account switching
- Validate access permissions for protected features
- Check for account status changes
-
User Profile Management
- Display current user information in profile components
- Show account selection interfaces for multi-account users
- Populate user forms with current data
- Update navigation with user-specific options
-
Data Synchronization
- Sync user data after external updates
- Refresh account information after administrative changes
- Update cached user data periodically
- Ensure consistency across application components
Important Points
Performance
The function is optimized for efficient data retrieval with minimal API calls. It includes intelligent caching through the Pinia store, optional store updates to reduce overhead, and efficient error handling to prevent blocking operations.
Security
Security is enforced through automatic authentication validation, token verification before API calls, secure handling of sensitive user data, and proper error handling that doesn't expose internal system details.
Flexibility
The system provides flexible usage patterns with optional store updates, support for multiple account scenarios, configurable error handling, and integration with various authentication flows.
Integration
Deep integration with the application ecosystem includes automatic Pinia store synchronization, seamless token management, coordination with authentication middleware, and consistent error handling with other authentication functions.
Technical Implementation
/**
* Retrieves authenticated user data including profile and account information
* @param useStore - Whether to update the Pinia store with retrieved data
* @returns Promise<AuthenticatedUserResponse | null> - User data or null if not authenticated
* @throws {Error} - Network or server errors (handled gracefully)
*/
const getAuthenticatedUser = async (useStore = true) => {
try {
// Make API call to get authenticated user data
const { data } = await useFetch("/api/auth/get-authenticated-user");
// Update store if requested and data is available
if (useStore && data) {
userStore.login({
user: data.value.user,
account: data.value.account,
accounts: data.value.accounts,
});
}
return data.value;
} catch (error) {
console.error("Failed to get authenticated user:", error);
return null;
}
};
Execution Flow
-
API Request
const { data } = await useFetch("/api/auth/get-authenticated-user");
-
Data Validation
if (data && data.value) { // Process user data }
-
Store Update (Optional)
if (useStore && data) { userStore.login({ user: data.value.user, account: data.value.account, accounts: data.value.accounts, }); }
-
Return Data
return data.value; // User data or null
-
Error Handling
catch (error) { console.error('Failed to get authenticated user:', error); return null; // Graceful failure }
Updated about 2 months ago