Skip to main content

Overview

The Admin API provides privileged endpoints for administrative operations. All endpoints require authentication with admin role. Base Path: /api/admin
All admin endpoints require the user to have the admin role. Unauthorized access will return a 403 Forbidden error.

Get Admin Statistics

const response = await api.admin.getStats();
Retrieve dashboard statistics including property counts, user metrics, and recent activity.

Authentication

Requires admin role. Returns 403 if user is not an administrator.

Response

success
boolean
required
Indicates if the request was successful
data
AdminStats
required
Admin statistics object

Example Response

{
  "success": true,
  "data": {
    "totalProperties": 156,
    "activeProperties": 142,
    "pendingProperties": 8,
    "totalUsers": 1247,
    "totalViews": 45623,
    "recentProperties": [
      {
        "id": "789",
        "title": "Departamento 2 ambientes Palermo",
        "createdAt": "2024-03-04T10:30:00Z"
      },
      {
        "id": "788",
        "title": "Casa 3 dormitorios con jardín",
        "createdAt": "2024-03-03T15:45:00Z"
      }
    ]
  }
}

Usage Example

From src/pages/AdminPage.tsx:65:
const statsResponse = await api.admin.getStats();
setStats(statsResponse.data);

Get All Properties (Admin)

const response = await api.admin.getProperties();
Retrieve all properties in the system, including those with any status. This endpoint returns properties that may be hidden from public listings.

Authentication

Requires admin role.

Response

success
boolean
required
Indicates if the request was successful
data
Property[]
required
Array of all properties with complete details including:
  • All statuses (activo, pendiente, vendido, alquilado, pausado)
  • User/owner information
  • View counts and analytics
  • Administrative metadata

Example Response

{
  "success": true,
  "data": [
    {
      "id": "123",
      "title": "Casa en Palermo",
      "status": "pendiente",
      "userId": "456",
      "viewsCount": 234,
      "createdAt": "2024-03-01T10:00:00Z",
      "updatedAt": "2024-03-04T14:30:00Z"
      // ... other property fields
    }
  ]
}

Usage Example

From src/pages/AdminPage.tsx:59:
const propertiesResponse = await api.admin.getProperties();
setProperties(propertiesResponse.data);

Get All Users

const response = await api.admin.getUsers();
Retrieve all registered users with their profile information and roles.

Authentication

Requires admin role.

Response

success
boolean
required
Indicates if the request was successful
data
User[]
required
Array of user objects

Example Response

{
  "success": true,
  "data": [
    {
      "id": "123",
      "email": "[email protected]",
      "name": "Juan Pérez",
      "role": "user",
      "createdAt": "2024-01-15T10:30:00Z",
      "emailVerified": "2024-01-15T11:00:00Z"
    },
    {
      "id": "456",
      "email": "[email protected]",
      "name": "Admin User",
      "role": "admin",
      "createdAt": "2023-12-01T09:00:00Z",
      "emailVerified": "2023-12-01T09:05:00Z"
    }
  ]
}

Update User Role

const response = await api.admin.updateUserRole("123", "admin");
Update a user’s role (promote to admin or demote to user).

Path Parameters

id
string
required
The user ID to update

Request Body

role
string
required
New role for the user. Must be either “user” or “admin”

Response

success
boolean
required
Indicates if the role was updated successfully
data
User
required
Updated user object with new role

Example Request

await api.admin.updateUserRole("123", "admin");

Example Response

{
  "success": true,
  "data": {
    "id": "123",
    "email": "[email protected]",
    "name": "Juan Pérez",
    "role": "admin",
    "updatedAt": "2024-03-04T16:45:00Z"
  }
}
Promoting users to admin grants them full access to administrative functions. Use with caution.

Update Property Status

const response = await api.admin.updatePropertyStatus("123", "activo");
Update a property’s status (activate, pause, mark as sold, etc.).

Path Parameters

id
string
required
The property ID to update

Request Body

status
string
required
New status for the property. Valid values:
  • activo - Active/published listing
  • pendiente - Pending review
  • vendido - Sold
  • alquilado - Rented
  • pausado - Paused/hidden

Response

success
boolean
required
Indicates if the status was updated successfully
data
Property
required
Updated property object with new status

