Fix jwt-token

This commit is contained in:
2025-09-13 13:35:12 +02:00
parent c6c8c505ba
commit 6507c74345
2 changed files with 260 additions and 51 deletions

View File

@@ -1,8 +1,9 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom'; import { Navigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { EyeIcon, EyeSlashIcon } from '@heroicons/react/24/outline'; import { EyeIcon, EyeSlashIcon } from '@heroicons/react/24/outline';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import api from '../services/api';
const Login = () => { const Login = () => {
const [credentials, setCredentials] = useState({ const [credentials, setCredentials] = useState({
@@ -10,8 +11,54 @@ const Login = () => {
password: '' password: ''
}); });
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const [tenantConfig, setTenantConfig] = useState(null);
const [configLoading, setConfigLoading] = useState(true);
const { login, loading, isAuthenticated } = useAuth(); const { login, loading, isAuthenticated } = useAuth();
// Fetch tenant configuration on mount
useEffect(() => {
const fetchTenantConfig = async () => {
try {
const response = await api.get('/auth/config');
setTenantConfig(response.data.data);
} catch (error) {
console.error('Failed to fetch tenant config:', error);
toast.error('Failed to load authentication configuration');
} finally {
setConfigLoading(false);
}
};
fetchTenantConfig();
}, []);
if (isAuthenticated) {
return <Navigate to="/" replace />;
}
// Show loading while fetching config
if (configLoading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
<p className="mt-4 text-gray-600">Loading...</p>
</div>
</div>
);
}
// Handle different auth providers
const handleSSO = (provider) => {
if (provider === 'saml' && tenantConfig?.saml?.login_url) {
window.location.href = tenantConfig.saml.login_url;
} else if (provider === 'oauth' && tenantConfig?.oauth?.login_url) {
window.location.href = tenantConfig.oauth.login_url;
} else {
toast.error(`${provider.toUpperCase()} authentication not configured`);
}
};
if (isAuthenticated) { if (isAuthenticated) {
return <Navigate to="/" replace />; return <Navigate to="/" replace />;
} }
@@ -50,74 +97,127 @@ const Login = () => {
</svg> </svg>
</div> </div>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Drone Detection System {tenantConfig?.tenant_name || 'Drone Detection System'}
</h2> </h2>
<p className="mt-2 text-center text-sm text-gray-600"> <p className="mt-2 text-center text-sm text-gray-600">
Sign in to your account Sign in to your account
</p> </p>
{tenantConfig?.auth_provider && (
<p className="mt-1 text-center text-xs text-gray-500">
Authentication: {tenantConfig.auth_provider.toUpperCase()}
</p>
)}
</div> </div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}> {/* Local/LDAP Authentication Form */}
<div className="rounded-md shadow-sm -space-y-px"> {(tenantConfig?.auth_provider === 'local' || tenantConfig?.auth_provider === 'ldap') && (
<div> <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
<label htmlFor="username" className="sr-only"> <div className="rounded-md shadow-sm -space-y-px">
Username or Email <div>
</label> <label htmlFor="username" className="sr-only">
<input Username or Email
id="username" </label>
name="username" <input
type="text" id="username"
required name="username"
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm" type="text"
placeholder="Username or Email" required
value={credentials.username} className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
onChange={handleChange} placeholder="Username or Email"
disabled={loading} value={credentials.username}
/> onChange={handleChange}
disabled={loading}
/>
</div>
<div className="relative">
<label htmlFor="password" className="sr-only">
Password
</label>
<input
id="password"
name="password"
type={showPassword ? 'text' : 'password'}
required
className="appearance-none rounded-none relative block w-full px-3 py-2 pr-10 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
placeholder="Password"
value={credentials.password}
onChange={handleChange}
disabled={loading}
/>
<button
type="button"
className="absolute inset-y-0 right-0 pr-3 flex items-center"
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? (
<EyeSlashIcon className="h-5 w-5 text-gray-400" />
) : (
<EyeIcon className="h-5 w-5 text-gray-400" />
)}
</button>
</div>
</div> </div>
<div className="relative">
<label htmlFor="password" className="sr-only"> <div>
Password
</label>
<input
id="password"
name="password"
type={showPassword ? 'text' : 'password'}
required
className="appearance-none rounded-none relative block w-full px-3 py-2 pr-10 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
placeholder="Password"
value={credentials.password}
onChange={handleChange}
disabled={loading}
/>
<button <button
type="button" type="submit"
className="absolute inset-y-0 right-0 pr-3 flex items-center" disabled={loading}
onClick={() => setShowPassword(!showPassword)} className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
> >
{showPassword ? ( {loading ? (
<EyeSlashIcon className="h-5 w-5 text-gray-400" /> <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
) : ( ) : (
<EyeIcon className="h-5 w-5 text-gray-400" /> 'Sign in'
)} )}
</button> </button>
</div> </div>
</div> </form>
)}
<div> {/* SAML Authentication */}
{tenantConfig?.auth_provider === 'saml' && (
<div className="mt-8">
<button <button
type="submit" onClick={() => handleSSO('saml')}
disabled={loading} className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
> >
{loading ? ( <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 24 24">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div> <path d="M12 2L2 7v10c0 5.55 3.84 9.739 9 11 5.16-1.261 9-5.45 9-11V7l-10-5z"/>
) : ( </svg>
'Sign in' Sign in with SAML SSO
)}
</button> </button>
</div> </div>
)}
{/* OAuth Authentication */}
{tenantConfig?.auth_provider === 'oauth' && (
<div className="mt-8">
<button
onClick={() => handleSSO('oauth')}
className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
>
<svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
</svg>
Sign in with OAuth
</button>
</div>
)}
{/* Registration link for local auth if enabled */}
{tenantConfig?.auth_provider === 'local' && tenantConfig?.local?.allow_registration && (
<div className="text-center">
<p className="text-sm text-gray-600">
Don't have an account?{' '}
<a href="/register" className="font-medium text-primary-600 hover:text-primary-500">
Sign up
</a>
</p>
</div>
)}
{/* Demo credentials for local/ldap auth */}
{(tenantConfig?.auth_provider === 'local' || tenantConfig?.auth_provider === 'ldap') && (
<div className="text-center"> <div className="text-center">
<p className="text-sm text-gray-600"> <p className="text-sm text-gray-600">
Demo credentials: <br /> Demo credentials: <br />
@@ -125,7 +225,16 @@ const Login = () => {
Password: <code className="bg-gray-100 px-1 rounded">admin123</code> Password: <code className="bg-gray-100 px-1 rounded">admin123</code>
</p> </p>
</div> </div>
</form> )}
{/* Error message if auth provider not configured */}
{!tenantConfig?.auth_provider && (
<div className="mt-8 p-4 bg-red-50 border border-red-200 rounded-md">
<p className="text-sm text-red-600">
Authentication not configured for this tenant. Please contact your administrator.
</p>
</div>
)}
</div> </div>
</div> </div>
); );

