|
<?php |
|
|
|
/** |
|
* Plugin Name: WPGraphQL JWT in Preview Link |
|
* Plugin URI: https://gist.github.com/lightningspirit/5f8a1aff58a0f944cf9333e511870411 |
|
* Description: Includes a WPGraphQL JWT token in every posts preview link |
|
* Author: Move Your Digital, Inc. |
|
* Author URI: https://moveyourdigital.com |
|
* Version: 0.1.0 |
|
* |
|
* @package WPGraphQL_JWT_Preview_Link |
|
*/ |
|
|
|
/* |
|
This program is free software; you can redistribute it and/or modify |
|
it under the terms of the GNU General Public License as published by |
|
the Free Software Foundation; either version 2 of the License, or |
|
(at your option) any later version. |
|
This program is distributed in the hope that it will be useful, |
|
but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
GNU General Public License for more details. |
|
You should have received a copy of the GNU General Public License |
|
along with this program; if not, write to the Free Software |
|
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
|
*/ |
|
|
|
namespace WPGraphQL\JWT_Preview_Link; |
|
|
|
// If this file is called directly, abort. |
|
if (!defined('WPINC')) { |
|
die; |
|
} |
|
|
|
/** |
|
* Generates a new JWT token for the given user |
|
* |
|
* @param WP_User given user or null for current user |
|
* @return string the JWT token |
|
*/ |
|
function generate_jwt_token(\WP_User $user = null) |
|
{ |
|
if (null == $user) { |
|
$user = get_user_by('ID', get_current_user_id()); |
|
} |
|
|
|
$jwt = \WPGraphQL\JWT_Authentication\Auth::get_token($user, false); |
|
|
|
return $jwt; |
|
} |
|
|
|
/** |
|
* Filters the URL used for a post preview. |
|
* |
|
* @since 2.0.5 |
|
* @since 4.0.0 Added the `$post` parameter. |
|
* |
|
* @param string $preview_link URL used for the post preview. |
|
* @param WP_Post $post Post object. |
|
*/ |
|
add_action('preview_post_link', function ($preview_link, $post) { |
|
if (!class_exists('\WPGraphQL\JWT_Authentication\Auth')) return $preview_link; |
|
|
|
$key = 'jwt_token_user_' . get_current_user_id(); |
|
|
|
$jwt = get_transient($key); |
|
if (!$jwt) { |
|
$jwt = generate_jwt_token(); |
|
set_transient($key, $jwt, 300); |
|
} |
|
|
|
return $preview_link . "&token=" . $jwt; |
|
}, 10, 2); |