Example Request

await api.admin.updatePropertyStatus("123", "vendido");

Example Response

{
  "success": true,
  "data": {
    "id": "123",
    "title": "Casa en Palermo",
    "status": "vendido",
    "updatedAt": "2024-03-04T17:00:00Z"
    // ... other property fields
  }
}

Usage Example

From src/pages/AdminPage.tsx:135:
const handleStatusChange = async (propertyId: string, newStatus: string) => {
  try {
    await api.admin.updatePropertyStatus(propertyId, newStatus);
    toast.success("Estado actualizado");
    // Refresh property list
    loadProperties();
  } catch (error) {
    toast.error("Error al actualizar estado");
  }
};

Create Admin User

const response = await api.admin.createAdmin({
  email: "[email protected]",
  password: "securePassword123",
  name: "New Admin"
});
Create a new user account with admin privileges. This is useful for initial setup or adding new administrators.

Request Body

email
string
required
Email address for the new admin (must be unique)
password
string
required
Secure password (minimum 8 characters recommended)
name
string
required
Full name of the admin user

Response

success
boolean
required
Indicates if the admin was created successfully
data
object
required

Example Request

const response = await api.admin.createAdmin({
  email: "[email protected]",
  password: "SecurePass123!",
  name: "Admin Principal"
});

Example Response

{
  "success": true,
  "data": {
    "id": "789",
    "email": "[email protected]",
    "name": "Admin Principal",
    "role": "admin",
    "message": "Admin user created successfully"
  }
}
This endpoint should be protected and only accessible to existing administrators. Consider implementing rate limiting to prevent abuse.

Error Responses

All admin endpoints may return the following errors:

Common Status Codes

  • 200 - Success
  • 400 - Bad Request (invalid parameters)
  • 401 - Unauthorized (not logged in)
  • 403 - Forbidden (not an admin)
  • 404 - Not Found (resource doesn’t exist)
  • 500 - Internal Server Error

Error Examples

{
  "message": "Admin access required",
  "code": "FORBIDDEN"
}

Admin Dashboard Example

Here’s a complete example of building an admin dashboard:
const AdminDashboard = () => {
  const [stats, setStats] = useState<AdminStats | null>(null);
  const [properties, setProperties] = useState<Property[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadAdminData = async () => {
      try {
        const [statsRes, propertiesRes, usersRes] = await Promise.all([
          api.admin.getStats(),
          api.admin.getProperties(),
          api.admin.getUsers()
        ]);

        setStats(statsRes.data);
        setProperties(propertiesRes.data);
        setUsers(usersRes.data);
      } catch (error) {
        if (error.message.includes('403')) {
          toast.error("No tienes permisos de administrador");
          navigate('/');
        } else {
          toast.error("Error cargando datos de administración");
        }
      } finally {
        setLoading(false);
      }
    };

    loadAdminData();
  }, []);

  const handleStatusChange = async (propertyId: string, newStatus: string) => {
    await api.admin.updatePropertyStatus(propertyId, newStatus);
    toast.success("Estado actualizado");
    // Refresh properties
    const response = await api.admin.getProperties();
    setProperties(response.data);
  };

  if (loading) return <LoadingSpinner />;

  return (
    <div className="admin-dashboard">
      <StatsCards stats={stats} />
      <PropertiesTable 
        properties={properties} 
        onStatusChange={handleStatusChange}
      />
      <UsersTable users={users} />
    </div>
  );
};

Security Considerations

Role-Based Access Control

All admin endpoints verify the user’s role:
// Server-side middleware example
const requireAdmin = async (req, res, next) => {
  const user = await getCurrentUser(req);
  
  if (!user || user.role !== 'admin') {
    return res.status(403).json({
      message: 'Admin access required',
      code: 'FORBIDDEN'
    });
  }
  
  next();
};

Audit Logging

Consider logging all administrative actions:
// Log admin actions
await logAdminAction({
  userId: admin.id,
  action: 'UPDATE_PROPERTY_STATUS',
  propertyId: '123',
  oldValue: 'activo',
  newValue: 'vendido',
  timestamp: new Date()
});

Build docs developers (and LLMs) love