Skip to content

Instantly share code, notes, and snippets.

@mikedamage
Created December 13, 2013 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedamage/7945936 to your computer and use it in GitHub Desktop.
Save mikedamage/7945936 to your computer and use it in GitHub Desktop.
Authentication controller for WordPress JSON API plugin
<?php
/*
Controller name: Authentication
Controller description: Login and logout functionality exposed over AJAX
*/
class JSON_API_Authentication_Controller {
public function login() {
global $json_api;
nocache_headers();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$json_api->error("POST only!");
}
$username = $json_api->query->username;
$password = $json_api->query->password;
$user = wp_authenticate($username, $password);
if (is_wp_error($user)) {
$json_api->error("Invalid username or password.");
}
$user_id = $user->ID;
wp_set_current_user($user_id, $username);
wp_set_auth_cookie($user_id);
do_action('wp_login', $user_id);
return array(
'logged_in' => true,
'email' => $user->user_email,
'username' => $user->user_login,
);
}
public function logout() {
global $json_api;
nocache_headers();
if (!is_user_logged_in()) {
$json_api->error('Not logged in');
}
wp_logout();
return array(
'message' => 'Successfully logged out',
);
}
public function is_logged_in() {
global $json_api;
return array(
'logged_in' => is_user_logged_in(),
);
}
}
// vim: set ts=4 sw=4 expandtab :
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment