api(); } private function api() { add_action('rest_api_init', function () { register_rest_route('almefy/v1', '/register', [ 'methods' => 'POST', 'permission_callback' => '__return_true', 'callback' => function ($request) { // API Has been disabled in backend $api_enabled = get_option('almefy-api-enabled') == 1; // $registration_enabled = get_option('almefy-mail-connect-on-register') == 1; if (!$api_enabled) { return new WP_Error('disabled', __('Registration via Almefy has been disabled by an administrator.', 'almefy-me')); } $client = AlmefyManager::$client; // Check if API set up correctly if ($client == null) { return new WP_REST_Response(__('Sorry, the almefy API data is incorrect!', 'almefy-me'), 500); } // body params $username = $request['username']; $email = $request['email']; if ($email == null || !is_email($email)) { return new WP_REST_Response(__('Sorry, email missing or invalid!', 'almefy-me'), 400); } if ($username == null) { $username = $email; } // Create Wordpress user if not exists $user_id = wp_create_user($username, wp_generate_password(64), $email); // false = 'new account' email, true = 'new device' $resend = false; if (is_wp_error($user_id)) { $error_code = $user_id->get_error_code(); if($error_code === "existing_user_login") { $resend = true; } else { return new WP_REST_Response($user_id->get_error_message(), 400); } } try { $success = AlmefyMailer::send_enrollment($email, $resend); if(!$success) { return new WP_REST_Response(__('Wordpress could not send this email. Is Wordpress configured correctly?', 'almefy-me'), 500); } return; } catch (\Almefy\Exception\TransportException $e) { return new WP_REST_Response(__('Could not connect to Almefy service.', 'almefy-me'), 500); } // wp_set_current_user($user_id); // wp_set_auth_cookie($user_id, true, is_ssl()); // wp_redirect("/", 301); // TODO: return redirect url? // return admin_url('/users.php?page=almefy-device-manager'); } ]); }); } }