Lesson 95 of 158 – Admin User API
95%

Admin User API

An Admin User API is a protected REST API used to manage users from an administrator account. In a React Native application, an admin can use this API to view users, create users, update user information, change roles, and remove users according to the permissions allowed by the system.

Note: Admin APIs must always perform authentication and authorization on the server. Hiding an admin screen in React Native is not enough to protect the API.

1. What is an Admin User API?

An Admin User API provides endpoints for administrators to manage users.

Admin Mobile App
       ↓
   JWT Token
       ↓
 Admin User API
       ↓
 Authentication
       ↓
 Authorization
       ↓
    MySQL

Only authorized users should be able to perform administrative operations.

2. Why Do We Need an Admin API?

A mobile application may need a separate administration system for managing users and application data.

  • View users
  • Create users
  • Update users
  • Delete users
  • Change user roles
  • Search users
  • Filter users
  • View user details

3. Admin API Security Flow

Request
   ↓
JWT Token
   ↓
Verify Authentication
   ↓
Identify User
   ↓
Check Admin Role
   ↓
Allow / Reject
   ↓
Admin Operation

The authorization check should happen before accessing protected data.

4. Admin User Table

A simple users table can contain user information and the user's role.

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    role VARCHAR(30) NOT NULL DEFAULT 'student',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

5. Example User Data

id | name  | email              | role
------------------------------------------
1  | Rahul | rahul@example.com  | admin
2  | Amit  | amit@example.com   | teacher
3  | Neha  | neha@example.com   | student
4  | Pooja | pooja@example.com  | student

The role determines which administrative operations the user can perform.

6. Admin GET Users API

The admin can retrieve a list of users using a GET request.

GET /api/admin/users.php

The endpoint should verify the administrator's JWT before returning users.

7. Selecting Users from MySQL

$stmt = $pdo->query(
    "SELECT id, name, email, role, created_at
     FROM users
     ORDER BY id DESC"
);

$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

Never include the password column in an administrator's normal user list.

8. Standard Users Response

{
    "success": true,
    "message": "Users retrieved successfully",
    "data": [
        {
            "id": 1,
            "name": "Rahul",
            "email": "rahul@example.com",
            "role": "admin"
        },
        {
            "id": 2,
            "name": "Amit",
            "email": "amit@example.com",
            "role": "student"
        }
    ]
}

9. Admin Authentication

Before processing the request, the API should verify the JWT.

require_once '../middleware/auth.php';

$user = requireAuth();

The authentication middleware should return the authenticated user's trusted information after successful verification.

10. Admin Authorization

if ($user['role'] !== 'admin') {

    http_response_code(403);

    echo json_encode([
        "success" => false,
        "message" => "Admin access required",
        "data" => null
    ]);

    exit;
}

Authentication and authorization should both be enforced by the server.

11. Admin POST Users API

An administrator can create a new user with a POST request.

POST /api/admin/users.php

The request body can contain the name, email, password, and role.

12. JSON Request Body

{
    "name": "Ravi",
    "email": "ravi@example.com",
    "password": "StrongPassword123",
    "role": "student"
}

The password should be hashed before storing it in the database.

13. Reading JSON in PHP

$input = json_decode(
    file_get_contents("php://input"),
    true
);

$name = trim($input['name'] ?? '');
$email = trim($input['email'] ?? '');
$password = $input['password'] ?? '';
$role = trim($input['role'] ?? 'student');

Always validate the received values before inserting them into the database.

14. Validating Admin User Data

15. Validating the Role

Do not allow arbitrary role values from the client.

$allowedRoles = [
    'admin',
    'teacher',
    'student'
];

if (!in_array($role, $allowedRoles, true)) {

    $errors['role'] = "Invalid role";
}

An allowlist prevents unexpected role values from entering the system.

16. Checking Duplicate Email

17. Hashing the Password

Passwords should never be stored as plain text.

Store the generated hash in the database instead of the original password.

18. Creating the User

Prepared statements help protect the database from SQL injection.

19. Create User Response

http_response_code(201);

