Wordpress external authentication

//remove_action( 'authenticate', 'wp_authenticate_username_password', 20);


add_filter( 'authenticate', 'aio_auth', 10, 3 );

function aio_auth( $user, $username, $password ){

	if($username == '' || $password == '') { 
		$user = new WP_Error( 'denied', __("ERROR: User/pass bad") );
		return;
	} else {
		//$response = wp_remote_post( "https://my.aio.it/app_users/sign_in.json", array(
		$response = wp_remote_post( "http://127.0.0.1:3000/app_users/sign_in.json", array(
			'body' => array(
				'app_user' => array(
					"email" => $username,
					"password" => $password,
				)
			)
		) );


		if ( is_wp_error( $response ) ) {
			// Se c'è un errore nella richiesta non faccio nulla. L'autenticazione prosegue localmente
			// a meno che non sia stata disabilitato il fallback.
		} else {		
			if ($response['body'] == 'ERROR') {
				// Se l'API restituisce errore gestisco il messaggio
				$user = new WP_Error( 'denied', __("ERRORE: Le credenziali utilizzate non corrispondono ad alcuna anagrafica presente in AIO" ) );
			    return $user;
			} else {
				// Altrimenti elaboro la risposta
				$body = json_decode($response['body']);
				
				$userobj = new WP_User();

				// Cerco se in wordpress l'utente è presente
				$user = $userobj->get_data_by( 'login', $body->email);
			

				if ($user->ID == 0) {
					error_log('User is NOT present!');
 
					// Se non è presente lo creo
					$userdata = array( 
									'user_email' => $body->email, 
									'user_login' => $body->email,                        
	                                'first_name' => $body->first_name,
	                                'last_name' => $body->last_name,
	                            );
					$new_user_id = wp_insert_user( $userdata ); 

	             	// carico lo user ed effettuo il login
	             	$user = new WP_User ($new_user_id);

				} else {
					error_log('User is present!');
					// Altrimenti mi eseguo il login
					$user = new WP_User($user->ID);
				}

				// Salvo il token per l'autenticazione JWT
				$headers = (array) $response['headers'];
				$headers = reset($headers);
				$jwt = str_replace('Bearer ', '', $headers['authorization']);
				
				//$decoded = JWT::decode($jwt, $key, ['HS256']);

				update_user_meta( $user->ID, 'jwt_token', $headers['authorization'] );
			    return $user;
			}

		}

	} 

}


function check_password_change( $user_id ) {
    if ( ! isset( $_POST['pass1'] ) || '' == $_POST['pass1'] ) {
        return;
    }

    // Recupero il JWT
    $jwt = get_user_meta(get_current_user_id(), 'jwt_token', true );


	$response = wp_remote_post( "https://my.aio.it/aio/app_users/profile/update_password.json", array(
	//$response = wp_remote_post( "http://127.0.0.1:3000/aio/app_users/profile/update_password.json", array(
	    'headers' => array(
	        'Content-Type' => 'application/json',
	        'Authorization' => $jwt
	    ),
		'body' => json_encode(
			array(
				"password" => $_POST['pass1']
			)
		)	
	) );

	if ( is_wp_error( $response ) ) {
		error_log('There was a problem updating user password');
	} else {
		error_log('User password updated successfully');
	}		
    error_log('Password changed');
}
add_action( 'profile_update', 'check_password_change' );


function wpse_password_reset( $user, $new_pass ) {
  error_log('Password reset hook');
  $jwt = get_user_meta($user->ID, 'jwt_token', true );

	$response = wp_remote_post( "https://my.aio.it/aio/app_users/profile/update_password.json", array(
	//$response = wp_remote_post( "http://127.0.0.1:3000/aio/app_users/profile/update_password.json", array(
	    'headers' => array(
	        'Content-Type' => 'application/json',
	        'Authorization' => $jwt
	    ),
		'body' => json_encode(
			array(
				"password" => $new_pass
			)
		)	
	) );
	if ( is_wp_error( $response ) ) {
		error_log('There was a problem updating user password');
	} else {
		error_log('User password updated successfully');
	}		
    error_log('Password changed');
}

add_action( 'password_reset', 'wpse_password_reset', 10, 2 );
Andrea Seves

Andrea Seves