Fix jwt-token

This commit is contained in:
2025-09-14 09:48:51 +02:00
parent cfa1af0fd0
commit 674c2e2d8f
3 changed files with 30 additions and 15 deletions

View File

@@ -1,5 +1,5 @@
const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { User, Tenant } = require('../models');
async function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
@@ -24,8 +24,16 @@ async function authenticateToken(req, res, next) {
provider: decoded.provider
});
// For older tokens without tenantId, we need to look up the user's tenant
let tenantId = decoded.tenantId;
const user = await User.findByPk(decoded.userId, {
attributes: ['id', 'username', 'email', 'role', 'is_active', 'tenant_id']
attributes: ['id', 'username', 'email', 'role', 'is_active', 'tenant_id'],
include: [{
model: Tenant,
as: 'tenant',
attributes: ['slug', 'name']
}]
});
if (!user || !user.is_active) {
@@ -37,12 +45,15 @@ async function authenticateToken(req, res, next) {
req.user = user;
// Extract tenant info from JWT token if available
if (decoded.tenantId) {
req.tenantId = decoded.tenantId;
console.log('✅ Tenant context set:', decoded.tenantId);
// Set tenant context - prefer JWT tenantId, fallback to user's tenant
if (tenantId) {
req.tenantId = tenantId;
console.log('✅ Tenant context from JWT:', tenantId);
} else if (user.tenant && user.tenant.slug) {
req.tenantId = user.tenant.slug;
console.log('✅ Tenant context from user record:', user.tenant.slug);
} else {
console.log('⚠️ No tenantId in JWT token');
console.log('⚠️ No tenant context available');
}
next();

View File

@@ -151,8 +151,20 @@ router.post('/login', validateRequest(loginSchema), async (req, res) => {
// GET /api/users/profile - Get current user profile
router.get('/profile', authenticateToken, async (req, res) => {
try {
// Log the user object for debugging
console.log('📍 /users/profile - req.user:', {
id: req.user.id,
username: req.user.username,
role: req.user.role,
email: req.user.email,
is_active: req.user.is_active,
tenant_id: req.user.tenant_id
});
const { password_hash: _, ...userProfile } = req.user.toJSON();
console.log('📤 /users/profile - Response:', userProfile);
res.json({
success: true,
data: userProfile