echo json_encode([
    "success" => true,
    "message" => "User created successfully",
    "data" => [
        "id" => $userId,
        "name" => $name,
        "email" => $email,
        "role" => $role
    ]
]);

Never return the user's password or password hash.

20. Admin PUT Users API

PUT can be used to update a user's information.

PUT /api/admin/users.php?id=10

The API should verify that the requested user exists and that the current user has permission to update it.

21. Updating a User

$stmt = $pdo->prepare(
    "UPDATE users
     SET name = ?, email = ?, role = ?
     WHERE id = ?"
);

$stmt->execute([
    $name,
    $email,
    $role,
    $userId
]);

Password updates should normally be handled separately so that an administrator does not accidentally overwrite the existing password.

22. Admin DELETE Users API

An administrator can delete a user using a DELETE request.

DELETE /api/admin/users.php?id=10

The endpoint must verify the administrator's permissions before deleting data.

23. Preventing Self-Deletion

Many applications prevent an administrator from accidentally deleting their own account.

if ((int)$userId === (int)$user['id']) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "You cannot delete your own account"
    ]);

    exit;
}

24. Searching Users

An admin API can support search using a query parameter.

GET /api/admin/users.php?search=rahul
$search = trim($_GET['search'] ?? '');

$stmt = $pdo->prepare(
    "SELECT id, name, email, role
     FROM users
     WHERE name LIKE ?
        OR email LIKE ?
     ORDER BY id DESC"
);

$term = "%" . $search . "%";

$stmt->execute([
    $term,
    $term
]);

25. React Native Admin User List

const response = await fetch(
    "https://example.com/api/admin/users.php",
    {
        method: "GET",
        headers: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
        }
    }
);

const result = await response.json();

if (result.success) {
    setUsers(result.data);
}

The mobile application can display the returned users in a FlatList.

26. Handling 403 in React Native

if (response.status === 403) {

    Alert.alert(
        "Access Denied",
        "You do not have admin permission."
    );

    return;
}

This improves the user experience, but the server remains responsible for enforcing the permission.

27. Admin User API Structure

api/
│
├── middleware/
│   ├── auth.php
│   └── role.php
│
├── admin/
│   └── users.php
│
├── login.php
├── register.php
└── profile.php

Separating administration endpoints helps keep the API organized.

28. Complete Admin API Flow

React Native Admin App
          ↓
     Bearer JWT
          ↓
   Verify JWT Token
          ↓
    Identify Admin
          ↓
   Check Admin Role
          ↓
    Validate Request
          ↓
      MySQL CRUD
          ↓
    Standard JSON
       Response

Every sensitive operation should pass through the required security checks.

29. Common Admin API Mistakes

  • Protecting the screen but not the API
  • Not verifying the JWT
  • Not checking the admin role
  • Trusting the role sent by React Native
  • Returning password hashes
  • Not validating input
  • Using SQL queries without prepared statements
  • Allowing an administrator to accidentally delete their own account
  • Returning database errors directly to the client

30. Admin User API Best Practices

  • Use JWT authentication for protected endpoints.
  • Verify the administrator's role on the server.
  • Use prepared statements for database operations.
  • Validate every request.
  • Hash passwords using password_hash().
  • Never return passwords or password hashes.
  • Use appropriate HTTP status codes.
  • Use standard JSON responses.
  • Check ownership and special restrictions where required.
  • Test GET, POST, PUT, and DELETE operations with Postman.
  • Test the complete admin workflow from React Native.

📌 Key Points

  • An Admin User API manages users through protected REST endpoints.
  • Authentication verifies the identity of the administrator.
  • Authorization verifies that the user has admin permission.
  • Admin endpoints can support GET, POST, PUT, and DELETE operations.
  • User passwords must always be hashed.
  • Password hashes should never be returned in API responses.
  • Use prepared statements for MySQL operations.
  • Use validation and appropriate HTTP status codes.
  • React Native should send the JWT using the Authorization header.
  • Server-side authorization is the actual security boundary.

🧠 Quick Quiz

Question: Which check should an Admin User API perform to ensure that only administrators can access protected admin operations?