Created
November 22, 2017 13:10
-
-
Save gemmadlou/f661ae7e7b5fef3a8cc3892115d97e91 to your computer and use it in GitHub Desktop.
JWT Auth Helper For Wordpress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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