Skip to content

Commit

Permalink
fix(theme): add checks before setting preview cookie
Browse files Browse the repository at this point in the history
- do not set on ajax requests
- only set cookie if token is a string
  • Loading branch information
rpeterman-gp committed Apr 10, 2024
1 parent 83023e5 commit a96810f
Showing 1 changed file with 27 additions and 22 deletions.
49 changes: 27 additions & 22 deletions wp-content/themes/the-world/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,28 +104,33 @@ function tw_preview_post_link( $preview_link, $post ) {
* @return void
*/
function tw_init_set_auth_cookie() {
$auth = new WPGraphQL\JWT_Authentication\Auth();
$secret_key = $auth->get_secret_key();
$user = wp_get_current_user();
$cookie_name = 'tw-can_preview';

if ( $user && $secret_key && ! isset( $_COOKIE[ $cookie_name ] ) ) {
$hostname = wp_parse_url( get_site_url(), PHP_URL_HOST );
// NOTE: Regex assumes front-end domains will use single segment TLD's.
$domain = trim( preg_replace( '~.*?\.?((?:\.?[\w_-]+){2})$~', '$1', $hostname ), '.' );
$token = $auth->get_refresh_token( $user );

setcookie(
$cookie_name,
$token,
array(
'expires' => 0,
'path' => '/',
'domain' => $domain,
'httponly' => true,
'secure' => isset( $_SERVER['HTTPS'] ),
)
);

if ( ! wp_doing_ajax() ) {
$auth = new WPGraphQL\JWT_Authentication\Auth();
$secret_key = $auth->get_secret_key();
$user = wp_get_current_user();
$cookie_name = 'tw-can_preview';

if ( $user && $secret_key && ! isset( $_COOKIE[ $cookie_name ] ) ) {
$hostname = wp_parse_url( get_site_url(), PHP_URL_HOST );
// NOTE: Regex assumes front-end domains will use single segment TLD's.
$domain = trim( preg_replace( '~.*?\.?((?:\.?[\w_-]+){2})$~', '$1', $hostname ), '.' );
$token = $auth->get_refresh_token( $user );

if ( $token && is_string( $token ) ) {
setcookie(
$cookie_name,
$token,
array(
'expires' => 0,
'path' => '/',
'domain' => $domain,
'httponly' => true,
'secure' => isset( $_SERVER['HTTPS'] ),
)
);
}
}
}
}
}
Expand Down

0 comments on commit a96810f

Please sign in to comment.