View File

@@ -84,6 +84,73 @@ router.get('/config/:tenantId', async (req, res) => {
} }
}); });
/**
* GET /auth/config
* Get authentication configuration for current tenant (auto-detected)
*/
router.get('/config', async (req, res) => {
try {
// Auto-determine tenant from request
const tenantId = await multiAuth.determineTenant(req);
if (!tenantId) {
return res.status(400).json({
success: false,
message: 'Unable to determine tenant from request'
});
}
const tenant = await Tenant.findOne({ where: { slug: tenantId } });
if (!tenant) {
return res.status(404).json({
success: false,
message: 'Tenant not found'
});
}
// Return public auth configuration (no secrets)
const publicConfig = {
tenant_id: tenant.slug,
tenant_name: tenant.name,
auth_provider: tenant.auth_provider,
branding: tenant.branding
};
// Add provider-specific configuration
if (tenant.auth_provider === 'local') {
const authConfig = JSON.parse(tenant.auth_config || '{}');
publicConfig.local = {
allow_registration: authConfig.allow_registration || false,
require_email_verification: authConfig.require_email_verification || false
};
} else if (tenant.auth_provider === 'saml') {
publicConfig.saml = {
login_url: `/auth/saml/${tenantId}/login`,
metadata_url: `/auth/saml/${tenantId}/metadata`
};
} else if (tenant.auth_provider === 'oauth') {
publicConfig.oauth = {
login_url: `/auth/oauth/${tenantId}/login`
};
} else if (tenant.auth_provider === 'ldap') {
publicConfig.ldap = {
// LDAP uses same form as local but with different backend
};
}
res.json({
success: true,
data: publicConfig
});
} catch (error) {
console.error('Error fetching auth config:', error);
res.status(500).json({
success: false,
message: 'Failed to fetch authentication configuration'
});
}
});
/** /**
* POST /auth/login * POST /auth/login
* Universal login endpoint that routes to appropriate provider * Universal login endpoint that routes to appropriate provider
@@ -129,6 +196,39 @@ router.post('/login', async (req, res, next) => {
} }
}); });
/**
* POST /auth/local
* Local authentication endpoint with tenant isolation
*/
router.post('/local', async (req, res, next) => {
try {
// Determine tenant
const tenantId = await multiAuth.determineTenant(req);
const authConfig = await multiAuth.getTenantAuthConfig(tenantId);
// Verify tenant supports local authentication
if (authConfig.type !== 'local') {
return res.status(400).json({
success: false,
message: `This tenant uses ${authConfig.type} authentication. Please use the appropriate login method.`,
auth_provider: authConfig.type
});
}
req.tenant = { id: tenantId, authConfig };
// Call tenant-aware local login
return require('../routes/user').loginLocal(req, res, next);
} catch (error) {
console.error('Local login error:', error);
res.status(500).json({
success: false,
message: 'Local login failed'
});
}
});
/** /**
* SAML Authentication Routes * SAML Authentication Routes
*/ */