postiz-app/libraries/nestjs-libraries/src/sentry/sentry.user.context.ts
copilot-swe-agent[bot] b5bbf878a2 Use null instead of empty strings to clear Sentry tags
Co-authored-by: egelhaus <156946629+egelhaus@users.noreply.github.com>
2025-11-24 21:46:37 +00:00

63 lines
1.8 KiB
TypeScript

import * as Sentry from '@sentry/nestjs';
import { User } from '@prisma/client';
/**
* Sets user context for Sentry for the current request.
* This will include user information in all error reports and events.
* Only executes if Sentry DSN is configured.
*
* @param user - The user object from the database
*/
export const setSentryUserContext = (user: User | null) => {
// Only set context if Sentry is configured
if (!process.env.NEXT_PUBLIC_SENTRY_DSN) {
return;
}
try {
if (!user) {
// Clear user context when no user is present
Sentry.setUser(null);
return;
}
Sentry.setUser({
id: user.id,
email: user.email,
username: user.email, // Use email as username since that's the primary identifier
// Add additional useful context
ip_address: undefined, // Let Sentry auto-detect IP
});
// Also set additional tags for better filtering in Sentry
Sentry.setTag('user.activated', user.activated);
Sentry.setTag('user.provider', user.providerName || 'local');
if (user.isSuperAdmin) {
Sentry.setTag('user.super_admin', true);
}
} catch {
// Silently fail if Sentry throws an error - we don't want to break the app
}
};
/**
* Clears the Sentry user context.
* Useful when logging out or switching users.
* Only executes if Sentry DSN is configured.
*/
export const clearSentryUserContext = () => {
// Only clear context if Sentry is configured
if (!process.env.NEXT_PUBLIC_SENTRY_DSN) {
return;
}
try {
Sentry.setUser(null);
Sentry.setTag('user.activated', null);
Sentry.setTag('user.provider', null);
Sentry.setTag('user.super_admin', null);
} catch {
// Silently fail if Sentry throws an error - we don't want to break the app
}
};