Agregar Token en usuarios
This commit is contained in:
@@ -334,6 +334,8 @@ function DashboardPage({ user, setUser }) {
|
||||
<InspectionsTab inspections={inspections} user={user} onUpdate={loadData} />
|
||||
) : activeTab === 'settings' ? (
|
||||
<SettingsTab user={user} />
|
||||
) : activeTab === 'api-tokens' ? (
|
||||
<APITokensTab user={user} />
|
||||
) : activeTab === 'users' ? (
|
||||
<div className="text-center py-12">
|
||||
<div className="text-xl text-gray-400">👥</div>
|
||||
@@ -597,6 +599,310 @@ function SettingsTab({ user }) {
|
||||
)
|
||||
}
|
||||
|
||||
function APITokensTab({ user }) {
|
||||
const [tokens, setTokens] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||||
const [newTokenDescription, setNewTokenDescription] = useState('')
|
||||
const [createdToken, setCreatedToken] = useState(null)
|
||||
const [creating, setCreating] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
loadTokens()
|
||||
}, [])
|
||||
|
||||
const loadTokens = async () => {
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
const response = await fetch(`${API_URL}/api/users/me/tokens`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setTokens(data)
|
||||
}
|
||||
|
||||
setLoading(false)
|
||||
} catch (error) {
|
||||
console.error('Error loading tokens:', error)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateToken = async (e) => {
|
||||
e.preventDefault()
|
||||
setCreating(true)
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
const response = await fetch(`${API_URL}/api/users/me/tokens`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ description: newTokenDescription || null }),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setCreatedToken(data.token)
|
||||
setShowCreateForm(false)
|
||||
setNewTokenDescription('')
|
||||
loadTokens()
|
||||
} else {
|
||||
alert('Error al crear token')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error)
|
||||
alert('Error al crear token')
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRevokeToken = async (tokenId) => {
|
||||
if (!confirm('¿Estás seguro de revocar este token? Esta acción no se puede deshacer.')) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
const response = await fetch(`${API_URL}/api/users/me/tokens/${tokenId}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Token revocado correctamente')
|
||||
loadTokens()
|
||||
} else {
|
||||
alert('Error al revocar token')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error)
|
||||
alert('Error al revocar token')
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = (text) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
alert('Token copiado al portapapeles')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl">
|
||||
<div className="mb-6 flex justify-between items-start">
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-gray-900">Mis API Tokens</h2>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
Genera tokens para acceder a la API sin necesidad de login
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
className="px-4 py-2 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-lg hover:from-indigo-700 hover:to-purple-700 transition-all transform hover:scale-105 shadow-lg"
|
||||
>
|
||||
+ Generar Nuevo Token
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Modal de Token Creado */}
|
||||
{createdToken && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg max-w-2xl w-full p-6">
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900">Token Creado Exitosamente</h3>
|
||||
<p className="text-sm text-yellow-600 mt-2">
|
||||
⚠️ Guarda este token ahora. No podrás verlo de nuevo.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 border border-gray-300 rounded-lg p-4 mb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 text-sm font-mono break-all">{createdToken}</code>
|
||||
<button
|
||||
onClick={() => copyToClipboard(createdToken)}
|
||||
className="px-3 py-1 bg-indigo-600 text-white rounded hover:bg-indigo-700 transition flex-shrink-0"
|
||||
>
|
||||
📋 Copiar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
|
||||
<p className="text-sm text-blue-900 font-semibold mb-2">Ejemplo de uso:</p>
|
||||
<code className="text-xs text-blue-800 block">
|
||||
curl -H "Authorization: Bearer {createdToken}" http://tu-api.com/api/inspections
|
||||
</code>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setCreatedToken(null)}
|
||||
className="w-full px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition"
|
||||
>
|
||||
Cerrar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Formulario de Crear Token */}
|
||||
{showCreateForm && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-4">Generar Nuevo Token</h3>
|
||||
|
||||
<form onSubmit={handleCreateToken}>
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Descripción (opcional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newTokenDescription}
|
||||
onChange={(e) => setNewTokenDescription(e.target.value)}
|
||||
placeholder="ej: Integración con sistema X"
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Te ayuda a identificar para qué usas este token
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setShowCreateForm(false)
|
||||
setNewTokenDescription('')
|
||||
}}
|
||||
className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={creating}
|
||||
className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition disabled:opacity-50"
|
||||
>
|
||||
{creating ? 'Generando...' : 'Generar'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lista de Tokens */}
|
||||
{loading ? (
|
||||
<div className="text-center py-12">
|
||||
<div className="text-gray-500">Cargando tokens...</div>
|
||||
</div>
|
||||
) : tokens.length === 0 ? (
|
||||
<div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
|
||||
<div className="text-4xl mb-3">🔑</div>
|
||||
<p className="text-gray-600 mb-2">No tienes tokens API creados</p>
|
||||
<p className="text-sm text-gray-500">Genera uno para acceder a la API sin login</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{tokens.map((token) => (
|
||||
<div
|
||||
key={token.id}
|
||||
className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition"
|
||||
>
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-lg">🔑</span>
|
||||
<h4 className="font-semibold text-gray-900">
|
||||
{token.description || 'Token sin descripción'}
|
||||
</h4>
|
||||
<span className={`px-2 py-0.5 text-xs font-medium rounded-full ${
|
||||
token.is_active
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}>
|
||||
{token.is_active ? 'Activo' : 'Revocado'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="text-sm text-gray-600 space-y-1">
|
||||
<div>
|
||||
<span className="text-gray-500">Creado:</span>{' '}
|
||||
{new Date(token.created_at).toLocaleDateString('es-ES', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})}
|
||||
</div>
|
||||
{token.last_used_at && (
|
||||
<div>
|
||||
<span className="text-gray-500">Último uso:</span>{' '}
|
||||
{new Date(token.last_used_at).toLocaleDateString('es-ES', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{!token.last_used_at && (
|
||||
<div className="text-yellow-600">
|
||||
⚠️ Nunca usado
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{token.is_active && (
|
||||
<button
|
||||
onClick={() => handleRevokeToken(token.id)}
|
||||
className="ml-4 px-3 py-1 text-sm bg-red-100 text-red-700 rounded hover:bg-red-200 transition"
|
||||
>
|
||||
Revocar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Información de Ayuda */}
|
||||
<div className="mt-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="text-blue-600 text-xl">ℹ️</span>
|
||||
<div className="flex-1 text-sm text-blue-900">
|
||||
<p className="font-semibold mb-2">¿Cómo usar los tokens API?</p>
|
||||
<p className="mb-2">
|
||||
Los tokens API te permiten acceder a todos los endpoints sin necesidad de hacer login.
|
||||
Son perfectos para integraciones, scripts automatizados o aplicaciones externas.
|
||||
</p>
|
||||
<p className="mb-2">
|
||||
Incluye el token en el header <code className="bg-blue-100 px-1 py-0.5 rounded">Authorization</code> de tus requests:
|
||||
</p>
|
||||
<code className="block bg-blue-100 p-2 rounded text-xs mt-2">
|
||||
Authorization: Bearer syntria_tu_token_aqui
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function QuestionsManagerModal({ checklist, onClose }) {
|
||||
const [questions, setQuestions] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
@@ -81,6 +81,20 @@ export default function Sidebar({ user, activeTab, setActiveTab, sidebarOpen, se
|
||||
{sidebarOpen && <span>Reportes</span>}
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
onClick={() => setActiveTab('api-tokens')}
|
||||
className={`w-full flex items-center ${sidebarOpen ? 'gap-3 px-4' : 'justify-center px-2'} py-3 rounded-lg transition ${
|
||||
activeTab === 'api-tokens'
|
||||
? 'bg-gradient-to-r from-indigo-600 to-purple-600 text-white shadow-lg'
|
||||
: 'text-indigo-200 hover:bg-indigo-900/50'
|
||||
}`}
|
||||
title={!sidebarOpen ? 'API Tokens' : ''}
|
||||
>
|
||||
<span className="text-xl">🔑</span>
|
||||
{sidebarOpen && <span>API Tokens</span>}
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
onClick={() => setActiveTab('settings')}
|
||||
|
||||
Reference in New Issue
Block a user