wp.api如何验证当前用户及生产力(同rest api断点)

Published
2023-09-05
浏览次数 :  55

首先初始化wp.api

var wpApi = new wp.api.models.User({ id: 'me' });

id: 'me' 这个参数告诉wordpress抓取当前登录的用户,同 rest api 路由里面的 GET /wp/v2/users/me, (wp.api 就是rest api的客户端)

用fetch() 方法获取当前用户

wpApi.fetch().done(function(currentUser) {
    // `currentUser` now contains information about the current user
});

回调函数返回的currentUser会包含一切当前登录用户的信息,包含用户角色和用户生产力。

用代码检验用户生产力

要检验用户的角色和生产力,rest api的路由要加上查询?context=edit,, 路由地址是这样: url:’http://wp.local/wp-json/wp/v2/users/1?context=edit’, ,查看官方文档, https://developer.wordpress.org/rest-api/reference/users/,就会看到很多字段都有context的要求,在wp.api里面,我们可以在fetch方法里面传达data的方式来传递 context:edit

然后这里返回的结果包含rolse和capabilities: 记住要用到context 时候一定要传递nonce :

var wpApi = new wp.api.models.User({id:2}); 


	wpApi.fetch({data:{
		context:'edit'
	}}).done(function(res) {
		console.log(res);
	});

然后来验证这个capabilities和roles

if (currentUser.capabilities && currentUser.capabilities.edit_posts) {
    // The user can edit posts
} else {
    // The user cannot edit posts
}

将edit_posts 这个生产力可以替换成你想要的生产力

要明确wp用户的生产力基于用户的角色, 所以最好检验下用户的角色,看角色里面是否包含需要的生产力:

if (currentUser.roles && currentUser.roles.includes('editor')) {
    // The user has the 'editor' role
}

最好在用户可以接触到wp.api 之前先验证下用户的权限。根据您的身份验证方法(例如,OAuth、JWT、基本身份验证),您可能需要在发出API请求之前单独处理身份验证。

然后再给请求添加Nonce 防止CSRF

php里先创建nonce

function generate_custom_nonce() {
    $nonce = wp_create_nonce('my_custom_nonce'); // 'my_custom_nonce' is a unique identifier for your nonce
    wp_localize_script('your-script-handle', 'customNonce', $nonce);
}
add_action('wp_enqueue_scripts', 'generate_custom_nonce');

下一步

// Use the nonce for authentication
var nonce = customNonce;

// Initialize wp.api with the current user
var wpApi = new wp.api.models.User({ id: 'me' });

// Fetch the current user with the nonce for authentication
wpApi.fetch({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', nonce);
    },
}).done(function(currentUser) {
    // currentUser now contains information about the authenticated user
    if (currentUser.capabilities && currentUser.capabilities.edit_posts) {
        // The user can edit posts
    } else {
        // The user cannot edit posts
    }
});

使用application password的版本

// Example: Authenticate user and obtain a token (JWT or OAuth)
$.ajax({
    method: 'POST',
    url: '/your-authentication-endpoint', // Replace with your authentication endpoint
    data: {
        username: 'your_username',
        password: 'your_password',
    },
    success: function(token) {
        // Store the token securely (e.g., in a cookie or localStorage)
        localStorage.setItem('authToken', token);
        // Continue with API requests
        fetchCurrentUser();
    },
    error: function(err) {
        console.error('Authentication failed:', err);
    },
});
// Function to fetch the current user
function fetchCurrentUser() {
    // Retrieve the authentication token from storage
    var authToken = localStorage.getItem('authToken');

    if (!authToken) {
        console.error('Authentication token not found.');
        return;
    }

    // Set up headers with the authentication token
    var headers = {
        'Authorization': 'Bearer ' + authToken,
    };

    // Initialize wp.api with headers
    var wpApi = new wp.api.models.User({ id: 'me' }, { headers: headers });

    // Fetch the current user data
    wpApi.fetch().done(function(currentUser) {
        // Access user data and check capabilities or roles as needed
        if (currentUser.capabilities && currentUser.capabilities.edit_posts) {
            // The user can edit posts
        } else {
            // The user cannot edit posts
        }

        if (currentUser.roles && currentUser.roles.includes('editor')) {
            // The user has the 'editor' role
        }
    }).fail(function(xhr, status, error) {
        console.error('Failed to fetch user data:', error);
    });
}

// Call the fetchCurrentUser function after authentication
// This assumes that authentication has been successfully completed earlier
fetchCurrentUser();

标签:
Top