All files / apps/web/src/backoffice/pages OrgApiKeysManager.jsx

0% Statements 0/68
0% Branches 0/47
0% Functions 0/27
0% Lines 0/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Key, Plus, Copy, Loader2, RefreshCw, EyeOff, Trash2 } from 'lucide-react';
import api from '../../services/api';
import toast from 'react-hot-toast';
 
function OrgApiKeysManager({ organizationId }) {
  const queryClient = useQueryClient();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newKeyName, setNewKeyName] = useState('');
  const [createdKey, setCreatedKey] = useState(null);
  const [copied, setCopied] = useState(false);
 
 
  const prefix = organizationId ? `/${organizationId}` : '';
 
  const { data: keys, isLoading } = useQuery({
    queryKey: ['org-api-keys', organizationId],
    queryFn: async () => {
      const response = await api.get(`${prefix}/api-keys`);
      return response.data.data;
    },
    enabled: !!organizationId
  });
 
  const createKey = useMutation({
    mutationFn: async ({ name }) => {
      const response = await api.post(`${prefix}/api-keys`, { name });
      return response.data.data;
    },
    onSuccess: (data) => {
      setCreatedKey(data);
      queryClient.invalidateQueries(['org-api-keys', organizationId]);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Error creating API key');
    }
  });
 
  const revokeKey = useMutation({
    mutationFn: async (id) => {
      await api.patch(`${prefix}/api-keys/${id}/revoke`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['org-api-keys', organizationId]);
      toast.success('API key revoked');
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Error revoking API key');
    }
  });
 
  const deleteKey = useMutation({
    mutationFn: async (id) => {
      await api.delete(`${prefix}/api-keys/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['org-api-keys', organizationId]);
      toast.success('API key deleted');
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Error deleting API key');
    }
  });
 
  const regenerateKey = useMutation({
    mutationFn: async (id) => {
      const response = await api.post(`${prefix}/api-keys/${id}/regenerate`);
      return response.data.data;
    },
    onSuccess: (data) => {
      setCreatedKey(data);
      queryClient.invalidateQueries(['org-api-keys', organizationId]);
      if (data.propagation?.agents > 0) {
        toast.success(`Clé régénérée et propagée à ${data.propagation.agents} agent(s)`);
      } else {
        toast.success('Clé régénérée');
      }
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Error regenerating API key');
    }
  });
 
  const handleCopyRowKey = (keyValue) => {
    navigator.clipboard.writeText(keyValue);
    toast.success('Clé copiée');
  };
 
  const handleCreate = (e) => {
    e.preventDefault();
    if (!newKeyName.trim()) {
      toast.error('Name is required');
      return;
    }
    createKey.mutate({ name: newKeyName.trim() });
    setNewKeyName('');
  };
 
  const handleCopyKey = () => {
    if (createdKey?.key) {
      navigator.clipboard.writeText(createdKey.key);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };
 
  const closeCreatedKey = () => {
    setCreatedKey(null);
    setShowCreateModal(false);
    setCopied(false);
  };
 
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
      </div>
    );
  }
 
  return (
    <div className="space-y-6">
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <h4 className="text-sm font-medium text-blue-900 mb-1">Clés d'API Organisation</h4>
        <p className="text-sm text-blue-700">
          Ces clés permettent d'appeler les APIs Nooloom sans authentification JWT.
          Utilisez l'en-tête <code className="bg-blue-100 px-1 rounded">x-api-key</code> pour vous authentifier.
          Les clés sont liées à votre organisation et donnent accès aux mêmes ressources.
        </p>
      </div>
 
      <div className="flex justify-between items-center">
        <p className="text-sm text-gray-500">{keys?.length || 0} clé(s) configurée(s)</p>
        <button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          Créer une clé
        </button>
      </div>
 
      {(!keys || keys.length === 0) ? (
        <div className="bg-white rounded-lg shadow p-8 text-center">
          <Key className="w-12 h-12 mx-auto text-gray-400 mb-3" />
          <p className="text-gray-500">Aucune clé d'API configurée</p>
          <p className="text-sm text-gray-400 mt-1">Créez une clé pour intégrer Nooloom avec vos outils externes</p>
        </div>
      ) : (
        <div className="bg-white rounded-lg shadow overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nom</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Clé</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Dernière utilisation</th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {keys.map((key) => (
                <tr key={key._id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{key.name}</td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center gap-1">
                      <code className="text-sm font-mono text-gray-600">
                        {key.keyValue || key.key || key.keyPrefix}
                      </code>
                      <button
                        onClick={() => handleCopyRowKey(key.keyValue || key.key || key.keyPrefix)}
                        className="p-1 text-gray-400 hover:text-indigo-600 rounded"
                        title="Copier"
                      >
                        <Copy className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : 'Jamais'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm space-x-2">
                    {key.isActive && (
                      <>
                        <button
                          onClick={() => regenerateKey.mutate(key._id)}
                          className="inline-flex items-center px-2 py-1 text-indigo-600 hover:text-indigo-800"
                          title="Régénérer"
                        >
                          <RefreshCw className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => {
                            if (confirm('Révoquer cette clé ?')) revokeKey.mutate(key._id);
                          }}
                          className="inline-flex items-center px-2 py-1 text-yellow-600 hover:text-yellow-800"
                          title="Révoquer"
                        >
                          <EyeOff className="w-4 h-4" />
                        </button>
                      </>
                    )}
                    <button
                      onClick={() => {
                        if (confirm('Supprimer définitivement cette clé ?')) deleteKey.mutate(key._id);
                      }}
                      className="inline-flex items-center px-2 py-1 text-red-600 hover:text-red-800"
                      title="Supprimer"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
 
      {/* Create Modal */}
      {showCreateModal && !createdKey && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-medium mb-4">Créer une clé d'API</h3>
            <form onSubmit={handleCreate}>
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">Nom</label>
                <input
                  type="text"
                  value={newKeyName}
                  onChange={(e) => setNewKeyName(e.target.value)}
                  placeholder="Ex: Intégration CI/CD"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                  autoFocus
                />
              </div>
              <div className="flex justify-end space-x-3">
                <button
                  type="button"
                  onClick={() => { setShowCreateModal(false); setNewKeySystem(false); }}
                  className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
                >
                  Annuler
                </button>
                <button
                  type="submit"
                  disabled={createKey.isLoading}
                  className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
                >
                  {createKey.isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Créer'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
 
      {/* Key Created Modal */}
      {createdKey && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-lg">
            <h3 className="text-lg font-medium mb-2">Clé créée avec succès</h3>
            <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-4 mb-4">
              <div className="flex items-center bg-white border rounded-lg p-2">
                <code className="flex-1 text-sm font-mono break-all px-2">{createdKey.key}</code>
                <button
                  onClick={handleCopyKey}
                  className="flex items-center px-3 py-1.5 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 text-sm"
                >
                  <Copy className="w-3.5 h-3.5 mr-1" />
                  {copied ? 'Copiée' : 'Copier'}
                </button>
              </div>
            </div>
            <div className="flex justify-end">
              <button
                onClick={closeCreatedKey}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
              >
                Fermer
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
export default OrgApiKeysManager;