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β
- Entity Owner: User who originally created the entity
- ADMIN Role: Full platform administration access
- 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:
- Opportunities: All opportunities linked to the entity
- Memberships: User-entity associations are removed
- Events: Upcoming events hosted by the entity are cancelled
- Partnerships: Cross-entity relationships are severed
- 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β
-
Invalid Entity ID
- Status: 400
- Cause: Malformed or missing entity ID
- Solution: Verify entity ID format and existence
-
Unauthorized Access
- Status: 401
- Cause: Missing or invalid authentication token
- Solution: Ensure valid JWT token is provided
-
Insufficient Permissions
- Status: 403
- Cause: User lacks permission to delete the entity
- Solution: Contact admin or entity owner
-
Entity Not Found
- Status: 404
- Cause: Entity doesn't exist or was already deleted
- Solution: Verify entity ID and check if already deleted
-
Server Error
- Status: 500
- Cause: Database error or system failure
- Solution: Retry request or contact support
Security Considerationsβ
- Authentication Required: All requests must include valid JWT token
- Authorization Checks: Strict permission validation before deletion
- Audit Logging: All deletion attempts are logged for security monitoring
- Rate Limiting: Prevents abuse with 10 requests per minute limit
- 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');
});
});
Related Endpointsβ
- Get Entity Details - Retrieve entity information
- Update Entity - Modify entity details
- Create Entity - Create new entity
- List Entities - Browse all entities
- Entity Upload - Upload entity files
Best Practicesβ
For Developersβ
- Confirmation UI: Always require user confirmation before deletion
- Error Handling: Implement comprehensive error handling
- Loading States: Show loading indicators during deletion
- Success Feedback: Provide clear success/failure feedback
- Navigation: Redirect users appropriately after deletion
For Administratorsβ
- Backup Strategy: Ensure entity data is backed up before deletion
- Audit Review: Regularly review deletion logs for suspicious activity
- Permission Management: Carefully manage who has deletion permissions
- 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