Fix jwt-token
This commit is contained in:
@@ -15,7 +15,7 @@ async function authenticateToken(req, res, next) {
|
|||||||
try {
|
try {
|
||||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
const user = await User.findByPk(decoded.userId, {
|
const user = await User.findByPk(decoded.userId, {
|
||||||
attributes: ['id', 'username', 'email', 'role', 'is_active']
|
attributes: ['id', 'username', 'email', 'role', 'is_active', 'tenant_id']
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!user || !user.is_active) {
|
if (!user || !user.is_active) {
|
||||||
@@ -26,6 +26,12 @@ async function authenticateToken(req, res, next) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
req.user = user;
|
req.user = user;
|
||||||
|
|
||||||
|
// Extract tenant info from JWT token if available
|
||||||
|
if (decoded.tenantId) {
|
||||||
|
req.tenantId = decoded.tenantId;
|
||||||
|
}
|
||||||
|
|
||||||
next();
|
next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Token verification error:', error);
|
console.error('Token verification error:', error);
|
||||||
|
|||||||
@@ -215,10 +215,70 @@ router.post('/local', async (req, res, next) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
req.tenant = { id: tenantId, authConfig };
|
// Perform local authentication with tenant context
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
const { User, Tenant } = require('../models');
|
||||||
|
const { Op } = require('sequelize');
|
||||||
|
|
||||||
// Call tenant-aware local login
|
const { username, password } = req.body;
|
||||||
return require('../routes/user').loginLocal(req, res, next);
|
|
||||||
|
if (!username || !password) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Username and password are required'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find tenant
|
||||||
|
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||||
|
if (!tenant) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Tenant not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find user by username or email within this tenant
|
||||||
|
const user = await User.findOne({
|
||||||
|
where: {
|
||||||
|
[Op.or]: [
|
||||||
|
{ username: username },
|
||||||
|
{ email: username }
|
||||||
|
],
|
||||||
|
is_active: true,
|
||||||
|
tenant_id: tenant.id
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user || !await bcrypt.compare(password, user.password_hash)) {
|
||||||
|
return res.status(401).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Invalid credentials'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update last login
|
||||||
|
await user.update({ last_login: new Date() });
|
||||||
|
|
||||||
|
// Generate JWT token with tenant information
|
||||||
|
const token = multiAuth.generateJWTToken(user, tenantId);
|
||||||
|
|
||||||
|
// Remove password hash from response
|
||||||
|
const { password_hash: _, ...userResponse } = user.toJSON();
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
user: userResponse,
|
||||||
|
token,
|
||||||
|
expires_in: '24h',
|
||||||
|
tenant: {
|
||||||
|
id: tenant.slug,
|
||||||
|
name: tenant.name
|
||||||
|
}
|
||||||
|
},
|
||||||
|
message: 'Login successful'
|
||||||
|
});
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Local login error:', error);
|
console.error('Local login error:', error);
|
||||||
|
|||||||
@@ -3,10 +3,11 @@ const router = express.Router();
|
|||||||
const Joi = require('joi');
|
const Joi = require('joi');
|
||||||
const bcrypt = require('bcryptjs');
|
const bcrypt = require('bcryptjs');
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { User } = require('../models');
|
const { User, Tenant } = require('../models');
|
||||||
const { Op } = require('sequelize');
|
const { Op } = require('sequelize');
|
||||||
const { validateRequest } = require('../middleware/validation');
|
const { validateRequest } = require('../middleware/validation');
|
||||||
const { authenticateToken, requireRole } = require('../middleware/auth');
|
const { authenticateToken, requireRole } = require('../middleware/auth');
|
||||||
|
const MultiTenantAuth = require('../middleware/multi-tenant-auth');
|
||||||
|
|
||||||
// Validation schemas
|
// Validation schemas
|
||||||
const registerSchema = Joi.object({
|
const registerSchema = Joi.object({
|
||||||
@@ -80,14 +81,30 @@ router.post('/login', validateRequest(loginSchema), async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
const { username, password } = req.body;
|
const { username, password } = req.body;
|
||||||
|
|
||||||
// Find user by username or email
|
// Initialize multi-tenant auth
|
||||||
|
const multiAuth = new MultiTenantAuth();
|
||||||
|
|
||||||
|
// Determine tenant from request
|
||||||
|
const tenantId = await multiAuth.determineTenant(req);
|
||||||
|
|
||||||
|
// Find tenant
|
||||||
|
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
|
||||||
|
if (!tenant) {
|
||||||
|
return res.status(404).json({
|
||||||
|
success: false,
|
||||||
|
message: 'Tenant not found'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find user by username or email within this tenant
|
||||||
const user = await User.findOne({
|
const user = await User.findOne({
|
||||||
where: {
|
where: {
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ username: username },
|
{ username: username },
|
||||||
{ email: username }
|
{ email: username }
|
||||||
],
|
],
|
||||||
is_active: true
|
is_active: true,
|
||||||
|
tenant_id: tenant.id
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -101,12 +118,8 @@ router.post('/login', validateRequest(loginSchema), async (req, res) => {
|
|||||||
// Update last login
|
// Update last login
|
||||||
await user.update({ last_login: new Date() });
|
await user.update({ last_login: new Date() });
|
||||||
|
|
||||||
// Generate JWT token
|
// Generate JWT token with tenant information
|
||||||
const token = jwt.sign(
|
const token = multiAuth.generateJWTToken(user, tenantId);
|
||||||
{ userId: user.id, username: user.username, role: user.role },
|
|
||||||
process.env.JWT_SECRET,
|
|
||||||
{ expiresIn: '24h' }
|
|
||||||
);
|
|
||||||
|
|
||||||
// Remove password hash from response
|
// Remove password hash from response
|
||||||
const { password_hash: _, ...userResponse } = user.toJSON();
|
const { password_hash: _, ...userResponse } = user.toJSON();
|
||||||
@@ -116,7 +129,11 @@ router.post('/login', validateRequest(loginSchema), async (req, res) => {
|
|||||||
data: {
|
data: {
|
||||||
user: userResponse,
|
user: userResponse,
|
||||||
token,
|
token,
|
||||||
expires_in: '24h'
|
expires_in: '24h',
|
||||||
|
tenant: {
|
||||||
|
id: tenant.slug,
|
||||||
|
name: tenant.name
|
||||||
|
}
|
||||||
},
|
},
|
||||||
message: 'Login successful'
|
message: 'Login successful'
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user