Skip to main content

Entity Deletion API

Overview​

The Entity Deletion API allows authorized users to permanently remove entities from the Ring Platform. This endpoint implements strict authorization controls and audit logging to ensure only appropriate users can delete entities.

Endpoint Details​

  • URL: /api/entities/delete/[id]
  • Method: DELETE
  • Authentication: Required (JWT Token)
  • Authorization: Entity owner, ADMIN, or CONFIDENTIAL role
  • Rate Limit: 10 requests per minute

Ring Platform Concepts​

What are Entities?​

In Ring Platform, Entities represent organizations, companies, and institutions within the professional networking ecosystem:

  • 26 Industry Types: From 3D printing to quantum computing
  • Rich Metadata: Certifications, partnerships, employee count, founding year
  • Visibility Tiers: Public, subscriber, member, confidential access levels
  • Social Integration: LinkedIn, Twitter, Facebook, Instagram connections
  • Member Networks: Connected users and opportunity listings
  • Event Management: Upcoming events and announcements

Entity Deletion Impact​

Deleting an entity has cascading effects across the platform:

  • Opportunities: All linked opportunities are affected
  • Members: User associations are updated
  • Events: Upcoming events are cancelled
  • Partnerships: Cross-entity relationships are severed

URL Parameters​

  • id (string, required): The unique identifier of the entity to delete

Authentication Requirements​

This endpoint requires authentication with one of the following permissions:

  • Entity Owner: User who created the entity
  • ADMIN: Full platform administration access
  • CONFIDENTIAL: Premium access with entity management rights

Request Format​

Headers​

DELETE /api/entities/delete/{entity_id}
Authorization: Bearer <jwt_token>

Example Request​

DELETE /api/entities/delete/entity_123456789
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response Format​

Success Response (200 OK)​

{
"message": "Entity deleted successfully"
}

Error Responses​

400 Bad Request - Invalid ID​

{
"error": "Invalid ID parameter"
}

401 Unauthorized​

{
"error": "Unauthorized"
}

403 Forbidden - Insufficient Permissions​

{
"error": "Access denied: Forbidden"
}

404 Not Found​

{
"error": "Entity not found"
}

500 Internal Server Error​

{
"error": "Unable to delete entity: Internal Server Error"
}

Code Examples​

JavaScript/TypeScript​

