Files
Pascal Martineau 4e9ad82d96
All checks were successful
Deploy WordPress and Nuxt / deploy (push) Successful in 1m6s
refactor: rename userSwitchTo
2025-09-18 11:50:02 -04:00

81 lines
2.6 KiB
PHP

<?php
// Register switchTo mutation
add_action( 'graphql_register_types', 'ccat_graphql_register_switch_to' );
function ccat_graphql_register_switch_to() {
register_graphql_mutation(
'switchTo',
array(
'inputFields' => array(
'userId' => array(
'type' => 'ID',
'description' => 'The ID of the user to switch to',
),
),
'outputFields' => array(
'authToken' => array(
'type' => 'String',
'description' => 'JWT Token for the target user',
),
'refreshToken' => array(
'type' => 'String',
'description' => 'JWT Refresh Token for the target user',
),
'user' => array(
'type' => 'User',
'description' => 'The target user object',
),
),
'mutateAndGetPayload' => 'ccat_graphql_switch_to_mutation',
)
);
}
// Handle switchTo mutation
function ccat_graphql_switch_to_mutation( $input ) {
if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
throw new \GraphQL\Error\UserError( "Permissions insuffisantes pour se connecter en tant qu'un autre utilisateur." );
}
$user_id = absint( $input['userId'] );
$current_user_id = get_current_user_id();
if ( $user_id === $current_user_id ) {
throw new \GraphQL\Error\UserError( 'Impossible de se connecter en tant que son propre utilisateur.' );
}
$target_user = get_user_by( 'ID', $user_id );
if ( ! $target_user ) {
throw new \GraphQL\Error\UserError( 'Utilisateur introuvable.' );
}
$secret_key = defined( 'GRAPHQL_JWT_AUTH_SECRET_KEY' ) ? GRAPHQL_JWT_AUTH_SECRET_KEY : wp_salt();
$issued_at = time();
$expire = $issued_at + ( DAY_IN_SECONDS * 7 );
$token_data = array(
'iss' => get_bloginfo( 'url' ),
'iat' => $issued_at,
'nbf' => $issued_at,
'exp' => $expire,
'data' => array(
'user' => array(
'id' => $target_user->ID,
),
'switched_by' => $current_user_id,
),
);
$auth_token = \Firebase\JWT\JWT::encode( $token_data, $secret_key, 'HS256' );
$refresh_token_data = array(
'iss' => get_bloginfo( 'url' ),
'iat' => $issued_at,
'nbf' => $issued_at,
'exp' => $issued_at + ( DAY_IN_SECONDS * 30 ),
'data' => array(
'user' => array( 'id' => $target_user->ID ),
'switched_by' => $current_user_id,
),
);
$refresh_token = \Firebase\JWT\JWT::encode( $refresh_token_data, $secret_key, 'HS256' );
return array(
'authToken' => $auth_token,
'refreshToken' => $refresh_token,
'user' => \WPGraphQL::get_app_context()->get_loader( 'user' )->load_deferred( $target_user->ID ),
);
}