Skip to main content

What are User Roles?

StockAPI implements role-based access control (RBAC) to manage user permissions. Each user is assigned a role that determines what actions they can perform within the system. Roles are defined when a user is created and are included in the JWT token payload, allowing the API to verify permissions on each request.

User Model Structure

The user model defines the role field with a default value:
// From userModel.js:6-10
const userSchema = Schema({
    username: { type: String, unique: true, required: true },
    password: { type: String, required: true }, // hashed
    role: { type: String, default: "vendedor" }
}, { timestamps: true });
If no role is specified during user creation, the user is automatically assigned the “vendedor” role.

Available Roles

StockAPI supports the following user roles:

vendedor

Seller/Sales RepresentativeThe default role for standard users. Designed for employees who need to manage products and create orders in daily operations.

developer

Developer/AdministratorAdvanced role with full system access. Intended for technical staff and system administrators.

Role Capabilities

Vendedor (Seller)

The “vendedor” role is designed for day-to-day business operations:
  • Create new products
  • View product details
  • Update existing products (price, stock, etc.)
  • Delete products
  • Search for products
# Example: Creating a product as vendedor
curl -X POST https://api.stockapi.com/api/products \
  -H "Authorization: Bearer <vendedor-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Leche Entera 1L",
    "price": 180,
    "stock": 30,
    "category": "Lacteos"
  }'
  • Create new orders
  • View all orders
  • Delete orders
  • Automatic stock deduction upon order creation
# Example: Creating an order as vendedor
curl -X POST https://api.stockapi.com/api/orders \
  -H "Authorization: Bearer <vendedor-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "products": [
      {"productId": "507f1f77bcf86cd799439011", "quantity": 3}
    ],
    "customerName": "Juan Perez"
  }'
  • Update product stock levels
  • View current stock information
  • Receive automatic stock updates when orders are created
# Example: Updating product stock
curl -X PUT https://api.stockapi.com/api/products/507f1f77bcf86cd799439011 \
  -H "Authorization: Bearer <vendedor-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "stock": 100
  }'

Developer (Administrator)

The “developer” role has the same capabilities as “vendedor” with additional system-level access:
Developers have full access to all product and order management features available to sellers.
  • Access to system configuration
  • Ability to manage environment variables
  • Database management capabilities
  • Monitoring and debugging access
While user creation is manual through scripts, developers have the ability to:
  • Create new users via createUserScript.js
  • Assign roles to users
  • Manage user credentials
// Example: Creating a user with developer role
// In createUserScript.js
createUser("techuser", "securepassword", "developer");

Creating Users with Roles

Users are created manually using the createUserScript.js utility. The role is specified as the third parameter:
// From createUserScript.js:15-32
async function createUser(username, password, role = "vendedor") {
    try {
        const hashedPassword = await bcrypt.hash(password, 10);

        const newUser = new User({
            username,
            password: hashedPassword,
            role
        });

        await newUser.save();
        console.log(`✅ Usuario creado: ${username}`);
    } catch (error) {
        console.error("❌ Error al crear usuario:", error.message);
    } finally {
        mongoose.connection.close();
    }
}

Creating Different Role Types

// Creates a user with vendedor role
createUser("seller1", "password123");

// Or explicitly specify vendedor
createUser("seller2", "password123", "vendedor");
User credentials should NEVER be committed to version control. The script is for internal use only, and credentials should be managed securely.

Role Information in Tokens

When a user logs in, their role is included in the JWT token payload:
// Token payload structure
{
  "id": "507f1f77bcf86cd799439011",
  "username": "admin2",
  "role": "vendedor",
  "iat": 1731500000,
  "exp": 1731514400
}
The login response also includes the user’s role:
{
  "message": "Login exitoso",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "username": "admin2",
    "role": "vendedor"
  }
}

Role Verification

The role information is extracted from the JWT token by the verifyToken middleware:
// From jwtMiddleware.js:19-20
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; // includes id, username, and role
This allows controllers to access the user’s role via req.user.role for implementing role-specific logic.

Current Implementation

In the current implementation, both “vendedor” and “developer” roles have access to all protected endpoints. The role system provides a foundation for future fine-grained permission controls.
All authenticated endpoints require a valid JWT token but do not currently restrict access based on role. This means:
  • Both roles can create, read, update, and delete products
  • Both roles can create and manage orders
  • Role differentiation is primarily organizational

Future Enhancements

The role system is designed to support future permission controls such as:

Granular Permissions

Restrict certain actions to specific roles (e.g., only developers can delete products)

Custom Roles

Add new roles like “manager”, “auditor”, or “inventory-staff” with specific permissions

Role Hierarchy

Implement role inheritance where higher roles have all permissions of lower roles

Action Logging

Track which role performed which action for audit purposes

Best Practices

1

Assign Appropriate Roles

Give users the minimum role required for their job function. Most sales staff should have the “vendedor” role.
2

Limit Developer Accounts

Only create “developer” role accounts for technical staff who need system-level access.
3

Regular Audits

Periodically review user accounts and their assigned roles to ensure they’re still appropriate.
4

Secure Credentials

Always use strong passwords and never share credentials between users, even if they have the same role.

Role Comparison

FeatureVendedorDeveloper
Create Products
View Products
Update Products
Delete Products
Create Orders
View Orders
Delete Orders
System Access
Create Users
Database Access

Next Steps

JWT Tokens

Learn how to obtain and use authentication tokens

Products API

Start using the API to manage products

Build docs developers (and LLMs) love