array( 'userId' => array( 'type' => 'ID', 'description' => esc_html__( 'The ID of the user to switch to', 'ccat' ), ), ), 'outputFields' => array( 'authToken' => array( 'type' => 'String', 'description' => esc_html__( 'JWT Token for the target user', 'ccat' ), ), 'refreshToken' => array( 'type' => 'String', 'description' => esc_html__( 'JWT Refresh Token for the target user', 'ccat' ), ), 'user' => array( 'type' => 'User', 'description' => esc_html__( 'The target user object', 'ccat' ), ), ), 'mutateAndGetPayload' => 'ccat_graphql_switch_to_mutation', ) ); } // Callback for userSwitchTo mutation function ccat_graphql_switch_to_mutation( $input ) { if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) { throw new \GraphQL\Error\UserError( esc_html__( 'Insufficient permissions', 'ccat' ) ); } $user_id = absint( $input['userId'] ); $current_user_id = get_current_user_id(); if ( $user_id === $current_user_id ) { throw new \GraphQL\Error\UserError( esc_html__( 'Cannot switch to yourself', 'ccat' ) ); } $target_user = get_user_by( 'ID', $user_id ); if ( ! $target_user ) { throw new \GraphQL\Error\UserError( esc_html__( 'User not found', 'ccat' ) ); } $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 ), ); }