@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
315 lines • 8.86 kB
JavaScript
/**
* Authentication integration for mock environments
*/
import { createAuthHandlers } from '../handlers/auth';
import { addCoreHandlers } from '../core/setup';
/**
* Mock authentication manager
*/
export class MockAuthManager {
authContext;
config;
constructor(config = {}) {
this.config = config;
this.authContext = config.mockAuthContext || {
isAuthenticated: false,
user: null,
roles: [],
permissions: [],
};
}
/**
* Set authenticated user
*/
setUser(user, token) {
this.authContext = {
isAuthenticated: true,
user,
token: token || this.generateMockToken(user),
roles: user.roles || [],
permissions: user.permissions || [],
};
}
/**
* Clear authentication
*/
clearAuth() {
this.authContext = {
isAuthenticated: false,
user: null,
// token: undefined, // Optional field
roles: [],
permissions: [],
};
}
/**
* Get current auth context
*/
getAuthContext() {
return { ...this.authContext };
}
/**
* Check if user is authenticated
*/
isAuthenticated() {
return this.authContext.isAuthenticated;
}
/**
* Check if user has role
*/
hasRole(role) {
return this.authContext.roles?.includes(role) || false;
}
/**
* Check if user has permission
*/
hasPermission(permission) {
return this.authContext.permissions?.includes(permission) || false;
}
/**
* Get current user
*/
getCurrentUser() {
return this.authContext.user;
}
/**
* Get current token
*/
getCurrentToken() {
return this.authContext.token || null;
}
/**
* Validate token
*/
async validateToken(token) {
if (this.config.tokenValidator) {
return this.config.tokenValidator(token);
}
// Simple mock validation
return token === this.authContext.token;
}
/**
* Get user from token
*/
async getUserFromToken(token) {
if (this.config.userProvider) {
return this.config.userProvider(token);
}
// Simple mock implementation
if (token === this.authContext.token) {
return this.authContext.user;
}
return null;
}
/**
* Generate mock JWT token
*/
generateMockToken(user) {
const header = { alg: 'HS256', typ: 'JWT' };
const payload = {
sub: user.id,
email: user.email,
roles: user.roles || [],
permissions: user.permissions || [],
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour
};
// Simple base64 encoding (not secure, for mocking only)
const encodedHeader = btoa(JSON.stringify(header));
const encodedPayload = btoa(JSON.stringify(payload));
const signature = btoa(`mock-signature-${user.id}`);
return `${encodedHeader}.${encodedPayload}.${signature}`;
}
}
/**
* Create mock authentication manager
*/
export function createMockAuthManager(config = {}) {
return new MockAuthManager(config);
}
/**
* Setup authentication mocking with handlers
*/
export async function setupAuthMocking(users = [], config = {}) {
const authManager = createMockAuthManager(config);
// Create auth handlers
const authHandlers = createAuthHandlers(config.endpoints?.login || '/api/auth', {
users,
enableRegistration: true,
enablePasswordReset: true,
});
// Add handlers to MSW
addCoreHandlers(...authHandlers);
return authManager;
}
/**
* Mock user factory for authentication
*/
export function mockAuthUser(overrides = {}) {
return {
id: `user_${Date.now()}`,
email: 'user@example.com',
password: 'password',
firstName: 'Mock',
lastName: 'User',
roles: ['user'],
permissions: ['read'],
isActive: true,
...overrides,
};
}
/**
* Create admin user for testing
*/
export function createMockAdminUser(overrides = {}) {
return mockAuthUser({
email: 'admin@example.com',
firstName: 'Admin',
lastName: 'User',
roles: ['admin'],
permissions: [
'users:read',
'users:write',
'users:delete',
'roles:read',
'roles:write',
'settings:read',
'settings:write',
],
...overrides,
});
}
/**
* Create manager user for testing
*/
export function createMockManagerUser(overrides = {}) {
return mockAuthUser({
email: 'manager@example.com',
firstName: 'Manager',
lastName: 'User',
roles: ['manager'],
permissions: [
'users:read',
'users:write',
'roles:read',
],
...overrides,
});
}
/**
* Integration with @dbs-portal/core-auth
*/
export function integrateWithCoreAuth(authManager, coreAuthStore) {
if (!coreAuthStore) {
console.warn('Core auth store not provided for integration');
return;
}
// Sync mock auth state with core auth store
const authContext = authManager.getAuthContext();
if (authContext.isAuthenticated && authContext.user) {
// Set user in core auth store
if (typeof coreAuthStore.setUser === 'function') {
coreAuthStore.setUser(authContext.user);
}
// Set authentication state
if (typeof coreAuthStore.setAuthenticated === 'function') {
coreAuthStore.setAuthenticated(true);
}
// Set token
if (typeof coreAuthStore.setToken === 'function') {
coreAuthStore.setToken(authContext.token);
}
}
else {
// Clear auth state
if (typeof coreAuthStore.clearAuth === 'function') {
coreAuthStore.clearAuth();
}
}
}
/**
* Create protected route wrapper for testing
*/
export function withMockAuth(handlers, _authRequirements = {}) {
// This would wrap handlers with authentication checks
// Implementation depends on the specific handler structure
return handlers.map(handler => {
// Add authentication middleware to each handler
return handler; // Simplified for now
});
}
/**
* Mock authentication hooks for React components
*/
export function createMockAuthHooks(authManager) {
return {
useAuth: () => ({
isAuthenticated: authManager.isAuthenticated(),
user: authManager.getCurrentUser(),
token: authManager.getCurrentToken(),
login: async (credentials) => {
// Mock login implementation
const mockUser = mockAuthUser({
email: credentials.email,
});
authManager.setUser(mockUser);
return mockUser;
},
logout: () => {
authManager.clearAuth();
},
}),
usePermissions: () => ({
hasPermission: (permission) => authManager.hasPermission(permission),
hasRole: (role) => authManager.hasRole(role),
permissions: authManager.getAuthContext().permissions || [],
roles: authManager.getAuthContext().roles || [],
}),
useCurrentUser: () => authManager.getCurrentUser(),
};
}
/**
* Setup authentication for Storybook
*/
export function setupStorybookAuth(defaultUser) {
const authManager = createMockAuthManager();
// Set default authenticated user for Storybook
if (defaultUser !== undefined) {
const user = mockAuthUser(defaultUser);
authManager.setUser(user);
}
return authManager;
}
/**
* Authentication state persistence for development
*/
export class MockAuthPersistence {
storageKey = 'mock-auth-state';
save(authContext) {
try {
localStorage.setItem(this.storageKey, JSON.stringify(authContext));
}
catch (error) {
console.warn('Failed to save mock auth state:', error);
}
}
load() {
try {
const stored = localStorage.getItem(this.storageKey);
return stored ? JSON.parse(stored) : null;
}
catch (error) {
console.warn('Failed to load mock auth state:', error);
return null;
}
}
clear() {
try {
localStorage.removeItem(this.storageKey);
}
catch (error) {
console.warn('Failed to clear mock auth state:', error);
}
}
}
//# sourceMappingURL=auth.js.map