I have built an app using jQuery mobile and PhoneGap. The app fetches content from a Wordpress website using ajax and a Wordpress json plugin.
Now i wish to extend the functionality of the app to give users the posibility to update content.
For this they would have to login in wordpress.
I intend it to work somethin like this:
- Username & password sent from client to server with ajax
- Return token back to client from server
- Store token in client (local storage)
- Send that token with each requests to server and validate it serverside.
Edit: So far I got this to create the token and return it:
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
add_action( 'wp_ajax_priv_ajaxlogin', 'ajax_login' );
function ajax_login(){
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user = wp_signon( $info, false );
if ( is_wp_error($user) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Invalid username or password.')));
} else {
$expiration = $expire = time() + (14 * 24 * 60 * 60);
$pass_frag = substr($user->user_pass, 8, 4);
$key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
$hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
$token = $user->user_login . '|' . $expiration . '|' . $hash;
echo json_encode(array('loggedin'=>true, 'token'=>$token, 'message'=>__('Login successful...')));
}
die();
}
And this to verify the token:
function token_auth($token){
list($username, $expiration, $hmac) = $token;
$expired = $expiration;
// Allow a grace period for POST and AJAX requests
if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
$expired += HOUR_IN_SECONDS;
// Quick check to see if an honest cookie has expired
if ( $expired < time() ) {
return false;
}
$user = get_user_by('login', $username);
if ( ! $user ) {
return false;
}
$pass_frag = substr($user->user_pass, 8, 4);
$key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
$hash = hash_hmac('md5', $username . '|' . $expiration, $key);
if ( $hmac != $hash ) {
return false;
}
if ( $expiration < time() ) // AJAX/POST grace period set above
$GLOBALS['login_grace_period'] = 1;
return true;
wp_set_current_user( $user->ID );
}
And heres the js:
$('form#login').submit( function(e){
$('form#login p.status').show().text('Sending user info, please wait...');
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://example.com/wp-admin/admin-ajax.php',
username: $('form#login #username').val(),
password: $('form#login #password').val(),
data: {
'action': 'ajaxlogin',
'username': $('form#login #username').val(),
'password': $('form#login #password').val() },
success: function(data){
$('form#login p.status').text(data.message);
if (data.loggedin == true){
$.mobile.changePage( "/blog.html", { changeHash: false });
}
}
});
e.preventDefault();
});
Still work in progress.
Is there some way to encrypt passwords incase someone is not using https?