Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Created November 22, 2017 13:10
Show Gist options
  • Select an option

  • Save gemmadlou/f661ae7e7b5fef3a8cc3892115d97e91 to your computer and use it in GitHub Desktop.

Select an option

Save gemmadlou/f661ae7e7b5fef3a8cc3892115d97e91 to your computer and use it in GitHub Desktop.
JWT Auth Helper For Wordpress
<?php
namespace Voting\Infrastructure;
use Firebase\JWT\JWT;
use DomainException;
use SignatureInvalidException;
use UnexpectedValueException;
use Exception;
use Date;
/**
* Authentication
*/
class Authentication
{
const NONCE_ACTION = 'votingPlugin';
const ALGORITHM = 'HS256';
/**
* Must be called after scripts (whether enqueued or otherwise)
*
* @return void
*/
public static function init()
{
if (empty(self::getKey())) {
throw new Exception('JWT must be set in environment file');
}
add_action('admin_init', function() {
wp_localize_script('voting-client-js', 'votingPluginSettings', [
'nonce' => self::generateToken()
]);
});
}
private static function generateToken()
{
$user = wp_get_current_user();
if ($user->ID === 0) {
return null;
}
$token = [
'iss' => site_url(),
'aud' => site_url(),
'roles' => $user->caps,
'sub' => $user->ID,
'password' => $user->data->user_pass,
'iat' => Date('U'),
'exp' => Date('U') + (60 * 60 * 24)
];
return JWT::encode($token, self::getKey(), self::ALGORITHM);
}
/**
* Checks if nonce is valid
*
* @param string $nonce
* @return boolean
*/
public static function isValid($jwt)
{
try {
$decoded = JWT::decode($jwt, self::getKey(), [self::ALGORITHM]);
return wp_authenticate($decoded->sub, $decoded->password);
} catch (DomainException $e) {
return false;
} catch (SignatureInvalidException $e) {
return false;
} catch (UnexpectedValueException $e) {
return false;
}
}
private static function getKey()
{
return getenv('JWT_KEY');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment