Created
June 11, 2018 22:47
-
-
Save ChrisFlannagan/acc2dc080190df9c337c9579514f6cb5 to your computer and use it in GitHub Desktop.
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 | |
class Login { | |
public function hook(){ | |
add_filter( 'determine_current_user', [ $this, 'login_via_token' ], 20 ); | |
add_action( 'rest_api_init', [ $this, 'register_routes' ], 10 ); | |
} | |
public function register_routes(){ | |
register_rest_route( 'auth/v1', '/login/', [ | |
'methods' => 'POST', | |
'callback' => [ $this, 'basic_auth_handler' ], | |
] ); | |
} | |
public function basic_auth_handler( \WP_REST_Request $request ){ | |
if ( ! isset( $_SERVER[ 'PHP_AUTH_USER' ] ) ) { | |
return new \WP_Error( 'no_user', __( 'No User Passed' ), [ 'status' => 201 ] ); | |
} | |
$username = $_SERVER[ 'PHP_AUTH_USER' ]; | |
$password = $_SERVER[ 'PHP_AUTH_PW' ]; | |
$user = wp_authenticate( $username, $password ); | |
if ( is_wp_error( $user ) ){ | |
return $user; | |
} | |
return $this->get_valid_authenticated_response( $user ); | |
} | |
private function get_valid_authenticated_response( $user ) { | |
$columns = [ | |
'user_id' => $user->ID, | |
'token' => wp_hash_password( $user->user_email . time() ), | |
'expires' => gmdate( 'Y-m-d H:i:s', strtotime( '+1 week' ) ), | |
]; | |
AuthTable::instance()->add_token( $columns ); | |
$response = new \WP_REST_Response( $columns ); | |
$response->set_status( 200 ); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment