Fix jwt-token

This commit is contained in:
2025-09-16 21:03:00 +02:00
parent 20a191633b
commit 69cd3e1005
3 changed files with 263 additions and 18 deletions

View File

@@ -204,6 +204,38 @@ router.post('/login', async (req, res, next) => {
}
});
/**
* POST /auth/register
* Universal registration endpoint that routes to appropriate provider
*/
router.post('/register', async (req, res, next) => {
try {
// Determine tenant
const tenantId = await multiAuth.determineTenant(req);
const authConfig = await multiAuth.getTenantAuthConfig(tenantId);
req.tenant = { id: tenantId, authConfig };
// Only local authentication supports registration
if (authConfig.type !== 'local') {
return res.status(400).json({
success: false,
message: `Registration not supported for ${authConfig.type} authentication`
});
}
// Route to local registration handler
return require('../routes/user').registerLocal(req, res, next);
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({
success: false,
message: 'Registration failed'
});
}
});
/**
* POST /auth/local
* Local authentication endpoint with tenant isolation
@@ -478,4 +510,143 @@ router.post('/test/:tenantId', async (req, res) => {
}
});
/**
* POST /auth/refresh
* Refresh JWT token
*/
router.post('/refresh', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
success: false,
message: 'Authorization token required'
});
}
const token = authHeader.substring(7);
const jwt = require('jsonwebtoken');
// Verify current token (even if expired, we want to check if it's valid)
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET, { ignoreExpiration: true });
} catch (error) {
return res.status(401).json({
success: false,
message: 'Invalid token'
});
}
// Find user to ensure they still exist and are active
const { User } = require('../models');
const user = await User.findOne({
where: { id: decoded.userId, is_active: true }
});
if (!user) {
return res.status(401).json({
success: false,
message: 'User not found or inactive'
});
}
// Generate new token
const newToken = jwt.sign(
{
userId: user.id,
username: user.username,
role: user.role,
tenantId: decoded.tenantId,
provider: user.auth_provider
},
process.env.JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({
success: true,
data: {
token: newToken,
expires_in: '24h'
},
message: 'Token refreshed successfully'
});
} catch (error) {
console.error('Token refresh error:', error);
res.status(500).json({
success: false,
message: 'Token refresh failed'
});
}
});
/**
* POST /auth/logout
* Logout (mainly for client-side token removal)
*/
router.post('/logout', (req, res) => {
res.json({
success: true,
message: 'Logged out successfully'
});
});
/**
* GET /auth/me
* Get current user information
*/
router.get('/me', async (req, res) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
success: false,
message: 'Authorization token required'
});
}
const token = authHeader.substring(7);
const jwt = require('jsonwebtoken');
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch (error) {
return res.status(401).json({
success: false,
message: 'Invalid or expired token'
});
}
// Find user
const { User } = require('../models');
const user = await User.findOne({
where: { id: decoded.userId, is_active: true },
attributes: { exclude: ['password_hash'] }
});
if (!user) {
return res.status(401).json({
success: false,
message: 'User not found or inactive'
});
}
res.json({
success: true,
data: { user },
message: 'User information retrieved successfully'
});
} catch (error) {
console.error('Get user info error:', error);
res.status(500).json({
success: false,
message: 'Failed to retrieve user information'
});
}
});
module.exports = router;