async function deleteEntity(entityId: string, token: string): Promise<void> {
const response = await fetch(`/api/entities/delete/${entityId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to delete entity');
}

const result = await response.json();
console.log(result.message);
}

// Usage
try {
await deleteEntity('entity_123456789', userToken);
console.log('Entity deleted successfully');
} catch (error) {
console.error('Deletion failed:', error.message);
}

React Hook Example​

import { useState } from 'react';

interface UseEntityDeletionResult {
deleteEntity: (entityId: string) => Promise<void>;
isDeleting: boolean;
error: string | null;
}

function useEntityDeletion(): UseEntityDeletionResult {
const [isDeleting, setIsDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);

const deleteEntity = async (entityId: string) => {
setIsDeleting(true);
setError(null);

try {
const response = await fetch(`/api/entities/delete/${entityId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${getAuthToken()}`
}
});

if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error);
}

// Optionally refresh entity list or redirect
window.location.href = '/entities';
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
throw err;
} finally {
setIsDeleting(false);
}
};

return { deleteEntity, isDeleting, error };
}

// Usage in component
function EntityDeleteButton({ entityId }: { entityId: string }) {
const { deleteEntity, isDeleting, error } = useEntityDeletion();

const handleDelete = async () => {
if (confirm('Are you sure you want to delete this entity? This action cannot be undone.')) {
try {
await deleteEntity(entityId);
} catch (error) {
// Error is handled by the hook
}
}
};

return (
<div>
<button
onClick={handleDelete}
disabled={isDeleting}
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 disabled:opacity-50"
>
{isDeleting ? 'Deleting...' : 'Delete Entity'}
</button>
{error && (
<div className="text-red-600 mt-2">
Error: {error}
</div>
)}
</div>
);
}

cURL Example​

# Delete entity
curl -X DELETE https://ring.ck.ua/api/entities/delete/entity_123456789 \
-H "Authorization: Bearer YOUR_JWT_TOKEN"

# Expected response
# {"message":"Entity deleted successfully"}

Python Example​

import requests

def delete_entity(entity_id: str, token: str) -> bool:
"""Delete an entity by ID"""
url = f"https://ring.ck.ua/api/entities/delete/{entity_id}"
headers = {
"Authorization": f"Bearer {token}"
}

response = requests.delete(url, headers=headers)

if response.status_code == 200:
result = response.json()
print(f"Success: {result['message']}")
return True
elif response.status_code == 401:
raise PermissionError("Unauthorized - check your authentication token")
elif response.status_code == 403:
raise PermissionError("Forbidden - insufficient permissions to delete this entity")
elif response.status_code == 404:
raise ValueError("Entity not found")
else:
response.raise_for_status()

# Usage
try:
success = delete_entity("entity_123456789", "your_jwt_token")
if success:
print("Entity deleted successfully")
except Exception as e:
print(f"Error: {e}")

Authorization Logic​

Permission Hierarchy​

  1. Entity Owner: User who originally created the entity
  2. ADMIN Role: Full platform administration access
  3. CONFIDENTIAL Role: Premium access with entity management rights

Authorization Checks​

// Simplified authorization logic
function canDeleteEntity(user: User, entity: Entity): boolean {
// Admin can delete any entity
if (user.role === 'admin') return true;

// Confidential role can delete entities
if (user.role === 'confidential') return true;

// Entity owner can delete their own entity
if (entity.addedBy === user.id) return true;

return false;
}

Business Logic​

Cascade Deletion Effects​

When an entity is deleted, the following related data is affected:

  1. Opportunities: All opportunities linked to the entity
  2. Memberships: User-entity associations are removed
  3. Events: Upcoming events hosted by the entity are cancelled
  4. Partnerships: Cross-entity relationships are severed
  5. Media: Entity logos and gallery images are marked for cleanup

Audit Trail​

All entity deletions are logged with:

  • User ID: Who performed the deletion
  • Entity ID: Which entity was deleted
  • Timestamp: When the deletion occurred
  • IP Address: Source of the deletion request
  • Reason: Optional deletion reason (if provided)

Validation Rules​

Pre-deletion Checks​

  • Entity must exist and be accessible
  • User must have appropriate permissions
  • Entity must not have active dependencies (configurable)

Safety Measures​

  • Soft Delete Option: Some implementations may use soft deletion
  • Backup Creation: Entity data may be archived before deletion
  • Confirmation Required: UI should require explicit confirmation

Error Handling​

Common Error Scenarios​

  1. Invalid Entity ID

    • Status: 400
    • Cause: Malformed or missing entity ID
    • Solution: Verify entity ID format and existence
  2. Unauthorized Access

    • Status: 401
    • Cause: Missing or invalid authentication token
    • Solution: Ensure valid JWT token is provided
  3. Insufficient Permissions

    • Status: 403
    • Cause: User lacks permission to delete the entity
    • Solution: Contact admin or entity owner
  4. Entity Not Found

    • Status: 404
    • Cause: Entity doesn't exist or was already deleted
    • Solution: Verify entity ID and check if already deleted
  5. Server Error

    • Status: 500
    • Cause: Database error or system failure
    • Solution: Retry request or contact support

Security Considerations​

  1. Authentication Required: All requests must include valid JWT token
  2. Authorization Checks: Strict permission validation before deletion
  3. Audit Logging: All deletion attempts are logged for security monitoring
  4. Rate Limiting: Prevents abuse with 10 requests per minute limit
  5. Input Validation: Entity ID format validation to prevent injection attacks

Testing Examples​

Unit Test Example​

describe('DELETE /api/entities/delete/[id]', () => {
it('should delete entity successfully for admin user', async () => {
const response = await request(app)
.delete('/api/entities/delete/entity_123')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);

expect(response.body).toHaveProperty('message');
expect(response.body.message).toBe('Entity deleted successfully');
});

it('should return 403 for unauthorized user', async () => {
const response = await request(app)
.delete('/api/entities/delete/entity_123')
.set('Authorization', `Bearer ${regularUserToken}`)
.expect(403);

expect(response.body.error).toContain('Access denied');
});

it('should return 404 for non-existent entity', async () => {
const response = await request(app)
.delete('/api/entities/delete/nonexistent_id')
.set('Authorization', `Bearer ${adminToken}`)
.expect(404);

expect(response.body.error).toBe('Entity not found');
});

it('should return 400 for invalid entity ID', async () => {
const response = await request(app)
.delete('/api/entities/delete/')
.set('Authorization', `Bearer ${adminToken}`)
.expect(400);

expect(response.body.error).toBe('Invalid ID parameter');
});
});

Best Practices​

For Developers​

  1. Confirmation UI: Always require user confirmation before deletion
  2. Error Handling: Implement comprehensive error handling
  3. Loading States: Show loading indicators during deletion
  4. Success Feedback: Provide clear success/failure feedback
  5. Navigation: Redirect users appropriately after deletion

For Administrators​

  1. Backup Strategy: Ensure entity data is backed up before deletion
  2. Audit Review: Regularly review deletion logs for suspicious activity
  3. Permission Management: Carefully manage who has deletion permissions
  4. Recovery Plan: Have procedures for recovering accidentally deleted entities

Changelog​

  • v1.0.0 - Initial implementation with basic deletion
  • v1.1.0 - Added authorization checks and audit logging
  • v1.2.0 - Enhanced error handling and validation
  • v1.3.0 - Added cascade deletion effects
  • v1.4.0 - Improved security and rate limiting