Fix jwt-token
This commit is contained in:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user