Skip to content

Instantly share code, notes, and snippets.

@yoren
Last active August 3, 2016 19:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoren/9ba60405825a4cc0c463 to your computer and use it in GitHub Desktop.
Save yoren/9ba60405825a4cc0c463 to your computer and use it in GitHub Desktop.
Cookie Authentication In A AngularJS WordPress Theme
<?php
// The following function is from: https://github.com/WP-API/WP-API/blob/2.0-beta4/extras.php#L84-L136
/**
* Check for errors when using cookie-based authentication.
*
* WordPress' built-in cookie authentication is always active
* for logged in users. However, the API has to check nonces
* for each request to ensure users are not vulnerable to CSRF.
*
* @global mixed $wp_rest_auth_cookie
*
* @param WP_Error|mixed $result Error from another authentication handler,
* null if we should handle it, or another
* value if not
* @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result,
* otherwise true.
*/
function rest_cookie_check_errors( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
global $wp_rest_auth_cookie;
/*
* Is cookie authentication being used? (If we get an auth
* error, but we're still logged in, another authentication
* must have been used.)
*/
if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
return $result;
}
// Is there a nonce?
$nonce = null;
if ( isset( $_REQUEST['_wp_rest_nonce'] ) ) {
$nonce = $_REQUEST['_wp_rest_nonce'];
} elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
$nonce = $_SERVER['HTTP_X_WP_NONCE'];
}
if ( null === $nonce ) {
// No nonce at all, so act as if it's an unauthenticated request.
wp_set_current_user( 0 );
return true;
}
// Check the nonce.
$result = wp_verify_nonce( $nonce, 'wp_rest' );
if ( ! $result ) {
return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
}
return true;
}
<?php
function my_scripts() {
// ...
wp_localize_script(
'my-scripts',
'myLocalized',
array(
'partials' => trailingslashit( get_template_directory_uri() ) . 'partials/',
'nonce' => wp_create_nonce( 'wp_rest' )
)
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
<div class="say-hello">
<p ng-if="data.currentUser.id">Hello! {{data.currentUser.name}}!</p>
</div>
// ...
//sayHello Directive
app.directive('sayHello', function(){
return {
restrict: 'EA',
templateUrl: myLocalized.partials + 'say-hello.html',
controller: ['WPService', function(WPService) {
WPService.getCurrentUser();
}]
};
});
var app = angular.module('app', ['ngRoute', 'ngSanitize', 'slick']);
//Config the route
app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider) {
// ...
$httpProvider.interceptors.push([function() {
return {
'request': function(config) {
config.headers = config.headers || {};
//add nonce to avoid CSRF issues
config.headers['X-WP-Nonce'] = myLocalized.nonce;
return config;
}
};
}]);
}]);
// ...
function WPService($http) {
var WPService = {
categories: [],
posts: [],
pageTitle: 'Latest Posts:',
currentPage: 1,
totalPages: 1,
currentUser: {}
};
//...
WPService.getCurrentUser = function() {
return $http.get('wp-json/wp/v2/users/me').success(function(res){
WPService.currentUser = res;
});
};
return WPService;
}
app.factory('WPService', ['$http', WPService]);
@yoren
Copy link
Author

yoren commented Oct 11, 2015

For more information, please check this post out: Cookie Authentication In A AngularJS WordPress Theme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment