fix: Use wp_authenticate + wp_set_auth_cookie + wp_set_current_user for proper session

This commit is contained in:
dwindown
2025-11-05 00:42:11 +07:00
parent 0f6696b361
commit ff29f95264
3 changed files with 20 additions and 105 deletions

View File

@@ -31,20 +31,8 @@ class AuthController {
], 400 );
}
// Use wp_signon to properly authenticate and set cookies (same as wp-login.php)
$credentials = [
'user_login' => $username,
'user_password' => $password,
'remember' => true,
];
$user = wp_signon( $credentials, is_ssl() );
// Debug logging
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( '[AuthController::login] wp_signon result: ' . ( is_wp_error( $user ) ? 'ERROR' : 'SUCCESS' ) );
error_log( '[AuthController::login] User ID: ' . ( is_wp_error( $user ) ? 'N/A' : $user->ID ) );
}
// Authenticate user (same as wp-login.php)
$user = wp_authenticate( $username, $password );
if ( is_wp_error( $user ) ) {
return new WP_REST_Response( [
@@ -55,14 +43,24 @@ class AuthController {
// Check if user has WooCommerce permissions
if ( ! user_can( $user, 'manage_woocommerce' ) ) {
// Logout if no permission
wp_logout();
return new WP_REST_Response( [
'success' => false,
'message' => __( 'You do not have permission to access this area', 'woonoow' ),
], 403 );
}
// CRITICAL: Set auth cookie AND current user (as per WordPress best practices)
// This ensures session is properly established for both standalone and wp-admin
wp_set_auth_cookie( $user->ID, true, is_ssl() );
wp_set_current_user( $user->ID );
// Debug logging
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( '[AuthController::login] Login successful for user ID: ' . $user->ID );
error_log( '[AuthController::login] Current user ID: ' . get_current_user_id() );
error_log( '[AuthController::login] Cookies set: ' . ( headers_sent() ? 'Headers already sent!' : 'OK' ) );
}
// Return user data and new nonce
return new WP_REST_Response( [
'success' => true,