Skip to content

Instantly share code, notes, and snippets.

@heyjones
Created December 14, 2020 01:24
Show Gist options
  • Save heyjones/2df3144aa3fc43b56a5f600fb137a937 to your computer and use it in GitHub Desktop.
Save heyjones/2df3144aa3fc43b56a5f600fb137a937 to your computer and use it in GitHub Desktop.
Enables application password generation through the REST API. Use at your own risk!
<?php
namespace heyjones\userpass;
add_action( 'rest_api_init', __NAMESPACE__ . '\\rest_api_init' );
function rest_api_init() {
register_rest_route(
'heyjones',
'v1/userpass',
array(
'methods' => 'POST',
'callback' => __NAMESPACE__ . '\\create_new_application_password',
),
false
);
function create_new_application_password( $request ) {
// Parse the args
$username = $request->get_param( 'username' );
$password = $request->get_param( 'password' );
$app_name = $request->get_param( 'app_name' );
$app_id = $request->get_param( 'app_id' );
// Authenticate the user
$user = wp_authenticate(
$username,
$password
);
if( is_wp_error( $user ) ) {
// TODO: Can we just pass the error along?
$error = array(
'code' => 'invalid_username_password',
'message' => 'Unknown username or password.',
'data' => array(
'status' => 401,
),
);
wp_send_json( $error );
}
// Create the application password
$application_password = \WP_Application_Passwords::create_new_application_password(
$user->ID,
array(
'name' => $app_name,
'app_id' => $app_id,
)
);
if( is_wp_error( $application_password ) ) {
// TODO: Can we just pass the error along?
$error = array(
'code' => 'create_new_application_password',
// TODO: Actually tell them what happened
'message' => 'Something went wrong.',
'data' => array(
'status' => 401,
),
);
wp_send_json( $error );
}
// Return the password
list( $password ) = $application_password;
wp_send_json( array(
'password' => $password,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment