Skip to main content

User, Role and Capabilities

WP-Node adopts the same principles of Roles and Capabilities as described in the official WordPress documentation.

When a Context is initialized in WP-Node, it defaults to an anonymous user — a user with no ID, role, or capabilities. To perform user-specific operations, you can assign a valid WordPress user to the current context using the Current component.

Current Component​

The Current component represents the currently active user and their associated roles. It provides utility methods to retrieve user data, check roles, and validate capabilities.

Assigning a User to Context​

const context = await Application.getContext();

// Assign a user to the current context using user ID
// Alternatively, pass a username (e.g., "wp")
await context.current.assumeUser(1);

const user = context.current.user;

Retrieving Roles​

// Retrieve the primary role of the user
const role = await context.current.user?.role();

// WordPress allows users to have multiple roles.
// Use 'roles' to get all assigned roles.
const roles = await context.current.user?.roles();

Checking Capabilities​

// Check if the user has permission to edit any posts
const canEditPosts = await user?.can("edit_posts");

// Check if the user can edit a specific post (e.g., post ID 1)
const canEditPost = await user?.can("edit_post", 1);

Authentication and Authorization​

WP-Node includes a utility method checkPassword to verify a user's password hash. Combined with the Current component, this enables basic authentication and authorization logic in your app.

Here's the example

import Application from "@rnaga/wp-node/Application";
import { checkPassword } from "@rnaga/wp-node/common";

// Initialize context
const wp = await Application.getContext();

// Fetch user record from the database
const user = await wp.utils.user.get("user123");

// Attempt authentication
if (
!user.props?.ID ||
!user.props.user_pass ||
// Validate password
!checkPassword("password123", user.props.user_pass)
) {
throw new Error("Unknown user");
}

// Assign authenticated user to context
await wp.current.assumeUser(user.props.ID);

// Verify permission to edit posts
if (!(await wp.current.user!.can("edit_posts"))) {
throw new Error("User does not have permission to edit posts");
}