Merge pull request 'chore: migrate user identity from auth0_sub to UUID' (#219) from issue-206-migrate-user-identity-uuid into main
All checks were successful
Deploy to Staging / Build Images (push) Successful in 6m32s
Deploy to Staging / Deploy to Staging (push) Successful in 23s
Deploy to Staging / Verify Staging (push) Successful in 9s
Deploy to Staging / Notify Staging Ready (push) Successful in 7s
Deploy to Staging / Notify Staging Failure (push) Has been skipped
All checks were successful
Deploy to Staging / Build Images (push) Successful in 6m32s
Deploy to Staging / Deploy to Staging (push) Successful in 23s
Deploy to Staging / Verify Staging (push) Successful in 9s
Deploy to Staging / Notify Staging Ready (push) Successful in 7s
Deploy to Staging / Notify Staging Failure (push) Has been skipped
Reviewed-on: #219
This commit was merged in pull request #219.
This commit is contained in:
@@ -6,11 +6,12 @@
|
||||
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { AdminService } from '../domain/admin.service';
|
||||
import { AdminRepository } from '../data/admin.repository';
|
||||
import { UserProfileRepository } from '../../user-profile/data/user-profile.repository';
|
||||
import { pool } from '../../../core/config/database';
|
||||
import { logger } from '../../../core/logging/logger';
|
||||
import {
|
||||
CreateAdminInput,
|
||||
AdminAuth0SubInput,
|
||||
AdminIdInput,
|
||||
AuditLogsQueryInput,
|
||||
BulkCreateAdminInput,
|
||||
BulkRevokeAdminInput,
|
||||
@@ -18,7 +19,7 @@ import {
|
||||
} from './admin.validation';
|
||||
import {
|
||||
createAdminSchema,
|
||||
adminAuth0SubSchema,
|
||||
adminIdSchema,
|
||||
auditLogsQuerySchema,
|
||||
bulkCreateAdminSchema,
|
||||
bulkRevokeAdminSchema,
|
||||
@@ -33,10 +34,12 @@ import {
|
||||
|
||||
export class AdminController {
|
||||
private adminService: AdminService;
|
||||
private userProfileRepository: UserProfileRepository;
|
||||
|
||||
constructor() {
|
||||
const repository = new AdminRepository(pool);
|
||||
this.adminService = new AdminService(repository);
|
||||
this.userProfileRepository = new UserProfileRepository(pool);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,49 +50,18 @@ export class AdminController {
|
||||
const userId = request.userContext?.userId;
|
||||
const userEmail = this.resolveUserEmail(request);
|
||||
|
||||
console.log('[DEBUG] Admin verify - userId:', userId);
|
||||
console.log('[DEBUG] Admin verify - userEmail:', userEmail);
|
||||
|
||||
if (userEmail && request.userContext) {
|
||||
request.userContext.email = userEmail.toLowerCase();
|
||||
}
|
||||
|
||||
if (!userId && !userEmail) {
|
||||
console.log('[DEBUG] Admin verify - No userId or userEmail, returning 401');
|
||||
if (!userId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
let adminRecord = userId
|
||||
? await this.adminService.getAdminByAuth0Sub(userId)
|
||||
: null;
|
||||
|
||||
console.log('[DEBUG] Admin verify - adminRecord by auth0Sub:', adminRecord ? 'FOUND' : 'NOT FOUND');
|
||||
|
||||
// Fallback: attempt to resolve admin by email for legacy records
|
||||
if (!adminRecord && userEmail) {
|
||||
const emailMatch = await this.adminService.getAdminByEmail(userEmail.toLowerCase());
|
||||
|
||||
console.log('[DEBUG] Admin verify - emailMatch:', emailMatch ? 'FOUND' : 'NOT FOUND');
|
||||
if (emailMatch) {
|
||||
console.log('[DEBUG] Admin verify - emailMatch.auth0Sub:', emailMatch.auth0Sub);
|
||||
console.log('[DEBUG] Admin verify - emailMatch.revokedAt:', emailMatch.revokedAt);
|
||||
}
|
||||
|
||||
if (emailMatch && !emailMatch.revokedAt) {
|
||||
// If the stored auth0Sub differs, link it to the authenticated user
|
||||
if (userId && emailMatch.auth0Sub !== userId) {
|
||||
console.log('[DEBUG] Admin verify - Calling linkAdminAuth0Sub to update auth0Sub');
|
||||
adminRecord = await this.adminService.linkAdminAuth0Sub(userEmail, userId);
|
||||
console.log('[DEBUG] Admin verify - adminRecord after link:', adminRecord ? 'SUCCESS' : 'FAILED');
|
||||
} else {
|
||||
console.log('[DEBUG] Admin verify - Using emailMatch as adminRecord');
|
||||
adminRecord = emailMatch;
|
||||
}
|
||||
}
|
||||
}
|
||||
const adminRecord = await this.adminService.getAdminByUserProfileId(userId);
|
||||
|
||||
if (adminRecord && !adminRecord.revokedAt) {
|
||||
if (request.userContext) {
|
||||
@@ -97,12 +69,11 @@ export class AdminController {
|
||||
request.userContext.adminRecord = adminRecord;
|
||||
}
|
||||
|
||||
console.log('[DEBUG] Admin verify - Returning isAdmin: true');
|
||||
// User is an active admin
|
||||
return reply.code(200).send({
|
||||
isAdmin: true,
|
||||
adminRecord: {
|
||||
auth0Sub: adminRecord.auth0Sub,
|
||||
id: adminRecord.id,
|
||||
userProfileId: adminRecord.userProfileId,
|
||||
email: adminRecord.email,
|
||||
role: adminRecord.role
|
||||
}
|
||||
@@ -114,14 +85,11 @@ export class AdminController {
|
||||
request.userContext.adminRecord = undefined;
|
||||
}
|
||||
|
||||
console.log('[DEBUG] Admin verify - Returning isAdmin: false');
|
||||
// User is not an admin
|
||||
return reply.code(200).send({
|
||||
isAdmin: false,
|
||||
adminRecord: null
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('[DEBUG] Admin verify - Error caught:', error instanceof Error ? error.message : 'Unknown error');
|
||||
logger.error('Error verifying admin access', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
userId: request.userContext?.userId?.substring(0, 8) + '...'
|
||||
@@ -139,9 +107,9 @@ export class AdminController {
|
||||
*/
|
||||
async listAdmins(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
@@ -150,11 +118,6 @@ export class AdminController {
|
||||
|
||||
const admins = await this.adminService.getAllAdmins();
|
||||
|
||||
// Log VIEW action
|
||||
await this.adminService.getAdminByAuth0Sub(actorId);
|
||||
// Note: Not logging VIEW as it would create excessive audit entries
|
||||
// VIEW logging can be enabled if needed for compliance
|
||||
|
||||
return reply.code(200).send({
|
||||
total: admins.length,
|
||||
admins
|
||||
@@ -162,7 +125,7 @@ export class AdminController {
|
||||
} catch (error: any) {
|
||||
logger.error('Error listing admins', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId
|
||||
actorUserProfileId: request.userContext?.userId
|
||||
});
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
@@ -179,15 +142,24 @@ export class AdminController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
// Get actor's admin record to get admin ID
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorUserProfileId);
|
||||
if (!actorAdmin) {
|
||||
return reply.code(403).send({
|
||||
error: 'Forbidden',
|
||||
message: 'Actor is not an admin'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate request body
|
||||
const validation = createAdminSchema.safeParse(request.body);
|
||||
if (!validation.success) {
|
||||
@@ -200,23 +172,27 @@ export class AdminController {
|
||||
|
||||
const { email, role } = validation.data;
|
||||
|
||||
// Generate auth0Sub for the new admin
|
||||
// In production, this should be the actual Auth0 user ID
|
||||
// For now, we'll use email-based identifier
|
||||
const auth0Sub = `auth0|${email.replace('@', '_at_')}`;
|
||||
// Look up user profile by email to get UUID
|
||||
const userProfile = await this.userProfileRepository.getByEmail(email);
|
||||
if (!userProfile) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not Found',
|
||||
message: `No user profile found with email ${email}. User must sign up first.`
|
||||
});
|
||||
}
|
||||
|
||||
const admin = await this.adminService.createAdmin(
|
||||
email,
|
||||
role,
|
||||
auth0Sub,
|
||||
actorId
|
||||
userProfile.id,
|
||||
actorAdmin.id
|
||||
);
|
||||
|
||||
return reply.code(201).send(admin);
|
||||
} catch (error: any) {
|
||||
logger.error('Error creating admin', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId
|
||||
actorUserProfileId: request.userContext?.userId
|
||||
});
|
||||
|
||||
if (error.message.includes('already exists')) {
|
||||
@@ -234,36 +210,45 @@ export class AdminController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/admins/:auth0Sub/revoke - Revoke admin access
|
||||
* PATCH /api/admin/admins/:id/revoke - Revoke admin access
|
||||
*/
|
||||
async revokeAdmin(
|
||||
request: FastifyRequest<{ Params: AdminAuth0SubInput }>,
|
||||
request: FastifyRequest<{ Params: AdminIdInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
// Get actor's admin record
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorUserProfileId);
|
||||
if (!actorAdmin) {
|
||||
return reply.code(403).send({
|
||||
error: 'Forbidden',
|
||||
message: 'Actor is not an admin'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate params
|
||||
const validation = adminAuth0SubSchema.safeParse(request.params);
|
||||
const validation = adminIdSchema.safeParse(request.params);
|
||||
if (!validation.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Bad Request',
|
||||
message: 'Invalid auth0Sub parameter',
|
||||
message: 'Invalid admin ID parameter',
|
||||
details: validation.error.errors
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = validation.data;
|
||||
const { id } = validation.data;
|
||||
|
||||
// Check if admin exists
|
||||
const targetAdmin = await this.adminService.getAdminByAuth0Sub(auth0Sub);
|
||||
const targetAdmin = await this.adminService.getAdminById(id);
|
||||
if (!targetAdmin) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not Found',
|
||||
@@ -272,14 +257,14 @@ export class AdminController {
|
||||
}
|
||||
|
||||
// Revoke the admin (service handles last admin check)
|
||||
const admin = await this.adminService.revokeAdmin(auth0Sub, actorId);
|
||||
const admin = await this.adminService.revokeAdmin(id, actorAdmin.id);
|
||||
|
||||
return reply.code(200).send(admin);
|
||||
} catch (error: any) {
|
||||
logger.error('Error revoking admin', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId,
|
||||
targetAuth0Sub: request.params.auth0Sub
|
||||
actorUserProfileId: request.userContext?.userId,
|
||||
targetAdminId: (request.params as any).id
|
||||
});
|
||||
|
||||
if (error.message.includes('Cannot revoke the last active admin')) {
|
||||
@@ -304,36 +289,45 @@ export class AdminController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/admins/:auth0Sub/reinstate - Restore revoked admin
|
||||
* PATCH /api/admin/admins/:id/reinstate - Restore revoked admin
|
||||
*/
|
||||
async reinstateAdmin(
|
||||
request: FastifyRequest<{ Params: AdminAuth0SubInput }>,
|
||||
request: FastifyRequest<{ Params: AdminIdInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
// Get actor's admin record
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorUserProfileId);
|
||||
if (!actorAdmin) {
|
||||
return reply.code(403).send({
|
||||
error: 'Forbidden',
|
||||
message: 'Actor is not an admin'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate params
|
||||
const validation = adminAuth0SubSchema.safeParse(request.params);
|
||||
const validation = adminIdSchema.safeParse(request.params);
|
||||
if (!validation.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Bad Request',
|
||||
message: 'Invalid auth0Sub parameter',
|
||||
message: 'Invalid admin ID parameter',
|
||||
details: validation.error.errors
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = validation.data;
|
||||
const { id } = validation.data;
|
||||
|
||||
// Check if admin exists
|
||||
const targetAdmin = await this.adminService.getAdminByAuth0Sub(auth0Sub);
|
||||
const targetAdmin = await this.adminService.getAdminById(id);
|
||||
if (!targetAdmin) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not Found',
|
||||
@@ -342,14 +336,14 @@ export class AdminController {
|
||||
}
|
||||
|
||||
// Reinstate the admin
|
||||
const admin = await this.adminService.reinstateAdmin(auth0Sub, actorId);
|
||||
const admin = await this.adminService.reinstateAdmin(id, actorAdmin.id);
|
||||
|
||||
return reply.code(200).send(admin);
|
||||
} catch (error: any) {
|
||||
logger.error('Error reinstating admin', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId,
|
||||
targetAuth0Sub: request.params.auth0Sub
|
||||
actorUserProfileId: request.userContext?.userId,
|
||||
targetAdminId: (request.params as any).id
|
||||
});
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
@@ -418,15 +412,24 @@ export class AdminController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
// Get actor's admin record
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorUserProfileId);
|
||||
if (!actorAdmin) {
|
||||
return reply.code(403).send({
|
||||
error: 'Forbidden',
|
||||
message: 'Actor is not an admin'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate request body
|
||||
const validation = bulkCreateAdminSchema.safeParse(request.body);
|
||||
if (!validation.success) {
|
||||
@@ -447,15 +450,21 @@ export class AdminController {
|
||||
try {
|
||||
const { email, role = 'admin' } = adminInput;
|
||||
|
||||
// Generate auth0Sub for the new admin
|
||||
// In production, this should be the actual Auth0 user ID
|
||||
const auth0Sub = `auth0|${email.replace('@', '_at_')}`;
|
||||
// Look up user profile by email to get UUID
|
||||
const userProfile = await this.userProfileRepository.getByEmail(email);
|
||||
if (!userProfile) {
|
||||
failed.push({
|
||||
email,
|
||||
error: `No user profile found with email ${email}. User must sign up first.`
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const admin = await this.adminService.createAdmin(
|
||||
email,
|
||||
role,
|
||||
auth0Sub,
|
||||
actorId
|
||||
userProfile.id,
|
||||
actorAdmin.id
|
||||
);
|
||||
|
||||
created.push(admin);
|
||||
@@ -463,7 +472,7 @@ export class AdminController {
|
||||
logger.error('Error creating admin in bulk operation', {
|
||||
error: error.message,
|
||||
email: adminInput.email,
|
||||
actorId
|
||||
actorAdminId: actorAdmin.id
|
||||
});
|
||||
|
||||
failed.push({
|
||||
@@ -485,7 +494,7 @@ export class AdminController {
|
||||
} catch (error: any) {
|
||||
logger.error('Error in bulk create admins', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId
|
||||
actorUserProfileId: request.userContext?.userId
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -503,15 +512,24 @@ export class AdminController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
// Get actor's admin record
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorUserProfileId);
|
||||
if (!actorAdmin) {
|
||||
return reply.code(403).send({
|
||||
error: 'Forbidden',
|
||||
message: 'Actor is not an admin'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate request body
|
||||
const validation = bulkRevokeAdminSchema.safeParse(request.body);
|
||||
if (!validation.success) {
|
||||
@@ -522,37 +540,36 @@ export class AdminController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Subs } = validation.data;
|
||||
const { ids } = validation.data;
|
||||
|
||||
const revoked: AdminUser[] = [];
|
||||
const failed: Array<{ auth0Sub: string; error: string }> = [];
|
||||
const failed: Array<{ id: string; error: string }> = [];
|
||||
|
||||
// Process each revocation sequentially to maintain data consistency
|
||||
for (const auth0Sub of auth0Subs) {
|
||||
for (const id of ids) {
|
||||
try {
|
||||
// Check if admin exists
|
||||
const targetAdmin = await this.adminService.getAdminByAuth0Sub(auth0Sub);
|
||||
const targetAdmin = await this.adminService.getAdminById(id);
|
||||
if (!targetAdmin) {
|
||||
failed.push({
|
||||
auth0Sub,
|
||||
id,
|
||||
error: 'Admin user not found'
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Attempt to revoke the admin
|
||||
const admin = await this.adminService.revokeAdmin(auth0Sub, actorId);
|
||||
const admin = await this.adminService.revokeAdmin(id, actorAdmin.id);
|
||||
revoked.push(admin);
|
||||
} catch (error: any) {
|
||||
logger.error('Error revoking admin in bulk operation', {
|
||||
error: error.message,
|
||||
auth0Sub,
|
||||
actorId
|
||||
adminId: id,
|
||||
actorAdminId: actorAdmin.id
|
||||
});
|
||||
|
||||
// Special handling for "last admin" constraint
|
||||
failed.push({
|
||||
auth0Sub,
|
||||
id,
|
||||
error: error.message || 'Failed to revoke admin'
|
||||
});
|
||||
}
|
||||
@@ -570,7 +587,7 @@ export class AdminController {
|
||||
} catch (error: any) {
|
||||
logger.error('Error in bulk revoke admins', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId
|
||||
actorUserProfileId: request.userContext?.userId
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -588,15 +605,24 @@ export class AdminController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const actorId = request.userContext?.userId;
|
||||
const actorUserProfileId = request.userContext?.userId;
|
||||
|
||||
if (!actorId) {
|
||||
if (!actorUserProfileId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing'
|
||||
});
|
||||
}
|
||||
|
||||
// Get actor's admin record
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorUserProfileId);
|
||||
if (!actorAdmin) {
|
||||
return reply.code(403).send({
|
||||
error: 'Forbidden',
|
||||
message: 'Actor is not an admin'
|
||||
});
|
||||
}
|
||||
|
||||
// Validate request body
|
||||
const validation = bulkReinstateAdminSchema.safeParse(request.body);
|
||||
if (!validation.success) {
|
||||
@@ -607,36 +633,36 @@ export class AdminController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Subs } = validation.data;
|
||||
const { ids } = validation.data;
|
||||
|
||||
const reinstated: AdminUser[] = [];
|
||||
const failed: Array<{ auth0Sub: string; error: string }> = [];
|
||||
const failed: Array<{ id: string; error: string }> = [];
|
||||
|
||||
// Process each reinstatement sequentially to maintain data consistency
|
||||
for (const auth0Sub of auth0Subs) {
|
||||
for (const id of ids) {
|
||||
try {
|
||||
// Check if admin exists
|
||||
const targetAdmin = await this.adminService.getAdminByAuth0Sub(auth0Sub);
|
||||
const targetAdmin = await this.adminService.getAdminById(id);
|
||||
if (!targetAdmin) {
|
||||
failed.push({
|
||||
auth0Sub,
|
||||
id,
|
||||
error: 'Admin user not found'
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Attempt to reinstate the admin
|
||||
const admin = await this.adminService.reinstateAdmin(auth0Sub, actorId);
|
||||
const admin = await this.adminService.reinstateAdmin(id, actorAdmin.id);
|
||||
reinstated.push(admin);
|
||||
} catch (error: any) {
|
||||
logger.error('Error reinstating admin in bulk operation', {
|
||||
error: error.message,
|
||||
auth0Sub,
|
||||
actorId
|
||||
adminId: id,
|
||||
actorAdminId: actorAdmin.id
|
||||
});
|
||||
|
||||
failed.push({
|
||||
auth0Sub,
|
||||
id,
|
||||
error: error.message || 'Failed to reinstate admin'
|
||||
});
|
||||
}
|
||||
@@ -654,7 +680,7 @@ export class AdminController {
|
||||
} catch (error: any) {
|
||||
logger.error('Error in bulk reinstate admins', {
|
||||
error: error.message,
|
||||
actorId: request.userContext?.userId
|
||||
actorUserProfileId: request.userContext?.userId
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -665,9 +691,6 @@ export class AdminController {
|
||||
}
|
||||
|
||||
private resolveUserEmail(request: FastifyRequest): string | undefined {
|
||||
console.log('[DEBUG] resolveUserEmail - request.userContext:', JSON.stringify(request.userContext, null, 2));
|
||||
console.log('[DEBUG] resolveUserEmail - request.user:', JSON.stringify((request as any).user, null, 2));
|
||||
|
||||
const candidates: Array<string | undefined> = [
|
||||
request.userContext?.email,
|
||||
(request as any).user?.email,
|
||||
@@ -676,15 +699,11 @@ export class AdminController {
|
||||
(request as any).user?.preferred_username,
|
||||
];
|
||||
|
||||
console.log('[DEBUG] resolveUserEmail - candidates:', candidates);
|
||||
|
||||
for (const value of candidates) {
|
||||
if (typeof value === 'string' && value.includes('@')) {
|
||||
console.log('[DEBUG] resolveUserEmail - found email:', value);
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
console.log('[DEBUG] resolveUserEmail - no email found');
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { AdminController } from './admin.controller';
|
||||
import { UsersController } from './users.controller';
|
||||
import {
|
||||
CreateAdminInput,
|
||||
AdminAuth0SubInput,
|
||||
AdminIdInput,
|
||||
BulkCreateAdminInput,
|
||||
BulkRevokeAdminInput,
|
||||
BulkReinstateAdminInput,
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from './admin.validation';
|
||||
import {
|
||||
ListUsersQueryInput,
|
||||
UserAuth0SubInput,
|
||||
UserIdInput,
|
||||
UpdateTierInput,
|
||||
DeactivateUserInput,
|
||||
UpdateProfileInput,
|
||||
@@ -65,14 +65,14 @@ export const adminRoutes: FastifyPluginAsync = async (fastify) => {
|
||||
handler: adminController.createAdmin.bind(adminController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/admins/:auth0Sub/revoke - Revoke admin access
|
||||
fastify.patch<{ Params: AdminAuth0SubInput }>('/admin/admins/:auth0Sub/revoke', {
|
||||
// PATCH /api/admin/admins/:id/revoke - Revoke admin access
|
||||
fastify.patch<{ Params: AdminIdInput }>('/admin/admins/:id/revoke', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: adminController.revokeAdmin.bind(adminController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/admins/:auth0Sub/reinstate - Restore revoked admin
|
||||
fastify.patch<{ Params: AdminAuth0SubInput }>('/admin/admins/:auth0Sub/reinstate', {
|
||||
// PATCH /api/admin/admins/:id/reinstate - Restore revoked admin
|
||||
fastify.patch<{ Params: AdminIdInput }>('/admin/admins/:id/reinstate', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: adminController.reinstateAdmin.bind(adminController)
|
||||
});
|
||||
@@ -117,50 +117,50 @@ export const adminRoutes: FastifyPluginAsync = async (fastify) => {
|
||||
handler: usersController.listUsers.bind(usersController)
|
||||
});
|
||||
|
||||
// GET /api/admin/users/:auth0Sub - Get single user details
|
||||
fastify.get<{ Params: UserAuth0SubInput }>('/admin/users/:auth0Sub', {
|
||||
// GET /api/admin/users/:userId - Get single user details
|
||||
fastify.get<{ Params: UserIdInput }>('/admin/users/:userId', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.getUser.bind(usersController)
|
||||
});
|
||||
|
||||
// GET /api/admin/users/:auth0Sub/vehicles - Get user's vehicles (admin view)
|
||||
fastify.get<{ Params: UserAuth0SubInput }>('/admin/users/:auth0Sub/vehicles', {
|
||||
// GET /api/admin/users/:userId/vehicles - Get user's vehicles (admin view)
|
||||
fastify.get<{ Params: UserIdInput }>('/admin/users/:userId/vehicles', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.getUserVehicles.bind(usersController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/users/:auth0Sub/tier - Update subscription tier
|
||||
fastify.patch<{ Params: UserAuth0SubInput; Body: UpdateTierInput }>('/admin/users/:auth0Sub/tier', {
|
||||
// PATCH /api/admin/users/:userId/tier - Update subscription tier
|
||||
fastify.patch<{ Params: UserIdInput; Body: UpdateTierInput }>('/admin/users/:userId/tier', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.updateTier.bind(usersController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/users/:auth0Sub/deactivate - Soft delete user
|
||||
fastify.patch<{ Params: UserAuth0SubInput; Body: DeactivateUserInput }>('/admin/users/:auth0Sub/deactivate', {
|
||||
// PATCH /api/admin/users/:userId/deactivate - Soft delete user
|
||||
fastify.patch<{ Params: UserIdInput; Body: DeactivateUserInput }>('/admin/users/:userId/deactivate', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.deactivateUser.bind(usersController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/users/:auth0Sub/reactivate - Restore deactivated user
|
||||
fastify.patch<{ Params: UserAuth0SubInput }>('/admin/users/:auth0Sub/reactivate', {
|
||||
// PATCH /api/admin/users/:userId/reactivate - Restore deactivated user
|
||||
fastify.patch<{ Params: UserIdInput }>('/admin/users/:userId/reactivate', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.reactivateUser.bind(usersController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/users/:auth0Sub/profile - Update user email/displayName
|
||||
fastify.patch<{ Params: UserAuth0SubInput; Body: UpdateProfileInput }>('/admin/users/:auth0Sub/profile', {
|
||||
// PATCH /api/admin/users/:userId/profile - Update user email/displayName
|
||||
fastify.patch<{ Params: UserIdInput; Body: UpdateProfileInput }>('/admin/users/:userId/profile', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.updateProfile.bind(usersController)
|
||||
});
|
||||
|
||||
// PATCH /api/admin/users/:auth0Sub/promote - Promote user to admin
|
||||
fastify.patch<{ Params: UserAuth0SubInput; Body: PromoteToAdminInput }>('/admin/users/:auth0Sub/promote', {
|
||||
// PATCH /api/admin/users/:userId/promote - Promote user to admin
|
||||
fastify.patch<{ Params: UserIdInput; Body: PromoteToAdminInput }>('/admin/users/:userId/promote', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.promoteToAdmin.bind(usersController)
|
||||
});
|
||||
|
||||
// DELETE /api/admin/users/:auth0Sub - Hard delete user (permanent)
|
||||
fastify.delete<{ Params: UserAuth0SubInput }>('/admin/users/:auth0Sub', {
|
||||
// DELETE /api/admin/users/:userId - Hard delete user (permanent)
|
||||
fastify.delete<{ Params: UserIdInput }>('/admin/users/:userId', {
|
||||
preHandler: [fastify.requireAdmin],
|
||||
handler: usersController.hardDeleteUser.bind(usersController)
|
||||
});
|
||||
|
||||
@@ -10,8 +10,8 @@ export const createAdminSchema = z.object({
|
||||
role: z.enum(['admin', 'super_admin']).default('admin'),
|
||||
});
|
||||
|
||||
export const adminAuth0SubSchema = z.object({
|
||||
auth0Sub: z.string().min(1, 'auth0Sub is required'),
|
||||
export const adminIdSchema = z.object({
|
||||
id: z.string().uuid('Invalid admin ID format'),
|
||||
});
|
||||
|
||||
export const auditLogsQuerySchema = z.object({
|
||||
@@ -29,14 +29,14 @@ export const bulkCreateAdminSchema = z.object({
|
||||
});
|
||||
|
||||
export const bulkRevokeAdminSchema = z.object({
|
||||
auth0Subs: z.array(z.string().min(1, 'auth0Sub cannot be empty'))
|
||||
.min(1, 'At least one auth0Sub must be provided')
|
||||
ids: z.array(z.string().uuid('Invalid admin ID format'))
|
||||
.min(1, 'At least one admin ID must be provided')
|
||||
.max(100, 'Maximum 100 admins per batch'),
|
||||
});
|
||||
|
||||
export const bulkReinstateAdminSchema = z.object({
|
||||
auth0Subs: z.array(z.string().min(1, 'auth0Sub cannot be empty'))
|
||||
.min(1, 'At least one auth0Sub must be provided')
|
||||
ids: z.array(z.string().uuid('Invalid admin ID format'))
|
||||
.min(1, 'At least one admin ID must be provided')
|
||||
.max(100, 'Maximum 100 admins per batch'),
|
||||
});
|
||||
|
||||
@@ -49,7 +49,7 @@ export const bulkDeleteCatalogSchema = z.object({
|
||||
});
|
||||
|
||||
export type CreateAdminInput = z.infer<typeof createAdminSchema>;
|
||||
export type AdminAuth0SubInput = z.infer<typeof adminAuth0SubSchema>;
|
||||
export type AdminIdInput = z.infer<typeof adminIdSchema>;
|
||||
export type AuditLogsQueryInput = z.infer<typeof auditLogsQuerySchema>;
|
||||
export type BulkCreateAdminInput = z.infer<typeof bulkCreateAdminSchema>;
|
||||
export type BulkRevokeAdminInput = z.infer<typeof bulkRevokeAdminSchema>;
|
||||
|
||||
@@ -14,13 +14,13 @@ import { pool } from '../../../core/config/database';
|
||||
import { logger } from '../../../core/logging/logger';
|
||||
import {
|
||||
listUsersQuerySchema,
|
||||
userAuth0SubSchema,
|
||||
userIdSchema,
|
||||
updateTierSchema,
|
||||
deactivateUserSchema,
|
||||
updateProfileSchema,
|
||||
promoteToAdminSchema,
|
||||
ListUsersQueryInput,
|
||||
UserAuth0SubInput,
|
||||
UserIdInput,
|
||||
UpdateTierInput,
|
||||
DeactivateUserInput,
|
||||
UpdateProfileInput,
|
||||
@@ -95,10 +95,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/admin/users/:auth0Sub/vehicles - Get user's vehicles (admin view)
|
||||
* GET /api/admin/users/:userId/vehicles - Get user's vehicles (admin view)
|
||||
*/
|
||||
async getUserVehicles(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -119,7 +119,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const parseResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const parseResult = userIdSchema.safeParse(request.params);
|
||||
if (!parseResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -127,14 +127,14 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = parseResult.data;
|
||||
const vehicles = await this.userProfileRepository.getUserVehiclesForAdmin(auth0Sub);
|
||||
const { userId } = parseResult.data;
|
||||
const vehicles = await this.userProfileRepository.getUserVehiclesForAdmin(userId);
|
||||
|
||||
return reply.code(200).send({ vehicles });
|
||||
} catch (error) {
|
||||
logger.error('Error getting user vehicles', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -186,10 +186,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/admin/users/:auth0Sub - Get single user details
|
||||
* GET /api/admin/users/:userId - Get single user details
|
||||
*/
|
||||
async getUser(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -202,7 +202,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const parseResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const parseResult = userIdSchema.safeParse(request.params);
|
||||
if (!parseResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -210,8 +210,8 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = parseResult.data;
|
||||
const user = await this.userProfileService.getUserDetails(auth0Sub);
|
||||
const { userId } = parseResult.data;
|
||||
const user = await this.userProfileService.getUserDetails(userId);
|
||||
|
||||
if (!user) {
|
||||
return reply.code(404).send({
|
||||
@@ -224,7 +224,7 @@ export class UsersController {
|
||||
} catch (error) {
|
||||
logger.error('Error getting user details', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -235,12 +235,12 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/users/:auth0Sub/tier - Update subscription tier
|
||||
* PATCH /api/admin/users/:userId/tier - Update subscription tier
|
||||
* Uses subscriptionsService.adminOverrideTier() to sync both subscriptions.tier
|
||||
* and user_profiles.subscription_tier atomically
|
||||
*/
|
||||
async updateTier(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput; Body: UpdateTierInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput; Body: UpdateTierInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -253,7 +253,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const paramsResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const paramsResult = userIdSchema.safeParse(request.params);
|
||||
if (!paramsResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -270,11 +270,11 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = paramsResult.data;
|
||||
const { userId } = paramsResult.data;
|
||||
const { subscriptionTier } = bodyResult.data;
|
||||
|
||||
// Verify user exists before attempting tier change
|
||||
const currentUser = await this.userProfileService.getUserDetails(auth0Sub);
|
||||
const currentUser = await this.userProfileService.getUserDetails(userId);
|
||||
if (!currentUser) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not found',
|
||||
@@ -285,34 +285,34 @@ export class UsersController {
|
||||
const previousTier = currentUser.subscriptionTier;
|
||||
|
||||
// Use subscriptionsService to update both tables atomically
|
||||
await this.subscriptionsService.adminOverrideTier(auth0Sub, subscriptionTier);
|
||||
await this.subscriptionsService.adminOverrideTier(userId, subscriptionTier);
|
||||
|
||||
// Log audit action
|
||||
await this.adminRepository.logAuditAction(
|
||||
actorId,
|
||||
'UPDATE_TIER',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
currentUser.id,
|
||||
{ previousTier, newTier: subscriptionTier }
|
||||
);
|
||||
|
||||
logger.info('User subscription tier updated via admin', {
|
||||
auth0Sub,
|
||||
userId,
|
||||
previousTier,
|
||||
newTier: subscriptionTier,
|
||||
actorAuth0Sub: actorId,
|
||||
actorId,
|
||||
});
|
||||
|
||||
// Return updated user profile
|
||||
const updatedUser = await this.userProfileService.getUserDetails(auth0Sub);
|
||||
const updatedUser = await this.userProfileService.getUserDetails(userId);
|
||||
return reply.code(200).send(updatedUser);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
|
||||
logger.error('Error updating user tier', {
|
||||
error: errorMessage,
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User not found') {
|
||||
@@ -330,10 +330,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/users/:auth0Sub/deactivate - Soft delete user
|
||||
* PATCH /api/admin/users/:userId/deactivate - Soft delete user
|
||||
*/
|
||||
async deactivateUser(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput; Body: DeactivateUserInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput; Body: DeactivateUserInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -346,7 +346,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const paramsResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const paramsResult = userIdSchema.safeParse(request.params);
|
||||
if (!paramsResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -363,11 +363,11 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = paramsResult.data;
|
||||
const { userId } = paramsResult.data;
|
||||
const { reason } = bodyResult.data;
|
||||
|
||||
const deactivatedUser = await this.userProfileService.deactivateUser(
|
||||
auth0Sub,
|
||||
userId,
|
||||
actorId,
|
||||
reason
|
||||
);
|
||||
@@ -378,7 +378,7 @@ export class UsersController {
|
||||
|
||||
logger.error('Error deactivating user', {
|
||||
error: errorMessage,
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User not found') {
|
||||
@@ -410,10 +410,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/users/:auth0Sub/reactivate - Restore deactivated user
|
||||
* PATCH /api/admin/users/:userId/reactivate - Restore deactivated user
|
||||
*/
|
||||
async reactivateUser(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -426,7 +426,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const paramsResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const paramsResult = userIdSchema.safeParse(request.params);
|
||||
if (!paramsResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -434,10 +434,10 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = paramsResult.data;
|
||||
const { userId } = paramsResult.data;
|
||||
|
||||
const reactivatedUser = await this.userProfileService.reactivateUser(
|
||||
auth0Sub,
|
||||
userId,
|
||||
actorId
|
||||
);
|
||||
|
||||
@@ -447,7 +447,7 @@ export class UsersController {
|
||||
|
||||
logger.error('Error reactivating user', {
|
||||
error: errorMessage,
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User not found') {
|
||||
@@ -472,10 +472,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/users/:auth0Sub/profile - Update user email/displayName
|
||||
* PATCH /api/admin/users/:userId/profile - Update user email/displayName
|
||||
*/
|
||||
async updateProfile(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput; Body: UpdateProfileInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput; Body: UpdateProfileInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -488,7 +488,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const paramsResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const paramsResult = userIdSchema.safeParse(request.params);
|
||||
if (!paramsResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -505,11 +505,11 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = paramsResult.data;
|
||||
const { userId } = paramsResult.data;
|
||||
const updates = bodyResult.data;
|
||||
|
||||
const updatedUser = await this.userProfileService.adminUpdateProfile(
|
||||
auth0Sub,
|
||||
userId,
|
||||
updates,
|
||||
actorId
|
||||
);
|
||||
@@ -520,7 +520,7 @@ export class UsersController {
|
||||
|
||||
logger.error('Error updating user profile', {
|
||||
error: errorMessage,
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User not found') {
|
||||
@@ -538,10 +538,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/users/:auth0Sub/promote - Promote user to admin
|
||||
* PATCH /api/admin/users/:userId/promote - Promote user to admin
|
||||
*/
|
||||
async promoteToAdmin(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput; Body: PromoteToAdminInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput; Body: PromoteToAdminInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -554,7 +554,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const paramsResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const paramsResult = userIdSchema.safeParse(request.params);
|
||||
if (!paramsResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -571,11 +571,11 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = paramsResult.data;
|
||||
const { userId } = paramsResult.data;
|
||||
const { role } = bodyResult.data;
|
||||
|
||||
// Get the user profile first to verify they exist and get their email
|
||||
const user = await this.userProfileService.getUserDetails(auth0Sub);
|
||||
// Get the user profile to verify they exist and get their email
|
||||
const user = await this.userProfileService.getUserDetails(userId);
|
||||
if (!user) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not found',
|
||||
@@ -591,12 +591,15 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
// Create the admin record using the user's real auth0Sub
|
||||
// Get actor's admin record for audit trail
|
||||
const actorAdmin = await this.adminService.getAdminByUserProfileId(actorId);
|
||||
|
||||
// Create the admin record using the user's UUID
|
||||
const adminUser = await this.adminService.createAdmin(
|
||||
user.email,
|
||||
role,
|
||||
auth0Sub, // Use the real auth0Sub from the user profile
|
||||
actorId
|
||||
userId,
|
||||
actorAdmin?.id || actorId
|
||||
);
|
||||
|
||||
return reply.code(201).send(adminUser);
|
||||
@@ -605,7 +608,7 @@ export class UsersController {
|
||||
|
||||
logger.error('Error promoting user to admin', {
|
||||
error: errorMessage,
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage.includes('already exists')) {
|
||||
@@ -623,10 +626,10 @@ export class UsersController {
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/admin/users/:auth0Sub - Hard delete user (permanent)
|
||||
* DELETE /api/admin/users/:userId - Hard delete user (permanent)
|
||||
*/
|
||||
async hardDeleteUser(
|
||||
request: FastifyRequest<{ Params: UserAuth0SubInput }>,
|
||||
request: FastifyRequest<{ Params: UserIdInput }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
@@ -639,7 +642,7 @@ export class UsersController {
|
||||
}
|
||||
|
||||
// Validate path param
|
||||
const paramsResult = userAuth0SubSchema.safeParse(request.params);
|
||||
const paramsResult = userIdSchema.safeParse(request.params);
|
||||
if (!paramsResult.success) {
|
||||
return reply.code(400).send({
|
||||
error: 'Validation error',
|
||||
@@ -647,14 +650,14 @@ export class UsersController {
|
||||
});
|
||||
}
|
||||
|
||||
const { auth0Sub } = paramsResult.data;
|
||||
const { userId } = paramsResult.data;
|
||||
|
||||
// Optional reason from query params
|
||||
const reason = (request.query as any)?.reason;
|
||||
|
||||
// Hard delete user
|
||||
await this.userProfileService.adminHardDeleteUser(
|
||||
auth0Sub,
|
||||
userId,
|
||||
actorId,
|
||||
reason
|
||||
);
|
||||
@@ -667,7 +670,7 @@ export class UsersController {
|
||||
|
||||
logger.error('Error hard deleting user', {
|
||||
error: errorMessage,
|
||||
auth0Sub: request.params?.auth0Sub,
|
||||
userId: (request.params as any)?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'Cannot delete your own account') {
|
||||
|
||||
@@ -19,9 +19,9 @@ export const listUsersQuerySchema = z.object({
|
||||
sortOrder: z.enum(['asc', 'desc']).default('desc'),
|
||||
});
|
||||
|
||||
// Path param for user auth0Sub
|
||||
export const userAuth0SubSchema = z.object({
|
||||
auth0Sub: z.string().min(1, 'auth0Sub is required'),
|
||||
// Path param for user UUID
|
||||
export const userIdSchema = z.object({
|
||||
userId: z.string().uuid('Invalid user ID format'),
|
||||
});
|
||||
|
||||
// Body for updating subscription tier
|
||||
@@ -50,7 +50,7 @@ export const promoteToAdminSchema = z.object({
|
||||
|
||||
// Type exports
|
||||
export type ListUsersQueryInput = z.infer<typeof listUsersQuerySchema>;
|
||||
export type UserAuth0SubInput = z.infer<typeof userAuth0SubSchema>;
|
||||
export type UserIdInput = z.infer<typeof userIdSchema>;
|
||||
export type UpdateTierInput = z.infer<typeof updateTierSchema>;
|
||||
export type DeactivateUserInput = z.infer<typeof deactivateUserSchema>;
|
||||
export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
|
||||
|
||||
@@ -10,29 +10,49 @@ import { logger } from '../../../core/logging/logger';
|
||||
export class AdminRepository {
|
||||
constructor(private pool: Pool) {}
|
||||
|
||||
async getAdminByAuth0Sub(auth0Sub: string): Promise<AdminUser | null> {
|
||||
async getAdminById(id: string): Promise<AdminUser | null> {
|
||||
const query = `
|
||||
SELECT auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
SELECT id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
FROM admin_users
|
||||
WHERE auth0_sub = $1
|
||||
WHERE id = $1
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [id]);
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.mapRowToAdminUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching admin by auth0_sub', { error, auth0Sub });
|
||||
logger.error('Error fetching admin by id', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminByUserProfileId(userProfileId: string): Promise<AdminUser | null> {
|
||||
const query = `
|
||||
SELECT id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
FROM admin_users
|
||||
WHERE user_profile_id = $1
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [userProfileId]);
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.mapRowToAdminUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching admin by user_profile_id', { error, userProfileId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminByEmail(email: string): Promise<AdminUser | null> {
|
||||
const query = `
|
||||
SELECT auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
SELECT id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
FROM admin_users
|
||||
WHERE LOWER(email) = LOWER($1)
|
||||
LIMIT 1
|
||||
@@ -52,7 +72,7 @@ export class AdminRepository {
|
||||
|
||||
async getAllAdmins(): Promise<AdminUser[]> {
|
||||
const query = `
|
||||
SELECT auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
SELECT id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
FROM admin_users
|
||||
ORDER BY created_at DESC
|
||||
`;
|
||||
@@ -68,7 +88,7 @@ export class AdminRepository {
|
||||
|
||||
async getActiveAdmins(): Promise<AdminUser[]> {
|
||||
const query = `
|
||||
SELECT auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
SELECT id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
FROM admin_users
|
||||
WHERE revoked_at IS NULL
|
||||
ORDER BY created_at DESC
|
||||
@@ -83,61 +103,61 @@ export class AdminRepository {
|
||||
}
|
||||
}
|
||||
|
||||
async createAdmin(auth0Sub: string, email: string, role: string, createdBy: string): Promise<AdminUser> {
|
||||
async createAdmin(userProfileId: string, email: string, role: string, createdBy: string): Promise<AdminUser> {
|
||||
const query = `
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by)
|
||||
INSERT INTO admin_users (user_profile_id, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
RETURNING id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub, email, role, createdBy]);
|
||||
const result = await this.pool.query(query, [userProfileId, email, role, createdBy]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('Failed to create admin user');
|
||||
}
|
||||
return this.mapRowToAdminUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error creating admin', { error, auth0Sub, email });
|
||||
logger.error('Error creating admin', { error, userProfileId, email });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async revokeAdmin(auth0Sub: string): Promise<AdminUser> {
|
||||
async revokeAdmin(id: string): Promise<AdminUser> {
|
||||
const query = `
|
||||
UPDATE admin_users
|
||||
SET revoked_at = CURRENT_TIMESTAMP
|
||||
WHERE auth0_sub = $1
|
||||
RETURNING auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
WHERE id = $1
|
||||
RETURNING id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [id]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('Admin user not found');
|
||||
}
|
||||
return this.mapRowToAdminUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error revoking admin', { error, auth0Sub });
|
||||
logger.error('Error revoking admin', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async reinstateAdmin(auth0Sub: string): Promise<AdminUser> {
|
||||
async reinstateAdmin(id: string): Promise<AdminUser> {
|
||||
const query = `
|
||||
UPDATE admin_users
|
||||
SET revoked_at = NULL
|
||||
WHERE auth0_sub = $1
|
||||
RETURNING auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
WHERE id = $1
|
||||
RETURNING id, user_profile_id, email, role, created_at, created_by, revoked_at, updated_at
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [id]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('Admin user not found');
|
||||
}
|
||||
return this.mapRowToAdminUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error reinstating admin', { error, auth0Sub });
|
||||
logger.error('Error reinstating admin', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -202,30 +222,11 @@ export class AdminRepository {
|
||||
}
|
||||
}
|
||||
|
||||
async updateAuth0SubByEmail(email: string, auth0Sub: string): Promise<AdminUser> {
|
||||
const query = `
|
||||
UPDATE admin_users
|
||||
SET auth0_sub = $1,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE LOWER(email) = LOWER($2)
|
||||
RETURNING auth0_sub, email, role, created_at, created_by, revoked_at, updated_at
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub, email]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error(`Admin user with email ${email} not found`);
|
||||
}
|
||||
return this.mapRowToAdminUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error updating admin auth0_sub by email', { error, email, auth0Sub });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private mapRowToAdminUser(row: any): AdminUser {
|
||||
return {
|
||||
auth0Sub: row.auth0_sub,
|
||||
id: row.id,
|
||||
userProfileId: row.user_profile_id,
|
||||
email: row.email,
|
||||
role: row.role,
|
||||
createdAt: new Date(row.created_at),
|
||||
|
||||
@@ -11,11 +11,20 @@ import { auditLogService } from '../../audit-log';
|
||||
export class AdminService {
|
||||
constructor(private repository: AdminRepository) {}
|
||||
|
||||
async getAdminByAuth0Sub(auth0Sub: string): Promise<AdminUser | null> {
|
||||
async getAdminById(id: string): Promise<AdminUser | null> {
|
||||
try {
|
||||
return await this.repository.getAdminByAuth0Sub(auth0Sub);
|
||||
return await this.repository.getAdminById(id);
|
||||
} catch (error) {
|
||||
logger.error('Error getting admin by auth0_sub', { error });
|
||||
logger.error('Error getting admin by id', { error });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminByUserProfileId(userProfileId: string): Promise<AdminUser | null> {
|
||||
try {
|
||||
return await this.repository.getAdminByUserProfileId(userProfileId);
|
||||
} catch (error) {
|
||||
logger.error('Error getting admin by user_profile_id', { error });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -47,7 +56,7 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
async createAdmin(email: string, role: string, auth0Sub: string, createdBy: string): Promise<AdminUser> {
|
||||
async createAdmin(email: string, role: string, userProfileId: string, createdByAdminId: string): Promise<AdminUser> {
|
||||
try {
|
||||
// Check if admin already exists
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
@@ -57,10 +66,10 @@ export class AdminService {
|
||||
}
|
||||
|
||||
// Create new admin
|
||||
const admin = await this.repository.createAdmin(auth0Sub, normalizedEmail, role, createdBy);
|
||||
const admin = await this.repository.createAdmin(userProfileId, normalizedEmail, role, createdByAdminId);
|
||||
|
||||
// Log audit action (legacy)
|
||||
await this.repository.logAuditAction(createdBy, 'CREATE', admin.auth0Sub, 'admin_user', admin.email, {
|
||||
await this.repository.logAuditAction(createdByAdminId, 'CREATE', admin.id, 'admin_user', admin.email, {
|
||||
email,
|
||||
role
|
||||
});
|
||||
@@ -68,10 +77,10 @@ export class AdminService {
|
||||
// Log to unified audit log
|
||||
await auditLogService.info(
|
||||
'admin',
|
||||
createdBy,
|
||||
userProfileId,
|
||||
`Admin user created: ${admin.email}`,
|
||||
'admin_user',
|
||||
admin.auth0Sub,
|
||||
admin.id,
|
||||
{ email: admin.email, role }
|
||||
).catch(err => logger.error('Failed to log admin create audit event', { error: err }));
|
||||
|
||||
@@ -83,7 +92,7 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
async revokeAdmin(auth0Sub: string, revokedBy: string): Promise<AdminUser> {
|
||||
async revokeAdmin(id: string, revokedByAdminId: string): Promise<AdminUser> {
|
||||
try {
|
||||
// Check that at least one active admin will remain
|
||||
const activeAdmins = await this.repository.getActiveAdmins();
|
||||
@@ -92,51 +101,51 @@ export class AdminService {
|
||||
}
|
||||
|
||||
// Revoke the admin
|
||||
const admin = await this.repository.revokeAdmin(auth0Sub);
|
||||
const admin = await this.repository.revokeAdmin(id);
|
||||
|
||||
// Log audit action (legacy)
|
||||
await this.repository.logAuditAction(revokedBy, 'REVOKE', auth0Sub, 'admin_user', admin.email);
|
||||
await this.repository.logAuditAction(revokedByAdminId, 'REVOKE', id, 'admin_user', admin.email);
|
||||
|
||||
// Log to unified audit log
|
||||
await auditLogService.info(
|
||||
'admin',
|
||||
revokedBy,
|
||||
admin.userProfileId,
|
||||
`Admin user revoked: ${admin.email}`,
|
||||
'admin_user',
|
||||
auth0Sub,
|
||||
id,
|
||||
{ email: admin.email }
|
||||
).catch(err => logger.error('Failed to log admin revoke audit event', { error: err }));
|
||||
|
||||
logger.info('Admin user revoked', { auth0Sub, email: admin.email });
|
||||
logger.info('Admin user revoked', { id, email: admin.email });
|
||||
return admin;
|
||||
} catch (error) {
|
||||
logger.error('Error revoking admin', { error, auth0Sub });
|
||||
logger.error('Error revoking admin', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async reinstateAdmin(auth0Sub: string, reinstatedBy: string): Promise<AdminUser> {
|
||||
async reinstateAdmin(id: string, reinstatedByAdminId: string): Promise<AdminUser> {
|
||||
try {
|
||||
// Reinstate the admin
|
||||
const admin = await this.repository.reinstateAdmin(auth0Sub);
|
||||
const admin = await this.repository.reinstateAdmin(id);
|
||||
|
||||
// Log audit action (legacy)
|
||||
await this.repository.logAuditAction(reinstatedBy, 'REINSTATE', auth0Sub, 'admin_user', admin.email);
|
||||
await this.repository.logAuditAction(reinstatedByAdminId, 'REINSTATE', id, 'admin_user', admin.email);
|
||||
|
||||
// Log to unified audit log
|
||||
await auditLogService.info(
|
||||
'admin',
|
||||
reinstatedBy,
|
||||
admin.userProfileId,
|
||||
`Admin user reinstated: ${admin.email}`,
|
||||
'admin_user',
|
||||
auth0Sub,
|
||||
id,
|
||||
{ email: admin.email }
|
||||
).catch(err => logger.error('Failed to log admin reinstate audit event', { error: err }));
|
||||
|
||||
logger.info('Admin user reinstated', { auth0Sub, email: admin.email });
|
||||
logger.info('Admin user reinstated', { id, email: admin.email });
|
||||
return admin;
|
||||
} catch (error) {
|
||||
logger.error('Error reinstating admin', { error, auth0Sub });
|
||||
logger.error('Error reinstating admin', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -150,12 +159,4 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
async linkAdminAuth0Sub(email: string, auth0Sub: string): Promise<AdminUser> {
|
||||
try {
|
||||
return await this.repository.updateAuth0SubByEmail(email.trim().toLowerCase(), auth0Sub);
|
||||
} catch (error) {
|
||||
logger.error('Error linking admin auth0_sub to email', { error, email, auth0Sub });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
*/
|
||||
|
||||
export interface AdminUser {
|
||||
auth0Sub: string;
|
||||
id: string;
|
||||
userProfileId: string;
|
||||
email: string;
|
||||
role: 'admin' | 'super_admin';
|
||||
createdAt: Date;
|
||||
@@ -19,11 +20,11 @@ export interface CreateAdminRequest {
|
||||
}
|
||||
|
||||
export interface RevokeAdminRequest {
|
||||
auth0Sub: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface ReinstateAdminRequest {
|
||||
auth0Sub: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface AdminAuditLog {
|
||||
@@ -71,25 +72,25 @@ export interface BulkCreateAdminResponse {
|
||||
}
|
||||
|
||||
export interface BulkRevokeAdminRequest {
|
||||
auth0Subs: string[];
|
||||
ids: string[];
|
||||
}
|
||||
|
||||
export interface BulkRevokeAdminResponse {
|
||||
revoked: AdminUser[];
|
||||
failed: Array<{
|
||||
auth0Sub: string;
|
||||
id: string;
|
||||
error: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface BulkReinstateAdminRequest {
|
||||
auth0Subs: string[];
|
||||
ids: string[];
|
||||
}
|
||||
|
||||
export interface BulkReinstateAdminResponse {
|
||||
reinstated: AdminUser[];
|
||||
failed: Array<{
|
||||
auth0Sub: string;
|
||||
id: string;
|
||||
error: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
@@ -4,18 +4,19 @@
|
||||
*/
|
||||
|
||||
import request from 'supertest';
|
||||
import { app } from '../../../../app';
|
||||
import { buildApp } from '../../../../app';
|
||||
import pool from '../../../../core/config/database';
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import fastifyPlugin from 'fastify-plugin';
|
||||
import { setAdminGuardPool } from '../../../../core/plugins/admin-guard.plugin';
|
||||
|
||||
const DEFAULT_ADMIN_SUB = 'test-admin-123';
|
||||
const DEFAULT_ADMIN_ID = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const DEFAULT_ADMIN_EMAIL = 'test-admin@motovaultpro.com';
|
||||
|
||||
let currentUser = {
|
||||
sub: DEFAULT_ADMIN_SUB,
|
||||
sub: 'auth0|test-admin-123',
|
||||
email: DEFAULT_ADMIN_EMAIL,
|
||||
};
|
||||
|
||||
@@ -25,11 +26,15 @@ jest.mock('../../../../core/plugins/auth.plugin', () => {
|
||||
default: fastifyPlugin(async function(fastify) {
|
||||
fastify.decorate('authenticate', async function(request, _reply) {
|
||||
// Inject dynamic test user context
|
||||
// JWT sub is still auth0|xxx format
|
||||
request.user = { sub: currentUser.sub };
|
||||
request.userContext = {
|
||||
userId: currentUser.sub,
|
||||
userId: DEFAULT_ADMIN_ID,
|
||||
email: currentUser.email,
|
||||
emailVerified: true,
|
||||
onboardingCompleted: true,
|
||||
isAdmin: false, // Will be set by admin guard
|
||||
subscriptionTier: 'free',
|
||||
};
|
||||
});
|
||||
}, { name: 'auth-plugin' })
|
||||
@@ -37,10 +42,14 @@ jest.mock('../../../../core/plugins/auth.plugin', () => {
|
||||
});
|
||||
|
||||
describe('Admin Management Integration Tests', () => {
|
||||
let testAdminAuth0Sub: string;
|
||||
let testNonAdminAuth0Sub: string;
|
||||
let app: FastifyInstance;
|
||||
let testAdminId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
// Build the app
|
||||
app = await buildApp();
|
||||
await app.ready();
|
||||
|
||||
// Run the admin migration directly using the migration file
|
||||
const migrationFile = join(__dirname, '../../migrations/001_create_admin_users.sql');
|
||||
const migrationSQL = readFileSync(migrationFile, 'utf-8');
|
||||
@@ -50,33 +59,31 @@ describe('Admin Management Integration Tests', () => {
|
||||
setAdminGuardPool(pool);
|
||||
|
||||
// Create test admin user
|
||||
testAdminAuth0Sub = DEFAULT_ADMIN_SUB;
|
||||
testAdminId = DEFAULT_ADMIN_ID;
|
||||
await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (auth0_sub) DO NOTHING
|
||||
`, [testAdminAuth0Sub, DEFAULT_ADMIN_EMAIL, 'admin', 'system']);
|
||||
|
||||
// Create test non-admin auth0Sub for permission tests
|
||||
testNonAdminAuth0Sub = 'test-non-admin-456';
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (user_profile_id) DO NOTHING
|
||||
`, [testAdminId, testAdminId, DEFAULT_ADMIN_EMAIL, 'admin', 'system']);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Clean up test database
|
||||
await pool.query('DROP TABLE IF EXISTS admin_audit_logs CASCADE');
|
||||
await pool.query('DROP TABLE IF EXISTS admin_users CASCADE');
|
||||
await app.close();
|
||||
await pool.end();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
// Clean up test data before each test (except the test admin)
|
||||
await pool.query(
|
||||
'DELETE FROM admin_users WHERE auth0_sub != $1 AND auth0_sub != $2',
|
||||
[testAdminAuth0Sub, 'system|bootstrap']
|
||||
'DELETE FROM admin_users WHERE user_profile_id != $1',
|
||||
[testAdminId]
|
||||
);
|
||||
await pool.query('DELETE FROM admin_audit_logs');
|
||||
currentUser = {
|
||||
sub: DEFAULT_ADMIN_SUB,
|
||||
sub: 'auth0|test-admin-123',
|
||||
email: DEFAULT_ADMIN_EMAIL,
|
||||
};
|
||||
});
|
||||
@@ -85,11 +92,11 @@ describe('Admin Management Integration Tests', () => {
|
||||
it('should reject non-admin user trying to list admins', async () => {
|
||||
// Create mock for non-admin user
|
||||
currentUser = {
|
||||
sub: testNonAdminAuth0Sub,
|
||||
sub: 'auth0|test-non-admin-456',
|
||||
email: 'test-user@example.com',
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/admins')
|
||||
.expect(403);
|
||||
|
||||
@@ -101,51 +108,51 @@ describe('Admin Management Integration Tests', () => {
|
||||
describe('GET /api/admin/verify', () => {
|
||||
it('should confirm admin access for existing admin', async () => {
|
||||
currentUser = {
|
||||
sub: testAdminAuth0Sub,
|
||||
sub: 'auth0|test-admin-123',
|
||||
email: DEFAULT_ADMIN_EMAIL,
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/verify')
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.isAdmin).toBe(true);
|
||||
expect(response.body.adminRecord).toMatchObject({
|
||||
auth0Sub: testAdminAuth0Sub,
|
||||
id: testAdminId,
|
||||
email: DEFAULT_ADMIN_EMAIL,
|
||||
});
|
||||
});
|
||||
|
||||
it('should link admin record by email when auth0_sub differs', async () => {
|
||||
const placeholderSub = 'auth0|placeholder-sub';
|
||||
const realSub = 'auth0|real-admin-sub';
|
||||
it('should link admin record by email when user_profile_id differs', async () => {
|
||||
const placeholderId = '9b9a1234-1234-1234-1234-123456789abc';
|
||||
const realId = 'a1b2c3d4-5678-90ab-cdef-123456789def';
|
||||
const email = 'link-admin@example.com';
|
||||
|
||||
await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`, [placeholderSub, email, 'admin', testAdminAuth0Sub]);
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, [placeholderId, placeholderId, email, 'admin', testAdminId]);
|
||||
|
||||
currentUser = {
|
||||
sub: realSub,
|
||||
sub: 'auth0|real-admin-sub',
|
||||
email,
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/verify')
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.isAdmin).toBe(true);
|
||||
expect(response.body.adminRecord).toMatchObject({
|
||||
auth0Sub: realSub,
|
||||
userProfileId: realId,
|
||||
email,
|
||||
});
|
||||
|
||||
const record = await pool.query(
|
||||
'SELECT auth0_sub FROM admin_users WHERE email = $1',
|
||||
'SELECT user_profile_id FROM admin_users WHERE email = $1',
|
||||
[email]
|
||||
);
|
||||
expect(record.rows[0].auth0_sub).toBe(realSub);
|
||||
expect(record.rows[0].user_profile_id).toBe(realId);
|
||||
});
|
||||
|
||||
it('should return non-admin response for unknown user', async () => {
|
||||
@@ -154,7 +161,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
email: 'non-admin@example.com',
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/verify')
|
||||
.expect(200);
|
||||
|
||||
@@ -166,17 +173,19 @@ describe('Admin Management Integration Tests', () => {
|
||||
describe('GET /api/admin/admins', () => {
|
||||
it('should list all admin users', async () => {
|
||||
// Create additional test admins
|
||||
const admin1Id = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
||||
const admin2Id = '8f14e45f-ceea-367f-a27f-c9a6d0c67e0e';
|
||||
await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by)
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by)
|
||||
VALUES
|
||||
($1, $2, $3, $4),
|
||||
($5, $6, $7, $8)
|
||||
($1, $2, $3, $4, $5),
|
||||
($6, $7, $8, $9, $10)
|
||||
`, [
|
||||
'auth0|admin1', 'admin1@example.com', 'admin', testAdminAuth0Sub,
|
||||
'auth0|admin2', 'admin2@example.com', 'super_admin', testAdminAuth0Sub
|
||||
admin1Id, admin1Id, 'admin1@example.com', 'admin', testAdminId,
|
||||
admin2Id, admin2Id, 'admin2@example.com', 'super_admin', testAdminId
|
||||
]);
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/admins')
|
||||
.expect(200);
|
||||
|
||||
@@ -184,7 +193,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
expect(response.body).toHaveProperty('admins');
|
||||
expect(response.body.admins.length).toBeGreaterThanOrEqual(3); // At least test admin + 2 created
|
||||
expect(response.body.admins[0]).toMatchObject({
|
||||
auth0Sub: expect.any(String),
|
||||
id: expect.any(String),
|
||||
email: expect.any(String),
|
||||
role: expect.stringMatching(/^(admin|super_admin)$/),
|
||||
createdAt: expect.any(String),
|
||||
@@ -194,12 +203,13 @@ describe('Admin Management Integration Tests', () => {
|
||||
|
||||
it('should include revoked admins in the list', async () => {
|
||||
// Create and revoke an admin
|
||||
const revokedId = 'f1e2d3c4-b5a6-9788-6543-210fedcba987';
|
||||
await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by, revoked_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
|
||||
`, ['auth0|revoked', 'revoked@example.com', 'admin', testAdminAuth0Sub]);
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by, revoked_at)
|
||||
VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP)
|
||||
`, [revokedId, revokedId, 'revoked@example.com', 'admin', testAdminId]);
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/admins')
|
||||
.expect(200);
|
||||
|
||||
@@ -218,17 +228,17 @@ describe('Admin Management Integration Tests', () => {
|
||||
role: 'admin'
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send(newAdminData)
|
||||
.expect(201);
|
||||
|
||||
expect(response.body).toMatchObject({
|
||||
auth0Sub: expect.any(String),
|
||||
id: expect.any(String),
|
||||
email: 'newadmin@example.com',
|
||||
role: 'admin',
|
||||
createdAt: expect.any(String),
|
||||
createdBy: testAdminAuth0Sub,
|
||||
createdBy: testAdminId,
|
||||
revokedAt: null
|
||||
});
|
||||
|
||||
@@ -238,7 +248,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
['CREATE', 'newadmin@example.com']
|
||||
);
|
||||
expect(auditResult.rows.length).toBe(1);
|
||||
expect(auditResult.rows[0].actor_admin_id).toBe(testAdminAuth0Sub);
|
||||
expect(auditResult.rows[0].actor_admin_id).toBe(testAdminId);
|
||||
});
|
||||
|
||||
it('should reject invalid email', async () => {
|
||||
@@ -247,7 +257,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
role: 'admin'
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send(invalidData)
|
||||
.expect(400);
|
||||
@@ -263,13 +273,13 @@ describe('Admin Management Integration Tests', () => {
|
||||
};
|
||||
|
||||
// Create first admin
|
||||
await request(app)
|
||||
await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send(adminData)
|
||||
.expect(201);
|
||||
|
||||
// Try to create duplicate
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send(adminData)
|
||||
.expect(400);
|
||||
@@ -284,7 +294,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
role: 'super_admin'
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send(superAdminData)
|
||||
.expect(201);
|
||||
@@ -297,7 +307,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
email: 'defaultrole@example.com'
|
||||
};
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send(adminData)
|
||||
.expect(201);
|
||||
@@ -306,23 +316,24 @@ describe('Admin Management Integration Tests', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/admin/admins/:auth0Sub/revoke', () => {
|
||||
describe('PATCH /api/admin/admins/:id/revoke', () => {
|
||||
it('should revoke admin access', async () => {
|
||||
// Create admin to revoke
|
||||
const toRevokeId = 'b1c2d3e4-f5a6-7890-1234-567890abcdef';
|
||||
const createResult = await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING auth0_sub
|
||||
`, ['auth0|to-revoke', 'torevoke@example.com', 'admin', testAdminAuth0Sub]);
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id
|
||||
`, [toRevokeId, toRevokeId, 'torevoke@example.com', 'admin', testAdminId]);
|
||||
|
||||
const auth0Sub = createResult.rows[0].auth0_sub;
|
||||
const adminId = createResult.rows[0].id;
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/admin/admins/${auth0Sub}/revoke`)
|
||||
const response = await request(app.server)
|
||||
.patch(`/api/admin/admins/${adminId}/revoke`)
|
||||
.expect(200);
|
||||
|
||||
expect(response.body).toMatchObject({
|
||||
auth0Sub,
|
||||
id: adminId,
|
||||
email: 'torevoke@example.com',
|
||||
revokedAt: expect.any(String)
|
||||
});
|
||||
@@ -330,7 +341,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
// Verify audit log
|
||||
const auditResult = await pool.query(
|
||||
'SELECT * FROM admin_audit_logs WHERE action = $1 AND target_admin_id = $2',
|
||||
['REVOKE', auth0Sub]
|
||||
['REVOKE', adminId]
|
||||
);
|
||||
expect(auditResult.rows.length).toBe(1);
|
||||
});
|
||||
@@ -338,12 +349,12 @@ describe('Admin Management Integration Tests', () => {
|
||||
it('should prevent revoking last active admin', async () => {
|
||||
// First, ensure only one active admin exists
|
||||
await pool.query(
|
||||
'UPDATE admin_users SET revoked_at = CURRENT_TIMESTAMP WHERE auth0_sub != $1',
|
||||
[testAdminAuth0Sub]
|
||||
'UPDATE admin_users SET revoked_at = CURRENT_TIMESTAMP WHERE user_profile_id != $1',
|
||||
[testAdminId]
|
||||
);
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/admin/admins/${testAdminAuth0Sub}/revoke`)
|
||||
const response = await request(app.server)
|
||||
.patch(`/api/admin/admins/${testAdminId}/revoke`)
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error).toBe('Bad Request');
|
||||
@@ -351,8 +362,8 @@ describe('Admin Management Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('should return 404 for non-existent admin', async () => {
|
||||
const response = await request(app)
|
||||
.patch('/api/admin/admins/auth0|nonexistent/revoke')
|
||||
const response = await request(app.server)
|
||||
.patch('/api/admin/admins/00000000-0000-0000-0000-000000000000/revoke')
|
||||
.expect(404);
|
||||
|
||||
expect(response.body.error).toBe('Not Found');
|
||||
@@ -360,23 +371,24 @@ describe('Admin Management Integration Tests', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/admin/admins/:auth0Sub/reinstate', () => {
|
||||
describe('PATCH /api/admin/admins/:id/reinstate', () => {
|
||||
it('should reinstate revoked admin', async () => {
|
||||
// Create revoked admin
|
||||
const reinstateId = 'c2d3e4f5-a6b7-8901-2345-678901bcdef0';
|
||||
const createResult = await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by, revoked_at)
|
||||
VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
|
||||
RETURNING auth0_sub
|
||||
`, ['auth0|to-reinstate', 'toreinstate@example.com', 'admin', testAdminAuth0Sub]);
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by, revoked_at)
|
||||
VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP)
|
||||
RETURNING id
|
||||
`, [reinstateId, reinstateId, 'toreinstate@example.com', 'admin', testAdminId]);
|
||||
|
||||
const auth0Sub = createResult.rows[0].auth0_sub;
|
||||
const adminId = createResult.rows[0].id;
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/admin/admins/${auth0Sub}/reinstate`)
|
||||
const response = await request(app.server)
|
||||
.patch(`/api/admin/admins/${adminId}/reinstate`)
|
||||
.expect(200);
|
||||
|
||||
expect(response.body).toMatchObject({
|
||||
auth0Sub,
|
||||
id: adminId,
|
||||
email: 'toreinstate@example.com',
|
||||
revokedAt: null
|
||||
});
|
||||
@@ -384,14 +396,14 @@ describe('Admin Management Integration Tests', () => {
|
||||
// Verify audit log
|
||||
const auditResult = await pool.query(
|
||||
'SELECT * FROM admin_audit_logs WHERE action = $1 AND target_admin_id = $2',
|
||||
['REINSTATE', auth0Sub]
|
||||
['REINSTATE', adminId]
|
||||
);
|
||||
expect(auditResult.rows.length).toBe(1);
|
||||
});
|
||||
|
||||
it('should return 404 for non-existent admin', async () => {
|
||||
const response = await request(app)
|
||||
.patch('/api/admin/admins/auth0|nonexistent/reinstate')
|
||||
const response = await request(app.server)
|
||||
.patch('/api/admin/admins/00000000-0000-0000-0000-000000000000/reinstate')
|
||||
.expect(404);
|
||||
|
||||
expect(response.body.error).toBe('Not Found');
|
||||
@@ -400,16 +412,17 @@ describe('Admin Management Integration Tests', () => {
|
||||
|
||||
it('should handle reinstating already active admin', async () => {
|
||||
// Create active admin
|
||||
const activeId = 'd3e4f5a6-b7c8-9012-3456-789012cdef01';
|
||||
const createResult = await pool.query(`
|
||||
INSERT INTO admin_users (auth0_sub, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING auth0_sub
|
||||
`, ['auth0|already-active', 'active@example.com', 'admin', testAdminAuth0Sub]);
|
||||
INSERT INTO admin_users (id, user_profile_id, email, role, created_by)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id
|
||||
`, [activeId, activeId, 'active@example.com', 'admin', testAdminId]);
|
||||
|
||||
const auth0Sub = createResult.rows[0].auth0_sub;
|
||||
const adminId = createResult.rows[0].id;
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/admin/admins/${auth0Sub}/reinstate`)
|
||||
const response = await request(app.server)
|
||||
.patch(`/api/admin/admins/${adminId}/reinstate`)
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.revokedAt).toBeNull();
|
||||
@@ -426,12 +439,12 @@ describe('Admin Management Integration Tests', () => {
|
||||
($5, $6, $7, $8),
|
||||
($9, $10, $11, $12)
|
||||
`, [
|
||||
testAdminAuth0Sub, 'CREATE', 'admin_user', 'test1@example.com',
|
||||
testAdminAuth0Sub, 'REVOKE', 'admin_user', 'test2@example.com',
|
||||
testAdminAuth0Sub, 'REINSTATE', 'admin_user', 'test3@example.com'
|
||||
testAdminId, 'CREATE', 'admin_user', 'test1@example.com',
|
||||
testAdminId, 'REVOKE', 'admin_user', 'test2@example.com',
|
||||
testAdminId, 'REINSTATE', 'admin_user', 'test3@example.com'
|
||||
]);
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/audit-logs')
|
||||
.expect(200);
|
||||
|
||||
@@ -440,7 +453,7 @@ describe('Admin Management Integration Tests', () => {
|
||||
expect(response.body.logs.length).toBeGreaterThanOrEqual(3);
|
||||
expect(response.body.logs[0]).toMatchObject({
|
||||
id: expect.any(String),
|
||||
actorAdminId: testAdminAuth0Sub,
|
||||
actorAdminId: testAdminId,
|
||||
action: expect.any(String),
|
||||
resourceType: expect.any(String),
|
||||
createdAt: expect.any(String)
|
||||
@@ -453,10 +466,10 @@ describe('Admin Management Integration Tests', () => {
|
||||
await pool.query(`
|
||||
INSERT INTO admin_audit_logs (actor_admin_id, action, resource_type, resource_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`, [testAdminAuth0Sub, 'CREATE', 'admin_user', `test${i}@example.com`]);
|
||||
`, [testAdminId, 'CREATE', 'admin_user', `test${i}@example.com`]);
|
||||
}
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/audit-logs?limit=5&offset=0')
|
||||
.expect(200);
|
||||
|
||||
@@ -473,12 +486,12 @@ describe('Admin Management Integration Tests', () => {
|
||||
($3, $4, CURRENT_TIMESTAMP - INTERVAL '1 minute'),
|
||||
($5, $6, CURRENT_TIMESTAMP)
|
||||
`, [
|
||||
testAdminAuth0Sub, 'FIRST',
|
||||
testAdminAuth0Sub, 'SECOND',
|
||||
testAdminAuth0Sub, 'THIRD'
|
||||
testAdminId, 'FIRST',
|
||||
testAdminId, 'SECOND',
|
||||
testAdminId, 'THIRD'
|
||||
]);
|
||||
|
||||
const response = await request(app)
|
||||
const response = await request(app.server)
|
||||
.get('/api/admin/audit-logs?limit=3')
|
||||
.expect(200);
|
||||
|
||||
@@ -491,45 +504,45 @@ describe('Admin Management Integration Tests', () => {
|
||||
describe('End-to-end workflow', () => {
|
||||
it('should create, revoke, and reinstate admin with full audit trail', async () => {
|
||||
// 1. Create new admin
|
||||
const createResponse = await request(app)
|
||||
const createResponse = await request(app.server)
|
||||
.post('/api/admin/admins')
|
||||
.send({ email: 'workflow@example.com', role: 'admin' })
|
||||
.expect(201);
|
||||
|
||||
const auth0Sub = createResponse.body.auth0Sub;
|
||||
const adminId = createResponse.body.id;
|
||||
|
||||
// 2. Verify admin appears in list
|
||||
const listResponse = await request(app)
|
||||
const listResponse = await request(app.server)
|
||||
.get('/api/admin/admins')
|
||||
.expect(200);
|
||||
|
||||
const createdAdmin = listResponse.body.admins.find(
|
||||
(admin: any) => admin.auth0Sub === auth0Sub
|
||||
(admin: any) => admin.id === adminId
|
||||
);
|
||||
expect(createdAdmin).toBeDefined();
|
||||
expect(createdAdmin.revokedAt).toBeNull();
|
||||
|
||||
// 3. Revoke admin
|
||||
const revokeResponse = await request(app)
|
||||
.patch(`/api/admin/admins/${auth0Sub}/revoke`)
|
||||
const revokeResponse = await request(app.server)
|
||||
.patch(`/api/admin/admins/${adminId}/revoke`)
|
||||
.expect(200);
|
||||
|
||||
expect(revokeResponse.body.revokedAt).toBeTruthy();
|
||||
|
||||
// 4. Reinstate admin
|
||||
const reinstateResponse = await request(app)
|
||||
.patch(`/api/admin/admins/${auth0Sub}/reinstate`)
|
||||
const reinstateResponse = await request(app.server)
|
||||
.patch(`/api/admin/admins/${adminId}/reinstate`)
|
||||
.expect(200);
|
||||
|
||||
expect(reinstateResponse.body.revokedAt).toBeNull();
|
||||
|
||||
// 5. Verify complete audit trail
|
||||
const auditResponse = await request(app)
|
||||
const auditResponse = await request(app.server)
|
||||
.get('/api/admin/audit-logs')
|
||||
.expect(200);
|
||||
|
||||
const workflowLogs = auditResponse.body.logs.filter(
|
||||
(log: any) => log.targetAdminId === auth0Sub || log.resourceId === 'workflow@example.com'
|
||||
(log: any) => log.targetAdminId === adminId || log.resourceId === 'workflow@example.com'
|
||||
);
|
||||
|
||||
expect(workflowLogs.length).toBeGreaterThanOrEqual(3);
|
||||
|
||||
@@ -26,7 +26,7 @@ describe('admin guard plugin', () => {
|
||||
fastify = Fastify();
|
||||
authenticateMock = jest.fn(async (request: FastifyRequest) => {
|
||||
request.userContext = {
|
||||
userId: 'auth0|admin',
|
||||
userId: '7c9e6679-7425-40de-944b-e07fc1f90ae7',
|
||||
email: 'admin@motovaultpro.com',
|
||||
emailVerified: true,
|
||||
onboardingCompleted: true,
|
||||
@@ -41,7 +41,7 @@ describe('admin guard plugin', () => {
|
||||
mockPool = {
|
||||
query: jest.fn().mockResolvedValue({
|
||||
rows: [{
|
||||
auth0_sub: 'auth0|admin',
|
||||
user_profile_id: '7c9e6679-7425-40de-944b-e07fc1f90ae7',
|
||||
email: 'admin@motovaultpro.com',
|
||||
role: 'admin',
|
||||
revoked_at: null,
|
||||
|
||||
@@ -6,13 +6,23 @@
|
||||
import { AdminService } from '../../domain/admin.service';
|
||||
import { AdminRepository } from '../../data/admin.repository';
|
||||
|
||||
// Mock the audit log service
|
||||
jest.mock('../../../audit-log', () => ({
|
||||
auditLogService: {
|
||||
info: jest.fn().mockResolvedValue(undefined),
|
||||
warn: jest.fn().mockResolvedValue(undefined),
|
||||
error: jest.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('AdminService', () => {
|
||||
let adminService: AdminService;
|
||||
let mockRepository: jest.Mocked<AdminRepository>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockRepository = {
|
||||
getAdminByAuth0Sub: jest.fn(),
|
||||
getAdminById: jest.fn(),
|
||||
getAdminByUserProfileId: jest.fn(),
|
||||
getAdminByEmail: jest.fn(),
|
||||
getAllAdmins: jest.fn(),
|
||||
getActiveAdmins: jest.fn(),
|
||||
@@ -26,30 +36,31 @@ describe('AdminService', () => {
|
||||
adminService = new AdminService(mockRepository);
|
||||
});
|
||||
|
||||
describe('getAdminByAuth0Sub', () => {
|
||||
describe('getAdminById', () => {
|
||||
it('should return admin when found', async () => {
|
||||
const mockAdmin = {
|
||||
auth0Sub: 'auth0|123456',
|
||||
id: '7c9e6679-7425-40de-944b-e07fc1f90ae7',
|
||||
userProfileId: '7c9e6679-7425-40de-944b-e07fc1f90ae7',
|
||||
email: 'admin@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockRepository.getAdminByAuth0Sub.mockResolvedValue(mockAdmin);
|
||||
mockRepository.getAdminById.mockResolvedValue(mockAdmin);
|
||||
|
||||
const result = await adminService.getAdminByAuth0Sub('auth0|123456');
|
||||
const result = await adminService.getAdminById('7c9e6679-7425-40de-944b-e07fc1f90ae7');
|
||||
|
||||
expect(result).toEqual(mockAdmin);
|
||||
expect(mockRepository.getAdminByAuth0Sub).toHaveBeenCalledWith('auth0|123456');
|
||||
expect(mockRepository.getAdminById).toHaveBeenCalledWith('7c9e6679-7425-40de-944b-e07fc1f90ae7');
|
||||
});
|
||||
|
||||
it('should return null when admin not found', async () => {
|
||||
mockRepository.getAdminByAuth0Sub.mockResolvedValue(null);
|
||||
mockRepository.getAdminById.mockResolvedValue(null);
|
||||
|
||||
const result = await adminService.getAdminByAuth0Sub('auth0|unknown');
|
||||
const result = await adminService.getAdminById('00000000-0000-0000-0000-000000000000');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
@@ -57,12 +68,15 @@ describe('AdminService', () => {
|
||||
|
||||
describe('createAdmin', () => {
|
||||
it('should create new admin and log audit', async () => {
|
||||
const newAdminId = '8f14e45f-ceea-367f-a27f-c9a6d0c67e0e';
|
||||
const creatorId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const mockAdmin = {
|
||||
auth0Sub: 'auth0|newadmin',
|
||||
id: newAdminId,
|
||||
userProfileId: newAdminId,
|
||||
email: 'newadmin@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'auth0|existing',
|
||||
createdBy: creatorId,
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
@@ -74,16 +88,16 @@ describe('AdminService', () => {
|
||||
const result = await adminService.createAdmin(
|
||||
'newadmin@motovaultpro.com',
|
||||
'admin',
|
||||
'auth0|newadmin',
|
||||
'auth0|existing'
|
||||
newAdminId,
|
||||
creatorId
|
||||
);
|
||||
|
||||
expect(result).toEqual(mockAdmin);
|
||||
expect(mockRepository.createAdmin).toHaveBeenCalled();
|
||||
expect(mockRepository.logAuditAction).toHaveBeenCalledWith(
|
||||
'auth0|existing',
|
||||
creatorId,
|
||||
'CREATE',
|
||||
mockAdmin.auth0Sub,
|
||||
mockAdmin.id,
|
||||
'admin_user',
|
||||
mockAdmin.email,
|
||||
expect.any(Object)
|
||||
@@ -91,12 +105,14 @@ describe('AdminService', () => {
|
||||
});
|
||||
|
||||
it('should reject if admin already exists', async () => {
|
||||
const existingId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const existingAdmin = {
|
||||
auth0Sub: 'auth0|existing',
|
||||
id: existingId,
|
||||
userProfileId: existingId,
|
||||
email: 'admin@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
@@ -104,39 +120,46 @@ describe('AdminService', () => {
|
||||
mockRepository.getAdminByEmail.mockResolvedValue(existingAdmin);
|
||||
|
||||
await expect(
|
||||
adminService.createAdmin('admin@motovaultpro.com', 'admin', 'auth0|new', 'auth0|existing')
|
||||
adminService.createAdmin('admin@motovaultpro.com', 'admin', '8f14e45f-ceea-367f-a27f-c9a6d0c67e0e', existingId)
|
||||
).rejects.toThrow('already exists');
|
||||
});
|
||||
});
|
||||
|
||||
describe('revokeAdmin', () => {
|
||||
it('should revoke admin when multiple active admins exist', async () => {
|
||||
const toRevokeId = 'a1b2c3d4-e5f6-7890-1234-567890abcdef';
|
||||
const admin1Id = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
||||
const admin2Id = '8f14e45f-ceea-367f-a27f-c9a6d0c67e0e';
|
||||
|
||||
const revokedAdmin = {
|
||||
auth0Sub: 'auth0|toadmin',
|
||||
id: toRevokeId,
|
||||
userProfileId: toRevokeId,
|
||||
email: 'toadmin@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
const activeAdmins = [
|
||||
{
|
||||
auth0Sub: 'auth0|admin1',
|
||||
id: admin1Id,
|
||||
userProfileId: admin1Id,
|
||||
email: 'admin1@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
{
|
||||
auth0Sub: 'auth0|admin2',
|
||||
id: admin2Id,
|
||||
userProfileId: admin2Id,
|
||||
email: 'admin2@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
@@ -146,20 +169,22 @@ describe('AdminService', () => {
|
||||
mockRepository.revokeAdmin.mockResolvedValue(revokedAdmin);
|
||||
mockRepository.logAuditAction.mockResolvedValue({} as any);
|
||||
|
||||
const result = await adminService.revokeAdmin('auth0|toadmin', 'auth0|admin1');
|
||||
const result = await adminService.revokeAdmin(toRevokeId, admin1Id);
|
||||
|
||||
expect(result).toEqual(revokedAdmin);
|
||||
expect(mockRepository.revokeAdmin).toHaveBeenCalledWith('auth0|toadmin');
|
||||
expect(mockRepository.revokeAdmin).toHaveBeenCalledWith(toRevokeId);
|
||||
expect(mockRepository.logAuditAction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should prevent revoking last active admin', async () => {
|
||||
const lastAdminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const lastAdmin = {
|
||||
auth0Sub: 'auth0|lastadmin',
|
||||
id: lastAdminId,
|
||||
userProfileId: lastAdminId,
|
||||
email: 'last@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
@@ -167,19 +192,22 @@ describe('AdminService', () => {
|
||||
mockRepository.getActiveAdmins.mockResolvedValue([lastAdmin]);
|
||||
|
||||
await expect(
|
||||
adminService.revokeAdmin('auth0|lastadmin', 'auth0|lastadmin')
|
||||
adminService.revokeAdmin(lastAdminId, lastAdminId)
|
||||
).rejects.toThrow('Cannot revoke the last active admin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('reinstateAdmin', () => {
|
||||
it('should reinstate revoked admin and log audit', async () => {
|
||||
const reinstateId = 'b2c3d4e5-f6a7-8901-2345-678901bcdef0';
|
||||
const adminActorId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const reinstatedAdmin = {
|
||||
auth0Sub: 'auth0|reinstate',
|
||||
id: reinstateId,
|
||||
userProfileId: reinstateId,
|
||||
email: 'reinstate@motovaultpro.com',
|
||||
role: 'admin',
|
||||
role: 'admin' as const,
|
||||
createdAt: new Date(),
|
||||
createdBy: 'system',
|
||||
createdBy: '550e8400-e29b-41d4-a716-446655440000',
|
||||
revokedAt: null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
@@ -187,14 +215,14 @@ describe('AdminService', () => {
|
||||
mockRepository.reinstateAdmin.mockResolvedValue(reinstatedAdmin);
|
||||
mockRepository.logAuditAction.mockResolvedValue({} as any);
|
||||
|
||||
const result = await adminService.reinstateAdmin('auth0|reinstate', 'auth0|admin');
|
||||
const result = await adminService.reinstateAdmin(reinstateId, adminActorId);
|
||||
|
||||
expect(result).toEqual(reinstatedAdmin);
|
||||
expect(mockRepository.reinstateAdmin).toHaveBeenCalledWith('auth0|reinstate');
|
||||
expect(mockRepository.reinstateAdmin).toHaveBeenCalledWith(reinstateId);
|
||||
expect(mockRepository.logAuditAction).toHaveBeenCalledWith(
|
||||
'auth0|admin',
|
||||
adminActorId,
|
||||
'REINSTATE',
|
||||
'auth0|reinstate',
|
||||
reinstateId,
|
||||
'admin_user',
|
||||
reinstatedAdmin.email
|
||||
);
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
|
||||
describe('Vehicle logging integration', () => {
|
||||
it('should create audit log with vehicle category and correct resource', async () => {
|
||||
const userId = 'test-user-vehicle-123';
|
||||
const userId = '550e8400-e29b-41d4-a716-446655440000';
|
||||
const vehicleId = 'vehicle-uuid-123';
|
||||
const entry = await service.info(
|
||||
'vehicle',
|
||||
@@ -56,7 +56,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should log vehicle update with correct fields', async () => {
|
||||
const userId = 'test-user-vehicle-456';
|
||||
const userId = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
||||
const vehicleId = 'vehicle-uuid-456';
|
||||
const entry = await service.info(
|
||||
'vehicle',
|
||||
@@ -75,7 +75,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should log vehicle deletion with vehicle info', async () => {
|
||||
const userId = 'test-user-vehicle-789';
|
||||
const userId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const vehicleId = 'vehicle-uuid-789';
|
||||
const entry = await service.info(
|
||||
'vehicle',
|
||||
@@ -96,7 +96,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
|
||||
describe('Auth logging integration', () => {
|
||||
it('should create audit log with auth category for signup', async () => {
|
||||
const userId = 'test-user-auth-123';
|
||||
const userId = '550e8400-e29b-41d4-a716-446655440000';
|
||||
const entry = await service.info(
|
||||
'auth',
|
||||
userId,
|
||||
@@ -116,7 +116,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should create audit log for password reset request', async () => {
|
||||
const userId = 'test-user-auth-456';
|
||||
const userId = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
||||
const entry = await service.info(
|
||||
'auth',
|
||||
userId,
|
||||
@@ -134,14 +134,14 @@ describe('AuditLog Feature Integration', () => {
|
||||
|
||||
describe('Admin logging integration', () => {
|
||||
it('should create audit log for admin user creation', async () => {
|
||||
const adminId = 'admin-user-123';
|
||||
const targetAdminSub = 'auth0|target-admin-456';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const targetAdminId = '8f14e45f-ceea-367f-a27f-c9a6d0c67e0e';
|
||||
const entry = await service.info(
|
||||
'admin',
|
||||
adminId,
|
||||
'Admin user created: newadmin@example.com',
|
||||
'admin_user',
|
||||
targetAdminSub,
|
||||
targetAdminId,
|
||||
{ email: 'newadmin@example.com', role: 'admin' }
|
||||
);
|
||||
|
||||
@@ -156,14 +156,14 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should create audit log for admin revocation', async () => {
|
||||
const adminId = 'admin-user-123';
|
||||
const targetAdminSub = 'auth0|target-admin-789';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const targetAdminId = 'a1b2c3d4-e5f6-7890-1234-567890abcdef';
|
||||
const entry = await service.info(
|
||||
'admin',
|
||||
adminId,
|
||||
'Admin user revoked: revoked@example.com',
|
||||
'admin_user',
|
||||
targetAdminSub,
|
||||
targetAdminId,
|
||||
{ email: 'revoked@example.com' }
|
||||
);
|
||||
|
||||
@@ -174,14 +174,14 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should create audit log for admin reinstatement', async () => {
|
||||
const adminId = 'admin-user-123';
|
||||
const targetAdminSub = 'auth0|target-admin-reinstated';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const targetAdminId = 'b2c3d4e5-f6a7-8901-2345-678901bcdef0';
|
||||
const entry = await service.info(
|
||||
'admin',
|
||||
adminId,
|
||||
'Admin user reinstated: reinstated@example.com',
|
||||
'admin_user',
|
||||
targetAdminSub,
|
||||
targetAdminId,
|
||||
{ email: 'reinstated@example.com' }
|
||||
);
|
||||
|
||||
@@ -194,7 +194,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
|
||||
describe('Backup/System logging integration', () => {
|
||||
it('should create audit log for backup creation', async () => {
|
||||
const adminId = 'admin-user-backup-123';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const backupId = 'backup-uuid-123';
|
||||
const entry = await service.info(
|
||||
'system',
|
||||
@@ -215,7 +215,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should create audit log for backup restore', async () => {
|
||||
const adminId = 'admin-user-backup-456';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const backupId = 'backup-uuid-456';
|
||||
const entry = await service.info(
|
||||
'system',
|
||||
@@ -233,7 +233,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should create error-level audit log for backup failure', async () => {
|
||||
const adminId = 'admin-user-backup-789';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const backupId = 'backup-uuid-789';
|
||||
const entry = await service.error(
|
||||
'system',
|
||||
@@ -253,7 +253,7 @@ describe('AuditLog Feature Integration', () => {
|
||||
});
|
||||
|
||||
it('should create error-level audit log for restore failure', async () => {
|
||||
const adminId = 'admin-user-restore-fail';
|
||||
const adminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
const backupId = 'backup-uuid-restore-fail';
|
||||
const entry = await service.error(
|
||||
'system',
|
||||
|
||||
@@ -126,7 +126,7 @@ export class AuditLogRepository {
|
||||
al.resource_type, al.resource_id, al.details, al.created_at,
|
||||
up.email as user_email
|
||||
FROM audit_logs al
|
||||
LEFT JOIN user_profiles up ON al.user_id = up.auth0_sub
|
||||
LEFT JOIN user_profiles up ON al.user_id = up.id
|
||||
${whereClause}
|
||||
ORDER BY al.created_at DESC
|
||||
LIMIT $${nextParamIndex} OFFSET $${nextParamIndex + 1}
|
||||
@@ -170,7 +170,7 @@ export class AuditLogRepository {
|
||||
al.resource_type, al.resource_id, al.details, al.created_at,
|
||||
up.email as user_email
|
||||
FROM audit_logs al
|
||||
LEFT JOIN user_profiles up ON al.user_id = up.auth0_sub
|
||||
LEFT JOIN user_profiles up ON al.user_id = up.id
|
||||
${whereClause}
|
||||
ORDER BY al.created_at DESC
|
||||
LIMIT ${MAX_EXPORT_RECORDS}
|
||||
|
||||
@@ -110,17 +110,17 @@ export class AuthController {
|
||||
*/
|
||||
async getVerifyStatus(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const auth0Sub = (request as any).user.sub;
|
||||
|
||||
const result = await this.authService.getVerifyStatus(userId);
|
||||
const result = await this.authService.getVerifyStatus(auth0Sub);
|
||||
|
||||
logger.info('Verification status checked', { userId, emailVerified: result.emailVerified });
|
||||
logger.info('Verification status checked', { userId: request.userContext?.userId, emailVerified: result.emailVerified });
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get verification status', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -137,17 +137,17 @@ export class AuthController {
|
||||
*/
|
||||
async resendVerification(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const auth0Sub = (request as any).user.sub;
|
||||
|
||||
const result = await this.authService.resendVerification(userId);
|
||||
const result = await this.authService.resendVerification(auth0Sub);
|
||||
|
||||
logger.info('Verification email resent', { userId });
|
||||
logger.info('Verification email resent', { userId: request.userContext?.userId });
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to resend verification email', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -199,23 +199,26 @@ export class AuthController {
|
||||
*/
|
||||
async getUserStatus(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const auth0Sub = (request as any).user.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
const result = await this.authService.getUserStatus(userId);
|
||||
const result = await this.authService.getUserStatus(auth0Sub);
|
||||
|
||||
// Log login event to audit trail (called once per Auth0 callback)
|
||||
const ipAddress = this.getClientIp(request);
|
||||
await auditLogService.info(
|
||||
'auth',
|
||||
userId,
|
||||
'User login',
|
||||
'user',
|
||||
userId,
|
||||
{ ipAddress }
|
||||
).catch(err => logger.error('Failed to log login audit event', { error: err }));
|
||||
if (userId) {
|
||||
await auditLogService.info(
|
||||
'auth',
|
||||
userId,
|
||||
'User login',
|
||||
'user',
|
||||
userId,
|
||||
{ ipAddress }
|
||||
).catch(err => logger.error('Failed to log login audit event', { error: err }));
|
||||
}
|
||||
|
||||
logger.info('User status retrieved', {
|
||||
userId: userId.substring(0, 8) + '...',
|
||||
userId: userId?.substring(0, 8) + '...',
|
||||
emailVerified: result.emailVerified,
|
||||
onboardingCompleted: result.onboardingCompleted,
|
||||
});
|
||||
@@ -224,7 +227,7 @@ export class AuthController {
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get user status', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -241,12 +244,12 @@ export class AuthController {
|
||||
*/
|
||||
async getSecurityStatus(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const auth0Sub = (request as any).user.sub;
|
||||
|
||||
const result = await this.authService.getSecurityStatus(userId);
|
||||
const result = await this.authService.getSecurityStatus(auth0Sub);
|
||||
|
||||
logger.info('Security status retrieved', {
|
||||
userId: userId.substring(0, 8) + '...',
|
||||
userId: request.userContext?.userId,
|
||||
emailVerified: result.emailVerified,
|
||||
});
|
||||
|
||||
@@ -254,7 +257,7 @@ export class AuthController {
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get security status', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -271,28 +274,31 @@ export class AuthController {
|
||||
*/
|
||||
async requestPasswordReset(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const auth0Sub = (request as any).user.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
const result = await this.authService.requestPasswordReset(userId);
|
||||
const result = await this.authService.requestPasswordReset(auth0Sub);
|
||||
|
||||
logger.info('Password reset email requested', {
|
||||
userId: userId.substring(0, 8) + '...',
|
||||
userId: userId?.substring(0, 8) + '...',
|
||||
});
|
||||
|
||||
// Log password reset request to unified audit log
|
||||
await auditLogService.info(
|
||||
'auth',
|
||||
userId,
|
||||
'Password reset requested',
|
||||
'user',
|
||||
userId
|
||||
).catch(err => logger.error('Failed to log password reset audit event', { error: err }));
|
||||
if (userId) {
|
||||
await auditLogService.info(
|
||||
'auth',
|
||||
userId,
|
||||
'Password reset requested',
|
||||
'user',
|
||||
userId
|
||||
).catch(err => logger.error('Failed to log password reset audit event', { error: err }));
|
||||
}
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to request password reset', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
return reply.code(500).send({
|
||||
@@ -312,21 +318,23 @@ export class AuthController {
|
||||
*/
|
||||
async trackLogout(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
const ipAddress = this.getClientIp(request);
|
||||
|
||||
// Log logout event to audit trail
|
||||
await auditLogService.info(
|
||||
'auth',
|
||||
userId,
|
||||
'User logout',
|
||||
'user',
|
||||
userId,
|
||||
{ ipAddress }
|
||||
).catch(err => logger.error('Failed to log logout audit event', { error: err }));
|
||||
if (userId) {
|
||||
await auditLogService.info(
|
||||
'auth',
|
||||
userId,
|
||||
'User logout',
|
||||
'user',
|
||||
userId,
|
||||
{ ipAddress }
|
||||
).catch(err => logger.error('Failed to log logout audit event', { error: err }));
|
||||
}
|
||||
|
||||
logger.info('User logout tracked', {
|
||||
userId: userId.substring(0, 8) + '...',
|
||||
userId: userId?.substring(0, 8) + '...',
|
||||
});
|
||||
|
||||
return reply.code(200).send({ success: true });
|
||||
@@ -334,7 +342,7 @@ export class AuthController {
|
||||
// Don't block logout on audit failure - always return success
|
||||
logger.error('Failed to track logout', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
return reply.code(200).send({ success: true });
|
||||
|
||||
@@ -19,6 +19,7 @@ jest.mock('../../../../core/plugins/auth.plugin', () => {
|
||||
return {
|
||||
default: fastifyPlugin(async function (fastify) {
|
||||
fastify.decorate('authenticate', async function (request, _reply) {
|
||||
// JWT sub is still auth0|xxx format
|
||||
request.user = { sub: 'auth0|test-user-123' };
|
||||
});
|
||||
}, { name: 'auth-plugin' }),
|
||||
|
||||
@@ -103,6 +103,8 @@ describe('AuthService', () => {
|
||||
onboardingCompletedAt: null,
|
||||
deactivatedAt: null,
|
||||
deactivatedBy: null,
|
||||
deletionRequestedAt: null,
|
||||
deletionScheduledFor: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
@@ -116,6 +118,8 @@ describe('AuthService', () => {
|
||||
onboardingCompletedAt: null,
|
||||
deactivatedAt: null,
|
||||
deactivatedBy: null,
|
||||
deletionRequestedAt: null,
|
||||
deletionScheduledFor: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
@@ -149,6 +153,8 @@ describe('AuthService', () => {
|
||||
onboardingCompletedAt: null,
|
||||
deactivatedAt: null,
|
||||
deactivatedBy: null,
|
||||
deletionRequestedAt: null,
|
||||
deletionScheduledFor: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
@@ -45,12 +45,12 @@ export class BackupController {
|
||||
request: FastifyRequest<{ Body: CreateBackupBody }>,
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
const adminSub = (request as any).userContext?.auth0Sub;
|
||||
const adminUserId = request.userContext?.userId;
|
||||
|
||||
const result = await this.backupService.createBackup({
|
||||
name: request.body.name,
|
||||
backupType: 'manual',
|
||||
createdBy: adminSub,
|
||||
createdBy: adminUserId,
|
||||
includeDocuments: request.body.includeDocuments,
|
||||
});
|
||||
|
||||
@@ -58,7 +58,7 @@ export class BackupController {
|
||||
// Log backup creation to unified audit log
|
||||
await auditLogService.info(
|
||||
'system',
|
||||
adminSub || null,
|
||||
adminUserId || null,
|
||||
`Backup created: ${request.body.name || 'Manual backup'}`,
|
||||
'backup',
|
||||
result.backupId,
|
||||
@@ -74,7 +74,7 @@ export class BackupController {
|
||||
// Log backup failure
|
||||
await auditLogService.error(
|
||||
'system',
|
||||
adminSub || null,
|
||||
adminUserId || null,
|
||||
`Backup failed: ${request.body.name || 'Manual backup'}`,
|
||||
'backup',
|
||||
result.backupId,
|
||||
@@ -139,7 +139,7 @@ export class BackupController {
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
const adminSub = (request as any).userContext?.auth0Sub;
|
||||
const adminUserId = request.userContext?.userId;
|
||||
|
||||
// Handle multipart file upload
|
||||
const data = await request.file();
|
||||
@@ -173,7 +173,7 @@ export class BackupController {
|
||||
const backup = await this.backupService.importUploadedBackup(
|
||||
tempPath,
|
||||
filename,
|
||||
adminSub
|
||||
adminUserId
|
||||
);
|
||||
|
||||
reply.status(201).send({
|
||||
@@ -217,7 +217,7 @@ export class BackupController {
|
||||
request: FastifyRequest<{ Params: BackupIdParam; Body: RestoreBody }>,
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
const adminSub = (request as any).userContext?.auth0Sub;
|
||||
const adminUserId = request.userContext?.userId;
|
||||
|
||||
try {
|
||||
const result = await this.restoreService.executeRestore({
|
||||
@@ -229,7 +229,7 @@ export class BackupController {
|
||||
// Log successful restore to unified audit log
|
||||
await auditLogService.info(
|
||||
'system',
|
||||
adminSub || null,
|
||||
adminUserId || null,
|
||||
`Backup restored: ${request.params.id}`,
|
||||
'backup',
|
||||
request.params.id,
|
||||
@@ -246,7 +246,7 @@ export class BackupController {
|
||||
// Log restore failure
|
||||
await auditLogService.error(
|
||||
'system',
|
||||
adminSub || null,
|
||||
adminUserId || null,
|
||||
`Backup restore failed: ${request.params.id}`,
|
||||
'backup',
|
||||
request.params.id,
|
||||
|
||||
@@ -15,7 +15,7 @@ export class DocumentsController {
|
||||
private readonly service = new DocumentsService();
|
||||
|
||||
async list(request: FastifyRequest<{ Querystring: ListQuery }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Documents list requested', {
|
||||
operation: 'documents.list',
|
||||
@@ -43,7 +43,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async get(request: FastifyRequest<{ Params: IdParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const documentId = request.params.id;
|
||||
|
||||
logger.info('Document get requested', {
|
||||
@@ -74,7 +74,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async create(request: FastifyRequest<{ Body: CreateBody }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const userTier: SubscriptionTier = request.userContext?.subscriptionTier || 'free';
|
||||
|
||||
logger.info('Document create requested', {
|
||||
@@ -120,7 +120,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async update(request: FastifyRequest<{ Params: IdParams; Body: UpdateBody }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const userTier: SubscriptionTier = request.userContext?.subscriptionTier || 'free';
|
||||
const documentId = request.params.id;
|
||||
|
||||
@@ -174,7 +174,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async remove(request: FastifyRequest<{ Params: IdParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const documentId = request.params.id;
|
||||
|
||||
logger.info('Document delete requested', {
|
||||
@@ -221,7 +221,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async upload(request: FastifyRequest<{ Params: IdParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const documentId = request.params.id;
|
||||
|
||||
logger.info('Document upload requested', {
|
||||
@@ -373,7 +373,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async download(request: FastifyRequest<{ Params: IdParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const documentId = request.params.id;
|
||||
|
||||
logger.info('Document download requested', {
|
||||
@@ -423,7 +423,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async listByVehicle(request: FastifyRequest<{ Params: { vehicleId: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.vehicleId;
|
||||
|
||||
logger.info('Documents by vehicle requested', {
|
||||
@@ -457,7 +457,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async addVehicle(request: FastifyRequest<{ Params: { id: string; vehicleId: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id: documentId, vehicleId } = request.params;
|
||||
|
||||
logger.info('Add vehicle to document requested', {
|
||||
@@ -523,7 +523,7 @@ export class DocumentsController {
|
||||
}
|
||||
|
||||
async removeVehicle(request: FastifyRequest<{ Params: { id: string; vehicleId: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id: documentId, vehicleId } = request.params;
|
||||
|
||||
logger.info('Remove vehicle from document requested', {
|
||||
|
||||
@@ -27,22 +27,22 @@ export class EmailIngestionController {
|
||||
|
||||
async getPendingAssociations(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const associations = await this.repository.getPendingAssociations(userId);
|
||||
return reply.code(200).send(associations);
|
||||
} catch (error: any) {
|
||||
logger.error('Error listing pending associations', { error: error.message, userId: (request as any).user?.sub });
|
||||
logger.error('Error listing pending associations', { error: error.message, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({ error: 'Failed to list pending associations' });
|
||||
}
|
||||
}
|
||||
|
||||
async getPendingAssociationCount(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const count = await this.repository.getPendingAssociationCount(userId);
|
||||
return reply.code(200).send({ count });
|
||||
} catch (error: any) {
|
||||
logger.error('Error counting pending associations', { error: error.message, userId: (request as any).user?.sub });
|
||||
logger.error('Error counting pending associations', { error: error.message, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({ error: 'Failed to count pending associations' });
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ export class EmailIngestionController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
const { vehicleId } = request.body;
|
||||
|
||||
@@ -63,7 +63,7 @@ export class EmailIngestionController {
|
||||
const result = await this.service.resolveAssociation(id, vehicleId, userId);
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
const userId = (request as any).user?.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
logger.error('Error resolving pending association', {
|
||||
error: error.message,
|
||||
associationId: request.params.id,
|
||||
@@ -89,13 +89,13 @@ export class EmailIngestionController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
await this.service.dismissAssociation(id, userId);
|
||||
return reply.code(204).send();
|
||||
} catch (error: any) {
|
||||
const userId = (request as any).user?.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
logger.error('Error dismissing pending association', {
|
||||
error: error.message,
|
||||
associationId: request.params.id,
|
||||
|
||||
@@ -20,12 +20,12 @@ export class FuelLogsController {
|
||||
|
||||
async createFuelLog(request: FastifyRequest<{ Body: EnhancedCreateFuelLogRequest }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const fuelLog = await this.fuelLogsService.createFuelLog(request.body, userId);
|
||||
|
||||
return reply.code(201).send(fuelLog);
|
||||
} catch (error: any) {
|
||||
logger.error('Error creating fuel log', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error creating fuel log', { error, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
@@ -49,14 +49,14 @@ export class FuelLogsController {
|
||||
|
||||
async getFuelLogsByVehicle(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { vehicleId } = request.params;
|
||||
|
||||
const fuelLogs = await this.fuelLogsService.getFuelLogsByVehicle(vehicleId, userId);
|
||||
|
||||
return reply.code(200).send(fuelLogs);
|
||||
} catch (error: any) {
|
||||
logger.error('Error listing fuel logs', { error, vehicleId: request.params.vehicleId, userId: (request as any).user?.sub });
|
||||
logger.error('Error listing fuel logs', { error, vehicleId: request.params.vehicleId, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
@@ -80,12 +80,12 @@ export class FuelLogsController {
|
||||
|
||||
async getUserFuelLogs(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const fuelLogs = await this.fuelLogsService.getUserFuelLogs(userId);
|
||||
|
||||
return reply.code(200).send(fuelLogs);
|
||||
} catch (error: any) {
|
||||
logger.error('Error listing all fuel logs', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error listing all fuel logs', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to get fuel logs'
|
||||
@@ -95,14 +95,14 @@ export class FuelLogsController {
|
||||
|
||||
async getFuelLog(request: FastifyRequest<{ Params: FuelLogParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
const fuelLog = await this.fuelLogsService.getFuelLog(id, userId);
|
||||
|
||||
return reply.code(200).send(fuelLog);
|
||||
} catch (error: any) {
|
||||
logger.error('Error getting fuel log', { error, fuelLogId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting fuel log', { error, fuelLogId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message === 'Fuel log not found') {
|
||||
return reply.code(404).send({
|
||||
@@ -126,14 +126,14 @@ export class FuelLogsController {
|
||||
|
||||
async updateFuelLog(request: FastifyRequest<{ Params: FuelLogParams; Body: EnhancedUpdateFuelLogRequest }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
const updatedFuelLog = await this.fuelLogsService.updateFuelLog(id, request.body, userId);
|
||||
|
||||
return reply.code(200).send(updatedFuelLog);
|
||||
} catch (error: any) {
|
||||
logger.error('Error updating fuel log', { error, fuelLogId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error updating fuel log', { error, fuelLogId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
@@ -163,14 +163,14 @@ export class FuelLogsController {
|
||||
|
||||
async deleteFuelLog(request: FastifyRequest<{ Params: FuelLogParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
await this.fuelLogsService.deleteFuelLog(id, userId);
|
||||
|
||||
return reply.code(204).send();
|
||||
} catch (error: any) {
|
||||
logger.error('Error deleting fuel log', { error, fuelLogId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error deleting fuel log', { error, fuelLogId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
@@ -194,14 +194,14 @@ export class FuelLogsController {
|
||||
|
||||
async getFuelStats(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { vehicleId } = request.params;
|
||||
|
||||
const stats = await this.fuelLogsService.getVehicleStats(vehicleId, userId);
|
||||
|
||||
return reply.code(200).send(stats);
|
||||
} catch (error: any) {
|
||||
logger.error('Error getting fuel stats', { error, vehicleId: request.params.vehicleId, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting fuel stats', { error, vehicleId: request.params.vehicleId, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
},
|
||||
"responseWithEfficiency": {
|
||||
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
|
||||
"userId": "auth0|user123",
|
||||
"userId": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"vehicleId": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"dateTime": "2024-01-15T10:30:00Z",
|
||||
"odometerReading": 52000,
|
||||
|
||||
@@ -18,7 +18,7 @@ export class MaintenanceController {
|
||||
request: FastifyRequest<{ Querystring: { vehicleId?: string; category?: string } }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Maintenance records list requested', {
|
||||
operation: 'maintenance.records.list',
|
||||
@@ -58,7 +58,7 @@ export class MaintenanceController {
|
||||
}
|
||||
|
||||
async getRecord(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const recordId = request.params.id;
|
||||
|
||||
logger.info('Maintenance record get requested', {
|
||||
@@ -102,7 +102,7 @@ export class MaintenanceController {
|
||||
request: FastifyRequest<{ Params: { vehicleId: string } }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.vehicleId;
|
||||
|
||||
logger.info('Maintenance records by vehicle requested', {
|
||||
@@ -134,7 +134,7 @@ export class MaintenanceController {
|
||||
}
|
||||
|
||||
async createRecord(request: FastifyRequest<{ Body: unknown }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Maintenance record create requested', {
|
||||
operation: 'maintenance.records.create',
|
||||
@@ -190,7 +190,7 @@ export class MaintenanceController {
|
||||
request: FastifyRequest<{ Params: { id: string }; Body: unknown }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const recordId = request.params.id;
|
||||
|
||||
logger.info('Maintenance record update requested', {
|
||||
@@ -255,7 +255,7 @@ export class MaintenanceController {
|
||||
}
|
||||
|
||||
async deleteRecord(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const recordId = request.params.id;
|
||||
|
||||
logger.info('Maintenance record delete requested', {
|
||||
@@ -289,7 +289,7 @@ export class MaintenanceController {
|
||||
request: FastifyRequest<{ Params: { vehicleId: string } }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.vehicleId;
|
||||
|
||||
logger.info('Maintenance schedules by vehicle requested', {
|
||||
@@ -321,7 +321,7 @@ export class MaintenanceController {
|
||||
}
|
||||
|
||||
async createSchedule(request: FastifyRequest<{ Body: unknown }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Maintenance schedule create requested', {
|
||||
operation: 'maintenance.schedules.create',
|
||||
@@ -377,7 +377,7 @@ export class MaintenanceController {
|
||||
request: FastifyRequest<{ Params: { id: string }; Body: unknown }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const scheduleId = request.params.id;
|
||||
|
||||
logger.info('Maintenance schedule update requested', {
|
||||
@@ -442,7 +442,7 @@ export class MaintenanceController {
|
||||
}
|
||||
|
||||
async deleteSchedule(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const scheduleId = request.params.id;
|
||||
|
||||
logger.info('Maintenance schedule delete requested', {
|
||||
@@ -476,7 +476,7 @@ export class MaintenanceController {
|
||||
request: FastifyRequest<{ Params: { vehicleId: string }; Querystring: { currentMileage?: string } }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.vehicleId;
|
||||
const currentMileage = request.query.currentMileage ? parseInt(request.query.currentMileage, 10) : undefined;
|
||||
|
||||
@@ -510,7 +510,7 @@ export class MaintenanceController {
|
||||
}
|
||||
|
||||
async getSubtypes(request: FastifyRequest<{ Params: { category: string } }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const category = request.params.category;
|
||||
|
||||
logger.info('Maintenance subtypes requested', {
|
||||
|
||||
@@ -99,7 +99,7 @@
|
||||
},
|
||||
"maintenanceScheduleResponse": {
|
||||
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
|
||||
"userId": "auth0|user123",
|
||||
"userId": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"vehicleId": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"type": "oil_change",
|
||||
"category": "routine_maintenance",
|
||||
|
||||
@@ -24,7 +24,7 @@ export class NotificationsController {
|
||||
// ========================
|
||||
|
||||
async getSummary(request: FastifyRequest, reply: FastifyReply) {
|
||||
const userId = request.user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
try {
|
||||
const summary = await this.service.getNotificationSummary(userId);
|
||||
@@ -38,7 +38,7 @@ export class NotificationsController {
|
||||
}
|
||||
|
||||
async getDueMaintenanceItems(request: FastifyRequest, reply: FastifyReply) {
|
||||
const userId = request.user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
try {
|
||||
const items = await this.service.getDueMaintenanceItems(userId);
|
||||
@@ -52,7 +52,7 @@ export class NotificationsController {
|
||||
}
|
||||
|
||||
async getExpiringDocuments(request: FastifyRequest, reply: FastifyReply) {
|
||||
const userId = request.user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
try {
|
||||
const documents = await this.service.getExpiringDocuments(userId);
|
||||
@@ -70,7 +70,7 @@ export class NotificationsController {
|
||||
// ========================
|
||||
|
||||
async getInAppNotifications(request: FastifyRequest, reply: FastifyReply) {
|
||||
const userId = request.user!.sub!;
|
||||
const userId = request.userContext!.userId;
|
||||
const query = request.query as { limit?: string; includeRead?: string };
|
||||
const limit = query.limit ? parseInt(query.limit, 10) : 20;
|
||||
const includeRead = query.includeRead === 'true';
|
||||
@@ -85,7 +85,7 @@ export class NotificationsController {
|
||||
}
|
||||
|
||||
async getUnreadCount(request: FastifyRequest, reply: FastifyReply) {
|
||||
const userId = request.user!.sub!;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
try {
|
||||
const count = await this.service.getUnreadCount(userId);
|
||||
@@ -97,7 +97,7 @@ export class NotificationsController {
|
||||
}
|
||||
|
||||
async markAsRead(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
|
||||
const userId = request.user!.sub!;
|
||||
const userId = request.userContext!.userId;
|
||||
const notificationId = request.params.id;
|
||||
|
||||
try {
|
||||
@@ -113,7 +113,7 @@ export class NotificationsController {
|
||||
}
|
||||
|
||||
async markAllAsRead(request: FastifyRequest, reply: FastifyReply) {
|
||||
const userId = request.user!.sub!;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
try {
|
||||
const count = await this.service.markAllAsRead(userId);
|
||||
@@ -125,7 +125,7 @@ export class NotificationsController {
|
||||
}
|
||||
|
||||
async deleteNotification(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
|
||||
const userId = request.user!.sub!;
|
||||
const userId = request.userContext!.userId;
|
||||
const notificationId = request.params.id;
|
||||
|
||||
try {
|
||||
|
||||
@@ -33,7 +33,7 @@ export class OcrController {
|
||||
request: FastifyRequest<{ Querystring: ExtractQuery }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
const preprocess = request.query.preprocess !== false;
|
||||
|
||||
logger.info('OCR extract requested', {
|
||||
@@ -140,7 +140,7 @@ export class OcrController {
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
|
||||
logger.info('VIN extract requested', {
|
||||
operation: 'ocr.controller.extractVin',
|
||||
@@ -240,7 +240,7 @@ export class OcrController {
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
|
||||
logger.info('Receipt extract requested', {
|
||||
operation: 'ocr.controller.extractReceipt',
|
||||
@@ -352,7 +352,7 @@ export class OcrController {
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
|
||||
logger.info('Maintenance receipt extract requested', {
|
||||
operation: 'ocr.controller.extractMaintenanceReceipt',
|
||||
@@ -460,7 +460,7 @@ export class OcrController {
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
|
||||
logger.info('Manual extract requested', {
|
||||
operation: 'ocr.controller.extractManual',
|
||||
@@ -584,7 +584,7 @@ export class OcrController {
|
||||
request: FastifyRequest<{ Body: JobSubmitBody }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
|
||||
logger.info('OCR job submit requested', {
|
||||
operation: 'ocr.controller.submitJob',
|
||||
@@ -691,7 +691,7 @@ export class OcrController {
|
||||
request: FastifyRequest<{ Params: JobIdParams }>,
|
||||
reply: FastifyReply
|
||||
) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext?.userId as string;
|
||||
const { jobId } = request.params;
|
||||
|
||||
logger.debug('OCR job status requested', {
|
||||
|
||||
@@ -51,7 +51,7 @@ export class OnboardingController {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
logger.error('Error in savePreferences controller', {
|
||||
error,
|
||||
userId: (request as AuthenticatedRequest).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User profile not found') {
|
||||
@@ -86,7 +86,7 @@ export class OnboardingController {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
logger.error('Error in completeOnboarding controller', {
|
||||
error,
|
||||
userId: (request as AuthenticatedRequest).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User profile not found') {
|
||||
@@ -124,7 +124,7 @@ export class OnboardingController {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
logger.error('Error in getStatus controller', {
|
||||
error,
|
||||
userId: (request as AuthenticatedRequest).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
});
|
||||
|
||||
if (errorMessage === 'User profile not found') {
|
||||
|
||||
@@ -7,7 +7,7 @@ export class OwnershipCostsController {
|
||||
private readonly service = new OwnershipCostsService();
|
||||
|
||||
async list(request: FastifyRequest<{ Querystring: ListQuery }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Ownership costs list requested', {
|
||||
operation: 'ownership-costs.list',
|
||||
@@ -35,7 +35,7 @@ export class OwnershipCostsController {
|
||||
}
|
||||
|
||||
async get(request: FastifyRequest<{ Params: IdParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const costId = request.params.id;
|
||||
|
||||
logger.info('Ownership cost get requested', {
|
||||
@@ -66,7 +66,7 @@ export class OwnershipCostsController {
|
||||
}
|
||||
|
||||
async create(request: FastifyRequest<{ Body: CreateBody }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Ownership cost create requested', {
|
||||
operation: 'ownership-costs.create',
|
||||
@@ -91,7 +91,7 @@ export class OwnershipCostsController {
|
||||
}
|
||||
|
||||
async update(request: FastifyRequest<{ Params: IdParams; Body: UpdateBody }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const costId = request.params.id;
|
||||
|
||||
logger.info('Ownership cost update requested', {
|
||||
@@ -123,7 +123,7 @@ export class OwnershipCostsController {
|
||||
}
|
||||
|
||||
async remove(request: FastifyRequest<{ Params: IdParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub as string;
|
||||
const userId = request.userContext!.userId;
|
||||
const costId = request.params.id;
|
||||
|
||||
logger.info('Ownership cost delete requested', {
|
||||
|
||||
@@ -47,7 +47,7 @@ export class CommunityStationsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
// Validate request body
|
||||
const validation = submitCommunityStationSchema.safeParse(request.body);
|
||||
@@ -62,7 +62,7 @@ export class CommunityStationsController {
|
||||
|
||||
return reply.code(201).send(station);
|
||||
} catch (error: any) {
|
||||
logger.error('Error submitting station', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error submitting station', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to submit station'
|
||||
@@ -79,7 +79,7 @@ export class CommunityStationsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
// Validate query params
|
||||
const validation = paginationSchema.safeParse(request.query);
|
||||
@@ -94,7 +94,7 @@ export class CommunityStationsController {
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Error getting user submissions', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting user submissions', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to retrieve submissions'
|
||||
@@ -111,7 +111,7 @@ export class CommunityStationsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
// Validate params
|
||||
const validation = stationIdSchema.safeParse(request.params);
|
||||
@@ -128,7 +128,7 @@ export class CommunityStationsController {
|
||||
} catch (error: any) {
|
||||
logger.error('Error withdrawing submission', {
|
||||
error,
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
stationId: request.params.id
|
||||
});
|
||||
|
||||
@@ -252,7 +252,7 @@ export class CommunityStationsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
// Validate params
|
||||
const paramsValidation = stationIdSchema.safeParse(request.params);
|
||||
@@ -280,7 +280,7 @@ export class CommunityStationsController {
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Error reporting removal', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error reporting removal', { error, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
@@ -379,7 +379,7 @@ export class CommunityStationsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const adminId = (request as any).user.sub;
|
||||
const adminId = request.userContext!.userId;
|
||||
|
||||
// Validate params
|
||||
const paramsValidation = stationIdSchema.safeParse(request.params);
|
||||
@@ -422,7 +422,7 @@ export class CommunityStationsController {
|
||||
|
||||
return reply.code(200).send(station);
|
||||
} catch (error: any) {
|
||||
logger.error('Error reviewing station', { error, adminId: (request as any).user?.sub });
|
||||
logger.error('Error reviewing station', { error, adminId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
|
||||
@@ -27,7 +27,7 @@ export class StationsController {
|
||||
|
||||
async searchStations(request: FastifyRequest<{ Body: StationSearchBody }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { latitude, longitude, radius, fuelType } = request.body;
|
||||
|
||||
if (!latitude || !longitude) {
|
||||
@@ -46,7 +46,7 @@ export class StationsController {
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Error searching stations', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error searching stations', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to search stations'
|
||||
@@ -79,7 +79,7 @@ export class StationsController {
|
||||
|
||||
async saveStation(request: FastifyRequest<{ Body: SaveStationBody }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const {
|
||||
placeId,
|
||||
nickname,
|
||||
@@ -106,7 +106,7 @@ export class StationsController {
|
||||
|
||||
return reply.code(201).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Error saving station', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error saving station', { error, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
@@ -127,7 +127,7 @@ export class StationsController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { placeId } = request.params;
|
||||
|
||||
const result = await this.stationsService.updateSavedStation(placeId, userId, request.body);
|
||||
@@ -137,7 +137,7 @@ export class StationsController {
|
||||
logger.error('Error updating saved station', {
|
||||
error,
|
||||
placeId: request.params.placeId,
|
||||
userId: (request as any).user?.sub
|
||||
userId: request.userContext?.userId
|
||||
});
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
@@ -156,12 +156,12 @@ export class StationsController {
|
||||
|
||||
async getSavedStations(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const result = await this.stationsService.getUserSavedStations(userId);
|
||||
|
||||
return reply.code(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Error getting saved stations', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting saved stations', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to get saved stations'
|
||||
@@ -171,14 +171,14 @@ export class StationsController {
|
||||
|
||||
async removeSavedStation(request: FastifyRequest<{ Params: StationParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { placeId } = request.params;
|
||||
|
||||
await this.stationsService.removeSavedStation(placeId, userId);
|
||||
|
||||
return reply.code(204).send();
|
||||
} catch (error: any) {
|
||||
logger.error('Error removing saved station', { error, placeId: request.params.placeId, userId: (request as any).user?.sub });
|
||||
logger.error('Error removing saved station', { error, placeId: request.params.placeId, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message.includes('not found')) {
|
||||
return reply.code(404).send({
|
||||
|
||||
@@ -12,8 +12,8 @@ describe('Community Stations API Integration Tests', () => {
|
||||
let app: FastifyInstance;
|
||||
let pool: Pool;
|
||||
|
||||
const testUserId = 'auth0|test-user-123';
|
||||
const testAdminId = 'auth0|test-admin-123';
|
||||
const testUserId = '550e8400-e29b-41d4-a716-446655440000';
|
||||
const testAdminId = '7c9e6679-7425-40de-944b-e07fc1f90ae7';
|
||||
|
||||
const mockStationData = {
|
||||
name: 'Test Gas Station',
|
||||
|
||||
@@ -28,7 +28,7 @@ export class DonationsController {
|
||||
*/
|
||||
async createDonation(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { amount } = request.body as CreateDonationBody;
|
||||
|
||||
logger.info('Creating donation', { userId, amount });
|
||||
@@ -63,7 +63,7 @@ export class DonationsController {
|
||||
*/
|
||||
async getDonations(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('Getting donations', { userId });
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export class SubscriptionsController {
|
||||
*/
|
||||
async getSubscription(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
const subscription = await this.service.getSubscription(userId);
|
||||
|
||||
@@ -39,7 +39,7 @@ export class SubscriptionsController {
|
||||
reply.status(200).send(subscription);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get subscription', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -54,14 +54,14 @@ export class SubscriptionsController {
|
||||
*/
|
||||
async checkNeedsVehicleSelection(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
const result = await this.service.checkNeedsVehicleSelection(userId);
|
||||
|
||||
reply.status(200).send(result);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to check needs vehicle selection', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -85,8 +85,8 @@ export class SubscriptionsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const email = (request as any).user.email;
|
||||
const userId = request.userContext!.userId;
|
||||
const email = request.userContext!.email || '';
|
||||
const { tier, billingCycle, paymentMethodId } = request.body;
|
||||
|
||||
// Validate inputs
|
||||
@@ -141,7 +141,7 @@ export class SubscriptionsController {
|
||||
reply.status(200).send(updatedSubscription);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to create checkout', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -156,14 +156,14 @@ export class SubscriptionsController {
|
||||
*/
|
||||
async cancelSubscription(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
const subscription = await this.service.cancelSubscription(userId);
|
||||
|
||||
reply.status(200).send(subscription);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to cancel subscription', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -178,14 +178,14 @@ export class SubscriptionsController {
|
||||
*/
|
||||
async reactivateSubscription(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
const subscription = await this.service.reactivateSubscription(userId);
|
||||
|
||||
reply.status(200).send(subscription);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to reactivate subscription', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -207,8 +207,8 @@ export class SubscriptionsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const email = (request as any).user.email;
|
||||
const userId = request.userContext!.userId;
|
||||
const email = request.userContext!.email || '';
|
||||
const { paymentMethodId } = request.body;
|
||||
|
||||
// Validate input
|
||||
@@ -228,7 +228,7 @@ export class SubscriptionsController {
|
||||
});
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to update payment method', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -243,14 +243,14 @@ export class SubscriptionsController {
|
||||
*/
|
||||
async getInvoices(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
const invoices = await this.service.getInvoices(userId);
|
||||
|
||||
reply.status(200).send(invoices);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get invoices', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
@@ -273,7 +273,7 @@ export class SubscriptionsController {
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { targetTier, vehicleIdsToKeep } = request.body;
|
||||
|
||||
// Validate inputs
|
||||
@@ -311,7 +311,7 @@ export class SubscriptionsController {
|
||||
reply.status(200).send(updatedSubscription);
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to downgrade subscription', {
|
||||
userId: (request as any).user?.sub,
|
||||
userId: request.userContext?.userId,
|
||||
error: error.message,
|
||||
});
|
||||
reply.status(500).send({
|
||||
|
||||
@@ -782,7 +782,7 @@ export class SubscriptionsService {
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Get user profile for email and name
|
||||
const userProfile = await this.userProfileRepository.getByAuth0Sub(userId);
|
||||
const userProfile = await this.userProfileRepository.getById(userId);
|
||||
if (!userProfile) {
|
||||
logger.warn('User profile not found for tier change notification', { userId });
|
||||
return;
|
||||
@@ -931,7 +931,7 @@ export class SubscriptionsService {
|
||||
|
||||
// Sync tier to user_profiles table (within same transaction)
|
||||
await client.query(
|
||||
'UPDATE user_profiles SET subscription_tier = $1 WHERE auth0_sub = $2',
|
||||
'UPDATE user_profiles SET subscription_tier = $1 WHERE id = $2',
|
||||
[newTier, userId]
|
||||
);
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ export async function processGracePeriodExpirations(): Promise<GracePeriodResult
|
||||
up.notification_email,
|
||||
up.display_name
|
||||
FROM subscriptions s
|
||||
LEFT JOIN user_profiles up ON s.user_id = up.auth0_sub
|
||||
LEFT JOIN user_profiles up ON s.user_id = up.id
|
||||
WHERE s.status = 'past_due'
|
||||
AND s.grace_period_end < NOW()
|
||||
ORDER BY s.grace_period_end ASC
|
||||
@@ -89,13 +89,13 @@ export async function processGracePeriodExpirations(): Promise<GracePeriodResult
|
||||
|
||||
await client.query(updateQuery, [subscription.id]);
|
||||
|
||||
// Sync tier to user_profiles table (user_id is auth0_sub)
|
||||
// Sync tier to user_profiles table
|
||||
const syncQuery = `
|
||||
UPDATE user_profiles
|
||||
SET
|
||||
subscription_tier = 'free',
|
||||
updated_at = NOW()
|
||||
WHERE auth0_sub = $1
|
||||
WHERE id = $1
|
||||
`;
|
||||
|
||||
await client.query(syncQuery, [subscription.user_id]);
|
||||
|
||||
@@ -15,7 +15,7 @@ export class UserExportController {
|
||||
}
|
||||
|
||||
async downloadExport(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
|
||||
logger.info('User export requested', { userId });
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export class UserImportController {
|
||||
* Uploads and imports user data archive
|
||||
*/
|
||||
async uploadAndImport(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const userId = request.user?.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
if (!userId) {
|
||||
return reply.code(401).send({ error: 'Unauthorized' });
|
||||
}
|
||||
@@ -139,7 +139,7 @@ export class UserImportController {
|
||||
* Generates preview of import data without executing import
|
||||
*/
|
||||
async generatePreview(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const userId = request.user?.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
if (!userId) {
|
||||
return reply.code(401).send({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export class UserPreferencesController {
|
||||
|
||||
async getPreferences(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
let preferences = await this.repository.findByUserId(userId);
|
||||
|
||||
// Create default preferences if none exist
|
||||
@@ -42,7 +42,7 @@ export class UserPreferencesController {
|
||||
updatedAt: preferences.updatedAt,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error getting user preferences', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting user preferences', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to get preferences',
|
||||
@@ -55,7 +55,7 @@ export class UserPreferencesController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { unitSystem, currencyCode, timeZone, darkMode } = request.body;
|
||||
|
||||
// Validate unitSystem if provided
|
||||
@@ -115,7 +115,7 @@ export class UserPreferencesController {
|
||||
updatedAt: preferences.updatedAt,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error updating user preferences', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error updating user preferences', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to update preferences',
|
||||
|
||||
@@ -18,11 +18,12 @@ import {
|
||||
|
||||
export class UserProfileController {
|
||||
private userProfileService: UserProfileService;
|
||||
private userProfileRepository: UserProfileRepository;
|
||||
|
||||
constructor() {
|
||||
const repository = new UserProfileRepository(pool);
|
||||
this.userProfileRepository = new UserProfileRepository(pool);
|
||||
const adminRepository = new AdminRepository(pool);
|
||||
this.userProfileService = new UserProfileService(repository);
|
||||
this.userProfileService = new UserProfileService(this.userProfileRepository);
|
||||
this.userProfileService.setAdminRepository(adminRepository);
|
||||
}
|
||||
|
||||
@@ -31,27 +32,24 @@ export class UserProfileController {
|
||||
*/
|
||||
async getProfile(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const auth0Sub = request.userContext?.userId;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
if (!auth0Sub) {
|
||||
if (!userId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing',
|
||||
});
|
||||
}
|
||||
|
||||
// Get user data from Auth0 token
|
||||
const auth0User = {
|
||||
sub: auth0Sub,
|
||||
email: (request as any).user?.email || request.userContext?.email || '',
|
||||
name: (request as any).user?.name,
|
||||
};
|
||||
// Get profile by UUID (auth plugin ensures profile exists during authentication)
|
||||
const profile = await this.userProfileRepository.getById(userId);
|
||||
|
||||
// Get or create profile
|
||||
const profile = await this.userProfileService.getOrCreateProfile(
|
||||
auth0Sub,
|
||||
auth0User
|
||||
);
|
||||
if (!profile) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not Found',
|
||||
message: 'User profile not found',
|
||||
});
|
||||
}
|
||||
|
||||
return reply.code(200).send(profile);
|
||||
} catch (error: any) {
|
||||
@@ -75,9 +73,9 @@ export class UserProfileController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const auth0Sub = request.userContext?.userId;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
if (!auth0Sub) {
|
||||
if (!userId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing',
|
||||
@@ -96,9 +94,9 @@ export class UserProfileController {
|
||||
|
||||
const updates = validation.data;
|
||||
|
||||
// Update profile
|
||||
// Update profile by UUID
|
||||
const profile = await this.userProfileService.updateProfile(
|
||||
auth0Sub,
|
||||
userId,
|
||||
updates
|
||||
);
|
||||
|
||||
@@ -138,9 +136,9 @@ export class UserProfileController {
|
||||
reply: FastifyReply
|
||||
) {
|
||||
try {
|
||||
const auth0Sub = request.userContext?.userId;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
if (!auth0Sub) {
|
||||
if (!userId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing',
|
||||
@@ -159,9 +157,9 @@ export class UserProfileController {
|
||||
|
||||
const { confirmationText } = validation.data;
|
||||
|
||||
// Request deletion (user is already authenticated via JWT)
|
||||
// Request deletion by UUID
|
||||
const profile = await this.userProfileService.requestDeletion(
|
||||
auth0Sub,
|
||||
userId,
|
||||
confirmationText
|
||||
);
|
||||
|
||||
@@ -210,17 +208,17 @@ export class UserProfileController {
|
||||
*/
|
||||
async cancelDeletion(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const auth0Sub = request.userContext?.userId;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
if (!auth0Sub) {
|
||||
if (!userId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing',
|
||||
});
|
||||
}
|
||||
|
||||
// Cancel deletion
|
||||
const profile = await this.userProfileService.cancelDeletion(auth0Sub);
|
||||
// Cancel deletion by UUID
|
||||
const profile = await this.userProfileService.cancelDeletion(userId);
|
||||
|
||||
return reply.code(200).send({
|
||||
message: 'Account deletion canceled successfully',
|
||||
@@ -258,27 +256,24 @@ export class UserProfileController {
|
||||
*/
|
||||
async getDeletionStatus(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const auth0Sub = request.userContext?.userId;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
if (!auth0Sub) {
|
||||
if (!userId) {
|
||||
return reply.code(401).send({
|
||||
error: 'Unauthorized',
|
||||
message: 'User context missing',
|
||||
});
|
||||
}
|
||||
|
||||
// Get user data from Auth0 token
|
||||
const auth0User = {
|
||||
sub: auth0Sub,
|
||||
email: (request as any).user?.email || request.userContext?.email || '',
|
||||
name: (request as any).user?.name,
|
||||
};
|
||||
// Get profile by UUID (auth plugin ensures profile exists)
|
||||
const profile = await this.userProfileRepository.getById(userId);
|
||||
|
||||
// Get or create profile
|
||||
const profile = await this.userProfileService.getOrCreateProfile(
|
||||
auth0Sub,
|
||||
auth0User
|
||||
);
|
||||
if (!profile) {
|
||||
return reply.code(404).send({
|
||||
error: 'Not Found',
|
||||
message: 'User profile not found',
|
||||
});
|
||||
}
|
||||
|
||||
const deletionStatus = this.userProfileService.getDeletionStatus(profile);
|
||||
|
||||
|
||||
@@ -44,6 +44,26 @@ export class UserProfileRepository {
|
||||
}
|
||||
}
|
||||
|
||||
async getById(id: string): Promise<UserProfile | null> {
|
||||
const query = `
|
||||
SELECT ${USER_PROFILE_COLUMNS}
|
||||
FROM user_profiles
|
||||
WHERE id = $1
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [id]);
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching user profile by id', { error, id });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getByEmail(email: string): Promise<UserProfile | null> {
|
||||
const query = `
|
||||
SELECT ${USER_PROFILE_COLUMNS}
|
||||
@@ -94,7 +114,7 @@ export class UserProfileRepository {
|
||||
}
|
||||
|
||||
async update(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
updates: { displayName?: string; notificationEmail?: string }
|
||||
): Promise<UserProfile> {
|
||||
const setClauses: string[] = [];
|
||||
@@ -115,12 +135,12 @@ export class UserProfileRepository {
|
||||
throw new Error('No fields to update');
|
||||
}
|
||||
|
||||
values.push(auth0Sub);
|
||||
values.push(userId);
|
||||
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET ${setClauses.join(', ')}
|
||||
WHERE auth0_sub = $${paramIndex}
|
||||
WHERE id = $${paramIndex}
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
@@ -133,7 +153,7 @@ export class UserProfileRepository {
|
||||
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error updating user profile', { error, auth0Sub, updates });
|
||||
logger.error('Error updating user profile', { error, userId, updates });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -174,7 +194,7 @@ export class UserProfileRepository {
|
||||
private mapRowToUserWithAdminStatus(row: any): UserWithAdminStatus {
|
||||
return {
|
||||
...this.mapRowToUserProfile(row),
|
||||
isAdmin: !!row.admin_auth0_sub,
|
||||
isAdmin: !!row.admin_id,
|
||||
adminRole: row.admin_role || null,
|
||||
vehicleCount: parseInt(row.vehicle_count, 10) || 0,
|
||||
};
|
||||
@@ -242,14 +262,14 @@ export class UserProfileRepository {
|
||||
up.id, up.auth0_sub, up.email, up.display_name, up.notification_email,
|
||||
up.subscription_tier, up.email_verified, up.onboarding_completed_at,
|
||||
up.deactivated_at, up.deactivated_by, up.created_at, up.updated_at,
|
||||
au.auth0_sub as admin_auth0_sub,
|
||||
au.id as admin_id,
|
||||
au.role as admin_role,
|
||||
(SELECT COUNT(*) FROM vehicles v
|
||||
WHERE v.user_id = up.auth0_sub
|
||||
WHERE v.user_id = up.id
|
||||
AND v.is_active = true
|
||||
AND v.deleted_at IS NULL) as vehicle_count
|
||||
FROM user_profiles up
|
||||
LEFT JOIN admin_users au ON up.auth0_sub = au.auth0_sub AND au.revoked_at IS NULL
|
||||
LEFT JOIN admin_users au ON au.user_profile_id = up.id AND au.revoked_at IS NULL
|
||||
${whereClause}
|
||||
ORDER BY ${sortColumn} ${sortOrder === 'desc' ? 'DESC' : 'ASC'} NULLS LAST
|
||||
LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
|
||||
@@ -274,32 +294,32 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Get single user with admin status
|
||||
*/
|
||||
async getUserWithAdminStatus(auth0Sub: string): Promise<UserWithAdminStatus | null> {
|
||||
async getUserWithAdminStatus(userId: string): Promise<UserWithAdminStatus | null> {
|
||||
const query = `
|
||||
SELECT
|
||||
up.id, up.auth0_sub, up.email, up.display_name, up.notification_email,
|
||||
up.subscription_tier, up.email_verified, up.onboarding_completed_at,
|
||||
up.deactivated_at, up.deactivated_by, up.created_at, up.updated_at,
|
||||
au.auth0_sub as admin_auth0_sub,
|
||||
au.id as admin_id,
|
||||
au.role as admin_role,
|
||||
(SELECT COUNT(*) FROM vehicles v
|
||||
WHERE v.user_id = up.auth0_sub
|
||||
WHERE v.user_id = up.id
|
||||
AND v.is_active = true
|
||||
AND v.deleted_at IS NULL) as vehicle_count
|
||||
FROM user_profiles up
|
||||
LEFT JOIN admin_users au ON up.auth0_sub = au.auth0_sub AND au.revoked_at IS NULL
|
||||
WHERE up.auth0_sub = $1
|
||||
LEFT JOIN admin_users au ON au.user_profile_id = up.id AND au.revoked_at IS NULL
|
||||
WHERE up.id = $1
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [userId]);
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.mapRowToUserWithAdminStatus(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching user with admin status', { error, auth0Sub });
|
||||
logger.error('Error fetching user with admin status', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -308,24 +328,24 @@ export class UserProfileRepository {
|
||||
* Update user subscription tier
|
||||
*/
|
||||
async updateSubscriptionTier(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
tier: SubscriptionTier
|
||||
): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET subscription_tier = $1
|
||||
WHERE auth0_sub = $2
|
||||
WHERE id = $2
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [tier, auth0Sub]);
|
||||
const result = await this.pool.query(query, [tier, userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error updating subscription tier', { error, auth0Sub, tier });
|
||||
logger.error('Error updating subscription tier', { error, userId, tier });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -333,22 +353,22 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Deactivate user (soft delete)
|
||||
*/
|
||||
async deactivateUser(auth0Sub: string, deactivatedBy: string): Promise<UserProfile> {
|
||||
async deactivateUser(userId: string, deactivatedBy: string): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET deactivated_at = NOW(), deactivated_by = $1
|
||||
WHERE auth0_sub = $2 AND deactivated_at IS NULL
|
||||
WHERE id = $2 AND deactivated_at IS NULL
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [deactivatedBy, auth0Sub]);
|
||||
const result = await this.pool.query(query, [deactivatedBy, userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found or already deactivated');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error deactivating user', { error, auth0Sub, deactivatedBy });
|
||||
logger.error('Error deactivating user', { error, userId, deactivatedBy });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -356,22 +376,22 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Reactivate user
|
||||
*/
|
||||
async reactivateUser(auth0Sub: string): Promise<UserProfile> {
|
||||
async reactivateUser(userId: string): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET deactivated_at = NULL, deactivated_by = NULL
|
||||
WHERE auth0_sub = $1 AND deactivated_at IS NOT NULL
|
||||
WHERE id = $1 AND deactivated_at IS NOT NULL
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found or not deactivated');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error reactivating user', { error, auth0Sub });
|
||||
logger.error('Error reactivating user', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -380,7 +400,7 @@ export class UserProfileRepository {
|
||||
* Admin update of user profile (can update email and displayName)
|
||||
*/
|
||||
async adminUpdateProfile(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
updates: { email?: string; displayName?: string }
|
||||
): Promise<UserProfile> {
|
||||
const setClauses: string[] = [];
|
||||
@@ -401,12 +421,12 @@ export class UserProfileRepository {
|
||||
throw new Error('No fields to update');
|
||||
}
|
||||
|
||||
values.push(auth0Sub);
|
||||
values.push(userId);
|
||||
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET ${setClauses.join(', ')}, updated_at = NOW()
|
||||
WHERE auth0_sub = $${paramIndex}
|
||||
WHERE id = $${paramIndex}
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
@@ -419,7 +439,7 @@ export class UserProfileRepository {
|
||||
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error admin updating user profile', { error, auth0Sub, updates });
|
||||
logger.error('Error admin updating user profile', { error, userId, updates });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -427,22 +447,22 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Update email verification status
|
||||
*/
|
||||
async updateEmailVerified(auth0Sub: string, emailVerified: boolean): Promise<UserProfile> {
|
||||
async updateEmailVerified(userId: string, emailVerified: boolean): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET email_verified = $1, updated_at = NOW()
|
||||
WHERE auth0_sub = $2
|
||||
WHERE id = $2
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [emailVerified, auth0Sub]);
|
||||
const result = await this.pool.query(query, [emailVerified, userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error updating email verified status', { error, auth0Sub, emailVerified });
|
||||
logger.error('Error updating email verified status', { error, userId, emailVerified });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -450,19 +470,19 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Mark onboarding as complete
|
||||
*/
|
||||
async markOnboardingComplete(auth0Sub: string): Promise<UserProfile> {
|
||||
async markOnboardingComplete(userId: string): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET onboarding_completed_at = NOW(), updated_at = NOW()
|
||||
WHERE auth0_sub = $1 AND onboarding_completed_at IS NULL
|
||||
WHERE id = $1 AND onboarding_completed_at IS NULL
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [userId]);
|
||||
if (result.rows.length === 0) {
|
||||
// Check if already completed or profile not found
|
||||
const existing = await this.getByAuth0Sub(auth0Sub);
|
||||
const existing = await this.getById(userId);
|
||||
if (existing && existing.onboardingCompletedAt) {
|
||||
return existing; // Already completed, return as-is
|
||||
}
|
||||
@@ -470,7 +490,7 @@ export class UserProfileRepository {
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error marking onboarding complete', { error, auth0Sub });
|
||||
logger.error('Error marking onboarding complete', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -478,22 +498,22 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Update user email (used when fetching correct email from Auth0)
|
||||
*/
|
||||
async updateEmail(auth0Sub: string, email: string): Promise<UserProfile> {
|
||||
async updateEmail(userId: string, email: string): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET email = $1, updated_at = NOW()
|
||||
WHERE auth0_sub = $2
|
||||
WHERE id = $2
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [email, auth0Sub]);
|
||||
const result = await this.pool.query(query, [email, userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error updating user email', { error, auth0Sub });
|
||||
logger.error('Error updating user email', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -502,7 +522,7 @@ export class UserProfileRepository {
|
||||
* Request account deletion (sets deletion timestamps and deactivates account)
|
||||
* 30-day grace period before permanent deletion
|
||||
*/
|
||||
async requestDeletion(auth0Sub: string): Promise<UserProfile> {
|
||||
async requestDeletion(userId: string): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET
|
||||
@@ -510,18 +530,18 @@ export class UserProfileRepository {
|
||||
deletion_scheduled_for = NOW() + INTERVAL '30 days',
|
||||
deactivated_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE auth0_sub = $1 AND deletion_requested_at IS NULL
|
||||
WHERE id = $1 AND deletion_requested_at IS NULL
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found or deletion already requested');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error requesting account deletion', { error, auth0Sub });
|
||||
logger.error('Error requesting account deletion', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -529,7 +549,7 @@ export class UserProfileRepository {
|
||||
/**
|
||||
* Cancel deletion request (clears deletion timestamps and reactivates account)
|
||||
*/
|
||||
async cancelDeletion(auth0Sub: string): Promise<UserProfile> {
|
||||
async cancelDeletion(userId: string): Promise<UserProfile> {
|
||||
const query = `
|
||||
UPDATE user_profiles
|
||||
SET
|
||||
@@ -538,18 +558,18 @@ export class UserProfileRepository {
|
||||
deactivated_at = NULL,
|
||||
deactivated_by = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE auth0_sub = $1 AND deletion_requested_at IS NOT NULL
|
||||
WHERE id = $1 AND deletion_requested_at IS NOT NULL
|
||||
RETURNING ${USER_PROFILE_COLUMNS}
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [userId]);
|
||||
if (result.rows.length === 0) {
|
||||
throw new Error('User profile not found or no deletion request pending');
|
||||
}
|
||||
return this.mapRowToUserProfile(result.rows[0]);
|
||||
} catch (error) {
|
||||
logger.error('Error canceling account deletion', { error, auth0Sub });
|
||||
logger.error('Error canceling account deletion', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -579,7 +599,7 @@ export class UserProfileRepository {
|
||||
* Hard delete user and all associated data
|
||||
* This is a permanent operation - use with caution
|
||||
*/
|
||||
async hardDeleteUser(auth0Sub: string): Promise<void> {
|
||||
async hardDeleteUser(userId: string): Promise<void> {
|
||||
const client = await this.pool.connect();
|
||||
|
||||
try {
|
||||
@@ -590,51 +610,51 @@ export class UserProfileRepository {
|
||||
`UPDATE community_stations
|
||||
SET submitted_by = 'deleted-user'
|
||||
WHERE submitted_by = $1`,
|
||||
[auth0Sub]
|
||||
[userId]
|
||||
);
|
||||
|
||||
// 2. Delete notification logs
|
||||
await client.query(
|
||||
'DELETE FROM notification_logs WHERE user_id = $1',
|
||||
[auth0Sub]
|
||||
[userId]
|
||||
);
|
||||
|
||||
// 3. Delete user notifications
|
||||
await client.query(
|
||||
'DELETE FROM user_notifications WHERE user_id = $1',
|
||||
[auth0Sub]
|
||||
[userId]
|
||||
);
|
||||
|
||||
// 4. Delete saved stations
|
||||
await client.query(
|
||||
'DELETE FROM saved_stations WHERE user_id = $1',
|
||||
[auth0Sub]
|
||||
[userId]
|
||||
);
|
||||
|
||||
// 5. Delete vehicles (cascades to fuel_logs, maintenance_logs, maintenance_schedules, documents)
|
||||
await client.query(
|
||||
'DELETE FROM vehicles WHERE user_id = $1',
|
||||
[auth0Sub]
|
||||
[userId]
|
||||
);
|
||||
|
||||
// 6. Delete user preferences
|
||||
await client.query(
|
||||
'DELETE FROM user_preferences WHERE user_id = $1',
|
||||
[auth0Sub]
|
||||
[userId]
|
||||
);
|
||||
|
||||
// 7. Delete user profile (final step)
|
||||
await client.query(
|
||||
'DELETE FROM user_profiles WHERE auth0_sub = $1',
|
||||
[auth0Sub]
|
||||
'DELETE FROM user_profiles WHERE id = $1',
|
||||
[userId]
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
logger.info('User hard deleted successfully', { auth0Sub });
|
||||
logger.info('User hard deleted successfully', { userId });
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
logger.error('Error hard deleting user', { error, auth0Sub });
|
||||
logger.error('Error hard deleting user', { error, userId });
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
@@ -686,7 +706,7 @@ export class UserProfileRepository {
|
||||
* Get vehicles for a user (admin view)
|
||||
* Returns only year, make, model for privacy
|
||||
*/
|
||||
async getUserVehiclesForAdmin(auth0Sub: string): Promise<Array<{ year: number; make: string; model: string }>> {
|
||||
async getUserVehiclesForAdmin(userId: string): Promise<Array<{ year: number; make: string; model: string }>> {
|
||||
const query = `
|
||||
SELECT year, make, model
|
||||
FROM vehicles
|
||||
@@ -697,14 +717,14 @@ export class UserProfileRepository {
|
||||
`;
|
||||
|
||||
try {
|
||||
const result = await this.pool.query(query, [auth0Sub]);
|
||||
const result = await this.pool.query(query, [userId]);
|
||||
return result.rows.map(row => ({
|
||||
year: row.year,
|
||||
make: row.make,
|
||||
model: row.model,
|
||||
}));
|
||||
} catch (error) {
|
||||
logger.error('Error getting user vehicles for admin', { error, auth0Sub });
|
||||
logger.error('Error getting user vehicles for admin', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user profile by Auth0 sub
|
||||
* Get user profile by Auth0 sub (used during auth flow)
|
||||
*/
|
||||
async getProfile(auth0Sub: string): Promise<UserProfile | null> {
|
||||
try {
|
||||
@@ -72,10 +72,10 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user profile
|
||||
* Update user profile by UUID
|
||||
*/
|
||||
async updateProfile(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
updates: UpdateProfileRequest
|
||||
): Promise<UserProfile> {
|
||||
try {
|
||||
@@ -85,17 +85,17 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
// Perform the update
|
||||
const profile = await this.repository.update(auth0Sub, updates);
|
||||
const profile = await this.repository.update(userId, updates);
|
||||
|
||||
logger.info('User profile updated', {
|
||||
auth0Sub,
|
||||
userId,
|
||||
profileId: profile.id,
|
||||
updatedFields: Object.keys(updates),
|
||||
});
|
||||
|
||||
return profile;
|
||||
} catch (error) {
|
||||
logger.error('Error updating user profile', { error, auth0Sub, updates });
|
||||
logger.error('Error updating user profile', { error, userId, updates });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -117,29 +117,29 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user details with admin status (admin-only)
|
||||
* Get user details with admin status by UUID (admin-only)
|
||||
*/
|
||||
async getUserDetails(auth0Sub: string): Promise<UserWithAdminStatus | null> {
|
||||
async getUserDetails(userId: string): Promise<UserWithAdminStatus | null> {
|
||||
try {
|
||||
return await this.repository.getUserWithAdminStatus(auth0Sub);
|
||||
return await this.repository.getUserWithAdminStatus(userId);
|
||||
} catch (error) {
|
||||
logger.error('Error getting user details', { error, auth0Sub });
|
||||
logger.error('Error getting user details', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user subscription tier (admin-only)
|
||||
* Update user subscription tier by UUID (admin-only)
|
||||
* Logs the change to admin audit logs
|
||||
*/
|
||||
async updateSubscriptionTier(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
tier: SubscriptionTier,
|
||||
actorAuth0Sub: string
|
||||
actorUserId: string
|
||||
): Promise<UserProfile> {
|
||||
try {
|
||||
// Get current user to log the change
|
||||
const currentUser = await this.repository.getByAuth0Sub(auth0Sub);
|
||||
const currentUser = await this.repository.getById(userId);
|
||||
if (!currentUser) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
@@ -147,14 +147,14 @@ export class UserProfileService {
|
||||
const previousTier = currentUser.subscriptionTier;
|
||||
|
||||
// Perform the update
|
||||
const updatedProfile = await this.repository.updateSubscriptionTier(auth0Sub, tier);
|
||||
const updatedProfile = await this.repository.updateSubscriptionTier(userId, tier);
|
||||
|
||||
// Log to audit trail
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
'UPDATE_TIER',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
updatedProfile.id,
|
||||
{ previousTier, newTier: tier }
|
||||
@@ -162,36 +162,36 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
logger.info('User subscription tier updated', {
|
||||
auth0Sub,
|
||||
userId,
|
||||
previousTier,
|
||||
newTier: tier,
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
});
|
||||
|
||||
return updatedProfile;
|
||||
} catch (error) {
|
||||
logger.error('Error updating subscription tier', { error, auth0Sub, tier, actorAuth0Sub });
|
||||
logger.error('Error updating subscription tier', { error, userId, tier, actorUserId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivate user account (admin-only soft delete)
|
||||
* Deactivate user account by UUID (admin-only soft delete)
|
||||
* Prevents self-deactivation
|
||||
*/
|
||||
async deactivateUser(
|
||||
auth0Sub: string,
|
||||
actorAuth0Sub: string,
|
||||
userId: string,
|
||||
actorUserId: string,
|
||||
reason?: string
|
||||
): Promise<UserProfile> {
|
||||
try {
|
||||
// Prevent self-deactivation
|
||||
if (auth0Sub === actorAuth0Sub) {
|
||||
if (userId === actorUserId) {
|
||||
throw new Error('Cannot deactivate your own account');
|
||||
}
|
||||
|
||||
// Verify user exists and is not already deactivated
|
||||
const currentUser = await this.repository.getByAuth0Sub(auth0Sub);
|
||||
const currentUser = await this.repository.getById(userId);
|
||||
if (!currentUser) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
@@ -200,14 +200,14 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
// Perform the deactivation
|
||||
const deactivatedProfile = await this.repository.deactivateUser(auth0Sub, actorAuth0Sub);
|
||||
const deactivatedProfile = await this.repository.deactivateUser(userId, actorUserId);
|
||||
|
||||
// Log to audit trail
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
'DEACTIVATE_USER',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
deactivatedProfile.id,
|
||||
{ reason: reason || 'No reason provided' }
|
||||
@@ -215,28 +215,28 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
logger.info('User deactivated', {
|
||||
auth0Sub,
|
||||
actorAuth0Sub,
|
||||
userId,
|
||||
actorUserId,
|
||||
reason,
|
||||
});
|
||||
|
||||
return deactivatedProfile;
|
||||
} catch (error) {
|
||||
logger.error('Error deactivating user', { error, auth0Sub, actorAuth0Sub });
|
||||
logger.error('Error deactivating user', { error, userId, actorUserId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactivate a deactivated user account (admin-only)
|
||||
* Reactivate a deactivated user account by UUID (admin-only)
|
||||
*/
|
||||
async reactivateUser(
|
||||
auth0Sub: string,
|
||||
actorAuth0Sub: string
|
||||
userId: string,
|
||||
actorUserId: string
|
||||
): Promise<UserProfile> {
|
||||
try {
|
||||
// Verify user exists and is deactivated
|
||||
const currentUser = await this.repository.getByAuth0Sub(auth0Sub);
|
||||
const currentUser = await this.repository.getById(userId);
|
||||
if (!currentUser) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
@@ -245,14 +245,14 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
// Perform the reactivation
|
||||
const reactivatedProfile = await this.repository.reactivateUser(auth0Sub);
|
||||
const reactivatedProfile = await this.repository.reactivateUser(userId);
|
||||
|
||||
// Log to audit trail
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
'REACTIVATE_USER',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
reactivatedProfile.id,
|
||||
{ previouslyDeactivatedBy: currentUser.deactivatedBy }
|
||||
@@ -260,29 +260,29 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
logger.info('User reactivated', {
|
||||
auth0Sub,
|
||||
actorAuth0Sub,
|
||||
userId,
|
||||
actorUserId,
|
||||
});
|
||||
|
||||
return reactivatedProfile;
|
||||
} catch (error) {
|
||||
logger.error('Error reactivating user', { error, auth0Sub, actorAuth0Sub });
|
||||
logger.error('Error reactivating user', { error, userId, actorUserId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin update of user profile (email, displayName)
|
||||
* Admin update of user profile by UUID (email, displayName)
|
||||
* Logs the change to admin audit logs
|
||||
*/
|
||||
async adminUpdateProfile(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
updates: { email?: string; displayName?: string },
|
||||
actorAuth0Sub: string
|
||||
actorUserId: string
|
||||
): Promise<UserProfile> {
|
||||
try {
|
||||
// Get current user to log the change
|
||||
const currentUser = await this.repository.getByAuth0Sub(auth0Sub);
|
||||
const currentUser = await this.repository.getById(userId);
|
||||
if (!currentUser) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
@@ -293,14 +293,14 @@ export class UserProfileService {
|
||||
};
|
||||
|
||||
// Perform the update
|
||||
const updatedProfile = await this.repository.adminUpdateProfile(auth0Sub, updates);
|
||||
const updatedProfile = await this.repository.adminUpdateProfile(userId, updates);
|
||||
|
||||
// Log to audit trail
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
'UPDATE_PROFILE',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
updatedProfile.id,
|
||||
{
|
||||
@@ -311,14 +311,14 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
logger.info('User profile updated by admin', {
|
||||
auth0Sub,
|
||||
userId,
|
||||
updatedFields: Object.keys(updates),
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
});
|
||||
|
||||
return updatedProfile;
|
||||
} catch (error) {
|
||||
logger.error('Error admin updating user profile', { error, auth0Sub, updates, actorAuth0Sub });
|
||||
logger.error('Error admin updating user profile', { error, userId, updates, actorUserId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -328,12 +328,12 @@ export class UserProfileService {
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Request account deletion
|
||||
* Request account deletion by UUID
|
||||
* Sets 30-day grace period before permanent deletion
|
||||
* Note: User is already authenticated via JWT, confirmation text is sufficient
|
||||
*/
|
||||
async requestDeletion(
|
||||
auth0Sub: string,
|
||||
userId: string,
|
||||
confirmationText: string
|
||||
): Promise<UserProfile> {
|
||||
try {
|
||||
@@ -343,7 +343,7 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
// Get user profile
|
||||
const profile = await this.repository.getByAuth0Sub(auth0Sub);
|
||||
const profile = await this.repository.getById(userId);
|
||||
if (!profile) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
@@ -354,14 +354,14 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
// Request deletion
|
||||
const updatedProfile = await this.repository.requestDeletion(auth0Sub);
|
||||
const updatedProfile = await this.repository.requestDeletion(userId);
|
||||
|
||||
// Log to audit trail
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
auth0Sub,
|
||||
userId,
|
||||
'REQUEST_DELETION',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
updatedProfile.id,
|
||||
{
|
||||
@@ -371,42 +371,42 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
logger.info('Account deletion requested', {
|
||||
auth0Sub,
|
||||
userId,
|
||||
deletionScheduledFor: updatedProfile.deletionScheduledFor,
|
||||
});
|
||||
|
||||
return updatedProfile;
|
||||
} catch (error) {
|
||||
logger.error('Error requesting account deletion', { error, auth0Sub });
|
||||
logger.error('Error requesting account deletion', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel pending deletion request
|
||||
* Cancel pending deletion request by UUID
|
||||
*/
|
||||
async cancelDeletion(auth0Sub: string): Promise<UserProfile> {
|
||||
async cancelDeletion(userId: string): Promise<UserProfile> {
|
||||
try {
|
||||
// Cancel deletion
|
||||
const updatedProfile = await this.repository.cancelDeletion(auth0Sub);
|
||||
const updatedProfile = await this.repository.cancelDeletion(userId);
|
||||
|
||||
// Log to audit trail
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
auth0Sub,
|
||||
userId,
|
||||
'CANCEL_DELETION',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
updatedProfile.id,
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
logger.info('Account deletion canceled', { auth0Sub });
|
||||
logger.info('Account deletion canceled', { userId });
|
||||
|
||||
return updatedProfile;
|
||||
} catch (error) {
|
||||
logger.error('Error canceling account deletion', { error, auth0Sub });
|
||||
logger.error('Error canceling account deletion', { error, userId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -438,22 +438,22 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin hard delete user (permanent deletion)
|
||||
* Admin hard delete user by UUID (permanent deletion)
|
||||
* Prevents self-delete
|
||||
*/
|
||||
async adminHardDeleteUser(
|
||||
auth0Sub: string,
|
||||
actorAuth0Sub: string,
|
||||
userId: string,
|
||||
actorUserId: string,
|
||||
reason?: string
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Prevent self-delete
|
||||
if (auth0Sub === actorAuth0Sub) {
|
||||
if (userId === actorUserId) {
|
||||
throw new Error('Cannot delete your own account');
|
||||
}
|
||||
|
||||
// Get user profile before deletion for audit log
|
||||
const profile = await this.repository.getByAuth0Sub(auth0Sub);
|
||||
const profile = await this.repository.getById(userId);
|
||||
if (!profile) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
@@ -461,9 +461,9 @@ export class UserProfileService {
|
||||
// Log to audit trail before deletion
|
||||
if (this.adminRepository) {
|
||||
await this.adminRepository.logAuditAction(
|
||||
actorAuth0Sub,
|
||||
actorUserId,
|
||||
'HARD_DELETE_USER',
|
||||
auth0Sub,
|
||||
userId,
|
||||
'user_profile',
|
||||
profile.id,
|
||||
{
|
||||
@@ -475,18 +475,20 @@ export class UserProfileService {
|
||||
}
|
||||
|
||||
// Hard delete from database
|
||||
await this.repository.hardDeleteUser(auth0Sub);
|
||||
await this.repository.hardDeleteUser(userId);
|
||||
|
||||
// Delete from Auth0
|
||||
await auth0ManagementClient.deleteUser(auth0Sub);
|
||||
// Delete from Auth0 (using auth0Sub for Auth0 API)
|
||||
if (profile.auth0Sub) {
|
||||
await auth0ManagementClient.deleteUser(profile.auth0Sub);
|
||||
}
|
||||
|
||||
logger.info('User hard deleted by admin', {
|
||||
auth0Sub,
|
||||
actorAuth0Sub,
|
||||
userId,
|
||||
actorUserId,
|
||||
reason,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error hard deleting user', { error, auth0Sub, actorAuth0Sub });
|
||||
logger.error('Error hard deleting user', { error, userId, actorUserId });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export class VehiclesController {
|
||||
|
||||
async getUserVehicles(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
// Use tier-aware method to filter out locked vehicles after downgrade
|
||||
const vehiclesWithStatus = await this.vehiclesService.getUserVehiclesWithTierStatus(userId);
|
||||
// Only return active vehicles (filter out locked ones)
|
||||
@@ -37,7 +37,7 @@ export class VehiclesController {
|
||||
|
||||
return reply.code(200).send(vehicles);
|
||||
} catch (error) {
|
||||
logger.error('Error getting user vehicles', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting user vehicles', { error, userId: request.userContext?.userId });
|
||||
return reply.code(500).send({
|
||||
error: 'Internal server error',
|
||||
message: 'Failed to get vehicles'
|
||||
@@ -65,12 +65,12 @@ export class VehiclesController {
|
||||
}
|
||||
}
|
||||
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicle = await this.vehiclesService.createVehicle(request.body, userId);
|
||||
|
||||
return reply.code(201).send(vehicle);
|
||||
} catch (error: any) {
|
||||
logger.error('Error creating vehicle', { error, userId: (request as any).user?.sub });
|
||||
logger.error('Error creating vehicle', { error, userId: request.userContext?.userId });
|
||||
|
||||
if (error instanceof VehicleLimitExceededError) {
|
||||
return reply.code(403).send({
|
||||
@@ -110,7 +110,7 @@ export class VehiclesController {
|
||||
|
||||
async getVehicle(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
// Check tier status - block access to locked vehicles
|
||||
@@ -131,7 +131,7 @@ export class VehiclesController {
|
||||
|
||||
return reply.code(200).send(vehicle);
|
||||
} catch (error: any) {
|
||||
logger.error('Error getting vehicle', { error, vehicleId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting vehicle', { error, vehicleId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message === 'Vehicle not found' || error.message === 'Unauthorized') {
|
||||
return reply.code(404).send({
|
||||
@@ -149,14 +149,14 @@ export class VehiclesController {
|
||||
|
||||
async updateVehicle(request: FastifyRequest<{ Params: VehicleParams; Body: UpdateVehicleBody }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
const vehicle = await this.vehiclesService.updateVehicle(id, request.body, userId);
|
||||
|
||||
return reply.code(200).send(vehicle);
|
||||
} catch (error: any) {
|
||||
logger.error('Error updating vehicle', { error, vehicleId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error updating vehicle', { error, vehicleId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message === 'Vehicle not found' || error.message === 'Unauthorized') {
|
||||
return reply.code(404).send({
|
||||
@@ -183,14 +183,14 @@ export class VehiclesController {
|
||||
|
||||
async deleteVehicle(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
await this.vehiclesService.deleteVehicle(id, userId);
|
||||
|
||||
return reply.code(204).send();
|
||||
} catch (error: any) {
|
||||
logger.error('Error deleting vehicle', { error, vehicleId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error deleting vehicle', { error, vehicleId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.message === 'Vehicle not found' || error.message === 'Unauthorized') {
|
||||
return reply.code(404).send({
|
||||
@@ -208,13 +208,13 @@ export class VehiclesController {
|
||||
|
||||
async getTCO(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
try {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const { id } = request.params;
|
||||
|
||||
const tco = await this.vehiclesService.getTCO(id, userId);
|
||||
return reply.code(200).send(tco);
|
||||
} catch (error: any) {
|
||||
logger.error('Error getting vehicle TCO', { error, vehicleId: request.params.id, userId: (request as any).user?.sub });
|
||||
logger.error('Error getting vehicle TCO', { error, vehicleId: request.params.id, userId: request.userContext?.userId });
|
||||
|
||||
if (error.statusCode === 404 || error.message === 'Vehicle not found') {
|
||||
return reply.code(404).send({
|
||||
@@ -383,7 +383,7 @@ export class VehiclesController {
|
||||
* Requires Pro or Enterprise tier
|
||||
*/
|
||||
async decodeVin(request: FastifyRequest<{ Body: DecodeVinRequest }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user?.sub;
|
||||
const userId = request.userContext?.userId;
|
||||
|
||||
try {
|
||||
const { vin } = request.body;
|
||||
@@ -447,7 +447,7 @@ export class VehiclesController {
|
||||
}
|
||||
|
||||
async uploadImage(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.id;
|
||||
|
||||
logger.info('Vehicle image upload requested', {
|
||||
@@ -604,7 +604,7 @@ export class VehiclesController {
|
||||
}
|
||||
|
||||
async downloadImage(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.id;
|
||||
|
||||
logger.info('Vehicle image download requested', {
|
||||
@@ -654,7 +654,7 @@ export class VehiclesController {
|
||||
}
|
||||
|
||||
async deleteImage(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
|
||||
const userId = (request as any).user.sub;
|
||||
const userId = request.userContext!.userId;
|
||||
const vehicleId = request.params.id;
|
||||
|
||||
logger.info('Vehicle image delete requested', {
|
||||
|
||||
@@ -82,7 +82,7 @@ export class VehiclesService {
|
||||
}
|
||||
|
||||
// Get user's tier for limit enforcement
|
||||
const userProfile = await this.userProfileRepository.getByAuth0Sub(userId);
|
||||
const userProfile = await this.userProfileRepository.getById(userId);
|
||||
if (!userProfile) {
|
||||
throw new Error('User profile not found');
|
||||
}
|
||||
@@ -227,7 +227,7 @@ export class VehiclesService {
|
||||
*/
|
||||
async getUserVehiclesWithTierStatus(userId: string): Promise<Array<VehicleResponse & { tierStatus: 'active' | 'locked' }>> {
|
||||
// Get user's subscription tier
|
||||
const userProfile = await this.userProfileRepository.getByAuth0Sub(userId);
|
||||
const userProfile = await this.userProfileRepository.getById(userId);
|
||||
if (!userProfile) {
|
||||
throw new Error('User profile not found');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user