diff --git a/assets/src/components/CreateUser.tsx b/assets/src/components/CreateUser.tsx
index 223ee54..a3cda25 100644
--- a/assets/src/components/CreateUser.tsx
+++ b/assets/src/components/CreateUser.tsx
@@ -17,7 +17,6 @@ import {
__experimentalHStack as HStack,
__experimentalVStack as VStack,
Dashicon,
- Snackbar,
SnackbarList,
Icon,
} from '@wordpress/components';
@@ -60,6 +59,9 @@ const initialFormState: UserFormData = {
role: 'subscriber',
};
+// Id of the general (non per-site) notice within the snackbar list.
+const GENERAL_NOTICE_ID = 'create-user-notice';
+
const CreateUser = ( {
availableSites,
}: {
@@ -82,12 +84,7 @@ const CreateUser = ( {
StrengthLevel | 'default'
>( 'default' );
const [ userCreationNotices, setUserCreationNotices ] = useState<
- Array<
- Omit< React.ComponentProps< typeof Snackbar >, 'children' > & {
- id: string;
- content: string;
- }
- >
+ Array< { id: string; content: string; className: string } >
>( [] );
const fetchStrongPassword = useCallback( async () => {
@@ -186,14 +183,21 @@ const CreateUser = ( {
);
if ( ! response.ok ) {
+ const errorData = ( await response
+ .json()
+ .catch( () => null ) ) as {
+ message?: string;
+ } | null;
setNotice( {
type: 'error',
- message: __(
- 'Failed to create user. Please try again later.',
- 'oneaccess'
- ),
+ message:
+ errorData?.message ||
+ __(
+ 'Failed to create user. Please try again later.',
+ 'oneaccess'
+ ),
} );
- throw new Error( 'Failed to create user' );
+ return;
}
const data = ( await response.json() ) as {
@@ -201,6 +205,7 @@ const CreateUser = ( {
message?: string;
data?: {
response_data?: CreateUserResult[];
+ error_log?: { site_name?: string; message?: string }[];
};
};
if ( ! data.success ) {
@@ -216,7 +221,17 @@ const CreateUser = ( {
return;
}
- const results = data?.data?.response_data || [];
+ const results: CreateUserResult[] = [
+ ...( data?.data?.response_data || [] ),
+ ...( data?.data?.error_log || [] ).map( ( failure ) => ( {
+ status: 'error' as const,
+ site: failure.site_name ?? '',
+ message:
+ failure.message ??
+ __( 'Failed to create user.', 'oneaccess' ),
+ } ) ),
+ ];
+
const newNotices = results.map(
( result: CreateUserResult, index: number ) => ( {
id: `notice-${ Date.now() }-${ index }`,
@@ -497,26 +512,32 @@ const CreateUser = ( {
- { notice && notice.message && (
- setNotice( null ) }
- >
- { notice.message }
-
- ) }
-
- { userCreationNotices.length > 0 && (
+ { ( notice?.message || userCreationNotices.length > 0 ) && (
{
- setTimeout( () => {
- setUserCreationNotices( [] );
- }, 3000 );
+ notices={ [
+ ...( notice?.message
+ ? [
+ {
+ id: GENERAL_NOTICE_ID,
+ content: notice.message,
+ className:
+ notice.type === 'error'
+ ? 'oneaccess-error-notice'
+ : 'oneaccess-success-notice',
+ },
+ ]
+ : [] ),
+ ...userCreationNotices,
+ ] }
+ onRemove={ ( id: string ) => {
+ if ( GENERAL_NOTICE_ID === id ) {
+ setNotice( null );
+ return;
+ }
+
+ setUserCreationNotices( ( current ) =>
+ current.filter( ( item ) => item.id !== id )
+ );
} }
/>
) }
diff --git a/assets/src/components/SharedUsers.tsx b/assets/src/components/SharedUsers.tsx
index e12bfe9..cd18d17 100644
--- a/assets/src/components/SharedUsers.tsx
+++ b/assets/src/components/SharedUsers.tsx
@@ -100,6 +100,12 @@ interface GenericApiResponse {
message?: string;
}
+interface DeleteUserResponse extends GenericApiResponse {
+ data?: {
+ error_log?: Array< { site_name?: string; message?: string } >;
+ };
+}
+
const SharedUsers = ( {
availableSites,
}: {
@@ -384,30 +390,56 @@ const SharedUsers = ( {
}
);
- if ( ! response.ok ) {
- throw new Error( 'Failed to delete user from sites' );
+ const data = ( await response
+ .json()
+ .catch( () => null ) ) as DeleteUserResponse | null;
+
+ if ( ! response.ok || ! data ) {
+ setNotice( {
+ type: 'error',
+ message:
+ data?.message ||
+ __( 'Failed to delete user.', 'oneaccess' ),
+ } );
+ return;
}
- const data = ( await response.json() ) as GenericApiResponse;
- if ( ! data.success ) {
- throw new Error(
- data.message || 'Failed to delete user from sites'
- );
+ if ( data.success ) {
+ setNotice( {
+ type: 'success',
+ message: __( 'User deleted successfully.', 'oneaccess' ),
+ } );
+ return;
}
+ // Partial failure: list each site's error after the summary.
+ const siteErrors = ( data.data?.error_log || [] )
+ .filter( ( failure ) => !! failure.message )
+ .map( ( { site_name: siteName = '', message = '' } ) =>
+ ! siteName || message.includes( siteName )
+ ? message
+ : `${ siteName }: ${ message }`
+ );
+
setNotice( {
- type: 'success',
- message: __( 'User deleted successfully.', 'oneaccess' ),
+ type: 'error',
+ message: [
+ data.message ||
+ __(
+ 'User could not be deleted from some sites.',
+ 'oneaccess'
+ ),
+ ...siteErrors,
+ ].join( ' ' ),
} );
-
- // Refresh users list
- await fetchUsers();
} catch {
setNotice( {
type: 'error',
message: __( 'Failed to delete user.', 'oneaccess' ),
} );
} finally {
+ // Refresh even on failure, since some sites may have been deleted.
+ await fetchUsers();
setIsDeletingUser( false );
setShowUserDeletionModal( false );
setSelectedUser( null );
diff --git a/assets/src/components/SiteModal.tsx b/assets/src/components/SiteModal.tsx
index c5143d3..42986a1 100644
--- a/assets/src/components/SiteModal.tsx
+++ b/assets/src/components/SiteModal.tsx
@@ -114,6 +114,8 @@ const SiteModal = ( {
headers: {
'Content-Type': 'application/json',
'X-OneAccess-Token': formData.api_key,
+ 'X-OneAccess-Site-URL':
+ window.OneAccessSettings.siteUrl,
},
}
);
diff --git a/assets/src/css/admin.scss b/assets/src/css/admin.scss
index d6d0e5c..b429d31 100644
--- a/assets/src/css/admin.scss
+++ b/assets/src/css/admin.scss
@@ -3,28 +3,26 @@
#oneaccess-settings-page,
#oneaccess-manage-user {
- &:has(.components-snackbar-list) {
-
- .components-snackbar-list {
- position: fixed;
- bottom: 20px;
- right: 20px;
- z-index: 1000000;
- align-items: flex-end;
- justify-content: flex-end;
- display: flex;
- flex-direction: column;
- }
+ .components-snackbar-list,
+ .components-snackbar {
+ position: fixed;
+ bottom: 20px;
+ right: 20px;
+ z-index: 1000000;
+ width: auto;
}
- &:not(:has(.components-snackbar-list)) {
+ .components-snackbar-list {
+ align-items: flex-end;
+ justify-content: flex-end;
+ display: flex;
+ flex-direction: column;
+ /* Snackbars in a list are laid out by the list itself. */
.components-snackbar {
- position: fixed;
- bottom: 20px;
- right: 20px;
- z-index: 1000000;
- width: auto;
+ position: static;
+ bottom: auto;
+ right: auto;
}
}
@@ -41,8 +39,6 @@
background-color: #e11d1d;
color: #fff;
}
-
-
}
.toplevel_page_oneaccess {
@@ -52,7 +48,6 @@
}
}
-
body {
&.oneaccess-missing-brand-sites,
diff --git a/assets/src/types/global.d.ts b/assets/src/types/global.d.ts
index 769bee1..91220b4 100644
--- a/assets/src/types/global.d.ts
+++ b/assets/src/types/global.d.ts
@@ -12,6 +12,7 @@ interface OneAccessSettings {
api_key: string;
setupUrl: string;
siteType: SiteType;
+ siteUrl: string;
}
export interface OneAccessOnboarding {
diff --git a/inc/Modules/Core/Assets.php b/inc/Modules/Core/Assets.php
index e182496..225a50c 100644
--- a/inc/Modules/Core/Assets.php
+++ b/inc/Modules/Core/Assets.php
@@ -72,6 +72,7 @@ public static function get_localized_data(): array {
'restUrl' => esc_url( home_url( '/wp-json' ) ),
'setupUrl' => esc_url( admin_url( 'admin.php?page=oneaccess-settings' ) ),
'siteType' => Settings::get_site_type(),
+ 'siteUrl' => esc_url( get_site_url() ),
];
}
diff --git a/inc/Modules/Core/Rest.php b/inc/Modules/Core/Rest.php
index 77f5d9a..cb5efd6 100644
--- a/inc/Modules/Core/Rest.php
+++ b/inc/Modules/Core/Rest.php
@@ -30,16 +30,13 @@ public function register_hooks(): void {
* @return array Modified headers.
*/
public function allowed_cors_headers( $headers ): array {
- // Skip if the headers are already present.
- if ( in_array( 'X-OneAccess-Token', $headers, true ) ) {
- return $headers;
+ // Append only the headers not already present so the list stays de-duplicated.
+ foreach ( [ 'X-OneAccess-Token', 'X-OneAccess-Site-URL' ] as $header ) {
+ if ( ! in_array( $header, $headers, true ) ) {
+ $headers[] = $header;
+ }
}
- return array_merge(
- $headers,
- [
- 'X-OneAccess-Token',
- ]
- );
+ return $headers;
}
}
diff --git a/inc/Modules/Rest/Abstract_REST_Controller.php b/inc/Modules/Rest/Abstract_REST_Controller.php
index 019e4b9..5c0f3f3 100644
--- a/inc/Modules/Rest/Abstract_REST_Controller.php
+++ b/inc/Modules/Rest/Abstract_REST_Controller.php
@@ -65,55 +65,140 @@ public static function permission_callback(): bool {
* @todo this should be on a hook.
*
* @param \WP_REST_Request $request Request.
- * @return bool
*/
- public function check_api_permissions( $request ) {
- // check if the request is from same site.
- if ( Settings::is_governing_site() ) {
- return current_user_can( 'manage_options' );
- }
+ public function check_api_permissions( $request ): bool {
+ $origin = $this->parse_origin( $request->get_header( 'origin' ) );
+ $request_origin = $origin['origin'];
+ $parsed_origin = $origin['parsed'];
+ $request_url = $origin['url'];
+ $origin_port = $origin['port'];
- // See if the `X_ONEACCESS_TOKEN` header is present.
- $token = $request->get_header( 'X_ONEACCESS_TOKEN' );
+ /**
+ * Token-based auth takes priority over the Origin same-host check: cross-site
+ * requests from sub-directory multisite installs lose the path in Origin, so
+ * same-host detection can misfire on sibling sub-sites. Validating by key
+ * instead avoids that false match.
+ */
+ $token = $request->get_header( 'X-OneAccess-Token' );
$token = ! empty( $token ) ? sanitize_text_field( wp_unslash( $token ) ) : '';
- // Bail if the token is missing or invalid.
- if ( ! hash_equals( Settings::get_api_key(), $token ) ) {
- return false;
+ if ( ! empty( $token ) ) {
+ $site_url_header = $this->parse_origin( $request->get_header( 'X-OneAccess-Site-URL' ) );
+ if ( ! empty( $site_url_header['url'] ) ) {
+ $origin = $site_url_header;
+ $request_origin = $origin['origin'];
+ $parsed_origin = $origin['parsed'];
+ $request_url = $origin['url'];
+ $origin_port = $origin['port'];
+ }
+
+ if ( empty( $request_url ) ) {
+ return false;
+ }
+
+ $stored_key = $this->get_stored_api_key( $request_url );
+ if ( empty( $stored_key ) || ! hash_equals( $stored_key, $token ) ) {
+ return false;
+ }
+
+ // Governing sites were checked by ::get_stored_api_key already.
+ if ( Settings::is_governing_site() ) {
+ return true;
+ }
+
+ // Once paired, every request (health-checks included) must come from the recorded governing site.
+ $governing_site_url = Settings::get_parent_site_url();
+ if ( ! empty( $governing_site_url ) ) {
+ return $this->is_url_from_host( $governing_site_url, $parsed_origin['host'], $origin_port );
+ }
+
+ // Only a health-check may bootstrap the governing-site relationship.
+ if ( '/' . $this->namespace . '/health-check' !== $request->get_route() ) {
+ return false;
+ }
+
+ Settings::set_parent_site_url( $request_origin );
+ return true;
}
- $request_origin = $request->get_header( 'origin' );
- $request_origin = ! empty( $request_origin ) ? esc_url_raw( wp_unslash( $request_origin ) ) : '';
- $user_agent = $request->get_header( 'user-agent' );
- $user_agent = ! empty( $user_agent ) ? sanitize_text_field( wp_unslash( $user_agent ) ) : '';
+ // No token: fall back to same-domain logged-in user check.
+ if ( empty( $request_url ) || $this->is_url_from_host( get_site_url(), $parsed_origin['host'], $origin_port ) ) {
+ return current_user_can( 'manage_options' );
+ }
- /**
- * If both origin and user-agent are missing, deny access.
- *
- * Here checking both because server side requests will not have origin header.
- */
- if ( empty( $request_origin ) && empty( $user_agent ) ) {
+ return false;
+ }
+
+ /**
+ * Parses a raw Origin or X-OneAccess-Site-URL header value into its components.
+ *
+ * @param ?string $raw Raw header value.
+ *
+ * @return array{origin: string, parsed: array, url: string, port: int|null}
+ */
+ private function parse_origin( ?string $raw ): array {
+ $origin = ! empty( $raw ) ? esc_url_raw( wp_unslash( $raw ) ) : '';
+ $parsed = wp_parse_url( $origin );
+ $parsed = is_array( $parsed ) ? $parsed : [];
+ $url = ! empty( $parsed['scheme'] ) && ! empty( $parsed['host'] )
+ ? untrailingslashit( trim( $origin ) )
+ : '';
+ $port = isset( $parsed['port'] ) ? (int) $parsed['port'] : null;
+
+ return [
+ 'origin' => $origin,
+ 'parsed' => $parsed,
+ 'url' => $url,
+ 'port' => $port,
+ ];
+ }
+
+ /**
+ * Check if two URLs belong to the same host.
+ *
+ * @param string $url The URL to check.
+ * @param string $host The host to compare against.
+ * @param int|null $port Optional. The port to compare against.
+ *
+ * @return bool True if both URLs belong to the same host (and port if specified), false otherwise.
+ */
+ protected function is_url_from_host( string $url, string $host, ?int $port = null ): bool {
+ $parsed_url = wp_parse_url( $url );
+
+ // Compare both host and port to properly handle localhost with different ports.
+ if ( ! isset( $parsed_url['host'] ) || $parsed_url['host'] !== $host ) {
return false;
}
- // If it's the same domain, we're good.
- if ( self::is_same_domain( get_site_url(), $request_origin ) ) {
- return true;
+ // If a port was provided, also compare ports.
+ if ( null !== $port ) {
+ $url_port = $parsed_url['port'] ?? 80;
+ return $url_port === $port;
}
- $governing_site_url = Settings::get_parent_site_url();
+ return true;
+ }
- // If it's a healthcheck with no governing site, allow it and set the governing site.
- if ( empty( $governing_site_url ) ) {
- if ( '/' . $this->namespace . '/health-check' === $request->get_route() ) {
- Settings::set_parent_site_url( $request_origin );
- return true;
- }
- return false;
+ /**
+ * Gets the locally-stored API key for comparison.
+ *
+ * @param ?string $site_url Site URL. Only used for brand->governing site requests.
+ *
+ * @return string The stored API key. Empty string if not found.
+ */
+ private function get_stored_api_key( ?string $site_url = null ): string {
+ if ( Settings::is_consumer_site() ) {
+ return Settings::get_api_key();
}
- // if token is valid and request is from different domain then check if it matches governing site url.
- return self::is_same_domain( $governing_site_url, $request_origin ) || false !== strpos( $user_agent, $governing_site_url );
+ // If there's no brand site URL we cannot match the API key.
+ if ( ! isset( $site_url ) ) {
+ return '';
+ }
+
+ $shared_sites = Settings::get_shared_sites();
+
+ return ! empty( $shared_sites[ $site_url ]['api_key'] ) ? $shared_sites[ $site_url ]['api_key'] : '';
}
/**
@@ -126,7 +211,7 @@ public function check_api_permissions( $request ) {
* @return string Full API endpoint URL.
*/
protected function build_api_endpoint( string $site_url, string $endpoint, string $rest_namespace = self::NAMESPACE ): string {
- return esc_url_raw( trailingslashit( $site_url ) ) . '/wp-json/' . $rest_namespace . '/' . ltrim( $endpoint, '/' );
+ return untrailingslashit( esc_url_raw( $site_url ) ) . '/wp-json/' . $rest_namespace . '/' . ltrim( $endpoint, '/' );
}
/**
diff --git a/inc/Modules/Rest/Actions_Controller.php b/inc/Modules/Rest/Actions_Controller.php
index 4178b61..e20fd82 100644
--- a/inc/Modules/Rest/Actions_Controller.php
+++ b/inc/Modules/Rest/Actions_Controller.php
@@ -456,8 +456,9 @@ private function make_brand_site_request( string $site_url, string $api_key, arr
$args = [
'headers' => [
- 'X-OneAccess-Token' => $api_key,
- 'Cache-Control' => 'no-cache',
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
+ 'Cache-Control' => 'no-cache',
],
'timeout' => 30, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- profile requests fetching take time.
];
@@ -1000,7 +1001,8 @@ public function rebuild_deduplicated_users_index(): WP_REST_Response {
trailingslashit( esc_url_raw( $site_url ) ) . 'wp-json/' . self::NAMESPACE . '/rebuild-brand-sites-index',
[
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
'timeout' => 30, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- rebuilding index take time.
]
diff --git a/inc/Modules/Rest/Brand_Site_Controller.php b/inc/Modules/Rest/Brand_Site_Controller.php
index 1d40a19..9336d33 100644
--- a/inc/Modules/Rest/Brand_Site_Controller.php
+++ b/inc/Modules/Rest/Brand_Site_Controller.php
@@ -131,7 +131,8 @@ public function reject_profile_request( \WP_REST_Request $request ): \WP_REST_Re
$site_url . '/wp-json/' . self::NAMESPACE . '/reject-profile',
[
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
'body' => [
'user_email' => $user_email,
@@ -193,7 +194,8 @@ public function approve_profile_request( \WP_REST_Request $request ): \WP_REST_R
$site_url . '/wp-json/' . self::NAMESPACE . '/approve-profile',
[
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
'body' => [
'user_id' => $user_id,
diff --git a/inc/Modules/Rest/Governing_Site_Controller.php b/inc/Modules/Rest/Governing_Site_Controller.php
index a172109..7d8d462 100644
--- a/inc/Modules/Rest/Governing_Site_Controller.php
+++ b/inc/Modules/Rest/Governing_Site_Controller.php
@@ -18,6 +18,11 @@
* Class Governing_Site_Controller
*/
class Governing_Site_Controller extends Abstract_REST_Controller {
+ /**
+ * Minimum number of characters accepted for a new user's password.
+ */
+ public const MIN_PASSWORD_LENGTH = 8;
+
/**
* {@inheritDoc}
*/
@@ -224,9 +229,8 @@ public function register_routes(): void {
'sanitize_callback' => 'sanitize_text_field',
],
'password' => [
- 'required' => true,
- 'type' => 'string',
- 'sanitize_callback' => 'sanitize_text_field',
+ 'required' => true,
+ 'type' => 'string',
],
'sites' => [
'required' => true,
@@ -355,11 +359,8 @@ public function delete_user( \WP_REST_Request $request ): \WP_REST_Response {
);
}
- // Get the user by email or login.
- $user = get_user_by( 'login', $username );
- if ( ! $user ) {
- $user = get_user_by( 'email', $email );
- }
+ // Match by email, the identity used across OneAccess; usernames may differ between sites.
+ $user = get_user_by( 'email', $email );
if ( ! $user ) {
return new \WP_REST_Response(
[
@@ -417,24 +418,35 @@ public function delete_user_from_sites( \WP_REST_Request $request ): \WP_REST_Re
);
}
- $response_data = [];
- $oneaccess_sites_info = Settings::get_shared_sites();
- $processed_sites = [];
- $error_log = [];
- $user_delete_results = [];
+ $response_data = [];
+ $processed_sites = [];
+ $error_log = [];
+ $user_delete_results = [];
foreach ( $sites as $site ) {
// Skip duplicate or invalid sites.
if ( empty( $site['site_url'] ) || in_array( $site['site_url'], $processed_sites, true ) ) {
- if ( ! empty( $site['site_url'] ) ) {
- $processed_sites[] = $site['site_url'];
- }
+ continue;
+ }
+ $processed_sites[] = $site['site_url'];
+
+ $site_info = Settings::get_shared_site_by_url( $site['site_url'] );
+ if ( null === $site_info ) {
+ $error_log[] = [
+ 'site_name' => $site['site_url'],
+ 'message' => sprintf(
+ /* translators: %s is the site URL */
+ __( 'Site %s is not connected to OneAccess.', 'oneaccess' ),
+ esc_html( $site['site_url'] )
+ ),
+ ];
continue;
}
- $request_url = $site['site_url'] . '/wp-json/' . self::NAMESPACE . '/delete-user';
- $api_key = $oneaccess_sites_info[ $site['site_url'] ]['api_key'] ?? '';
+ $site_name = ! empty( $site_info['name'] ) ? $site_info['name'] : $site['site_url'];
+ $request_url = $site_info['url'] . '/wp-json/' . self::NAMESPACE . '/delete-user';
+ $api_key = $site_info['api_key'];
$response = wp_safe_remote_request(
$request_url,
[
@@ -444,18 +456,19 @@ public function delete_user_from_sites( \WP_REST_Request $request ): \WP_REST_Re
'email' => $email,
],
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
]
);
if ( is_wp_error( $response ) ) {
$error_log[] = [
- 'site_name' => $site['site_url'] ?? '',
+ 'site_name' => $site_name,
'message' => sprintf(
- /* translators: %s is the site URL */
+ /* translators: %s is the site name */
__( 'Error deleting user from site %s.', 'oneaccess' ),
- esc_html( $site['site_url'] ?? '' )
+ esc_html( $site_name )
),
];
continue;
@@ -464,21 +477,20 @@ public function delete_user_from_sites( \WP_REST_Request $request ): \WP_REST_Re
$response_code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $response_code ) {
$error_log[] = [
- 'site_name' => $site['site_url'] ?? '',
+ 'site_name' => $site_name,
'message' => sprintf(
- /* translators: %s is the site URL */
+ /* translators: %s is the site name */
__( 'Failed to delete user from site %s.', 'oneaccess' ),
- esc_html( $site['site_url'] ?? '' )
+ esc_html( $site_name )
),
];
- $error_log[] = $response;
continue;
}
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
- if ( ! $response_body['success'] ) {
+ if ( ! is_array( $response_body ) || empty( $response_body['success'] ) ) {
$error_log[] = [
- 'site_name' => $site['site_url'] ?? '',
+ 'site_name' => $site_name,
'message' => $response_body['message'] ?? __( 'Failed to delete user from site.', 'oneaccess' ),
];
continue;
@@ -692,7 +704,7 @@ public function add_user_to_sites( \WP_REST_Request $request ): \WP_REST_Respons
$email = sanitize_email( $request->get_param( 'email' ) );
$username = sanitize_text_field( $request->get_param( 'username' ) );
$full_name = sanitize_text_field( $request->get_param( 'fullName' ) );
- $password = sanitize_text_field( $request->get_param( 'password' ) );
+ $password = (string) $request->get_param( 'password' );
$sites = $request->get_param( 'sites' );
if ( empty( $email ) || empty( $username ) || empty( $full_name ) || empty( $password ) || empty( $sites ) ) {
@@ -705,6 +717,11 @@ public function add_user_to_sites( \WP_REST_Request $request ): \WP_REST_Respons
);
}
+ $password_error = self::validate_password( $password );
+ if ( null !== $password_error ) {
+ return $password_error;
+ }
+
// Validate sites.
if ( ! is_array( $sites ) ) {
return new \WP_REST_Response(
@@ -737,11 +754,9 @@ public function add_user_to_sites( \WP_REST_Request $request ): \WP_REST_Respons
// Skip duplicate or invalid sites.
if ( empty( $site_url['url'] ) || in_array( $site_url['url'], $processed_sites, true ) ) {
- if ( ! empty( $site_url['url'] ) ) {
- $processed_sites[] = $site_url['url'];
- }
continue;
}
+ $processed_sites[] = $site_url['url'];
$api_key = $oneaccess_sites_info[ $url ]['api_key'] ?? '';
$user_role = $site_url['role'] ?? 'subscriber';
@@ -759,7 +774,8 @@ public function add_user_to_sites( \WP_REST_Request $request ): \WP_REST_Respons
'role' => $user_role,
],
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
]
);
@@ -792,7 +808,7 @@ public function add_user_to_sites( \WP_REST_Request $request ): \WP_REST_Respons
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
- if ( ! $response_body['success'] ) {
+ if ( ! is_array( $response_body ) || empty( $response_body['success'] ) ) {
$error_log[] = [
'site_name' => $site_url['url'] ?? '',
'message' => $response_body['message'] ?? __( 'Failed to add user to site.', 'oneaccess' ),
@@ -806,14 +822,7 @@ public function add_user_to_sites( \WP_REST_Request $request ): \WP_REST_Respons
'message' => __( 'User added successfully.', 'oneaccess' ),
];
- $first_name = '';
- $last_name = '';
-
- // split full name into first and last name.
- $name_parts = explode( ' ', $full_name );
-
- $first_name = $name_parts[0] ?? '';
- $last_name = isset( $name_parts[1] ) ? implode( ' ', array_slice( $name_parts, 1 ) ) : '';
+ [ $first_name, $last_name ] = self::split_full_name( $full_name );
$user_id = isset( $response_body['data']['user_id'] ) ? absint( $response_body['data']['user_id'] ) : 0;
$user_role = isset( $response_body['data']['role'] ) ? sanitize_text_field( $response_body['data']['role'] ) : 'subscriber';
@@ -931,17 +940,30 @@ public function update_user_roles_for_sites( \WP_REST_Request $request ): \WP_RE
foreach ( $roles as $key => $value ) {
$site_key = untrailingslashit( $key );
$site = (array) ( $oneaccess_sites_info[ $site_key ] ?? [] );
- $site_url = ! empty( $site['url'] ) ? trailingslashit( $site['url'] ) : '';
+ $site_url = ! empty( $site['url'] ) ? untrailingslashit( $site['url'] ) : '';
$api_key = $site['api_key'] ?? '';
$new_role = $value;
- // Skip duplicate or invalid sites.
- if ( empty( $site_url ) || in_array( $site_url, $processed_sites, true ) ) {
+ // Report unknown sites instead of silently skipping them.
+ if ( empty( $site_url ) ) {
+ $error_log[] = [
+ 'site_name' => $site_key,
+ 'message' => sprintf(
+ /* translators: %s is the site URL */
+ __( 'Site %s not found in OneAccess sites.', 'oneaccess' ),
+ esc_html( $site_key )
+ ),
+ ];
+ continue;
+ }
+
+ // Skip duplicate sites.
+ if ( in_array( $site_url, $processed_sites, true ) ) {
continue;
}
$processed_sites[] = $site_url;
- $request_url = $site_url . '/wp-json/' . self::NAMESPACE . '/update-user';
+ $request_url = $this->build_api_endpoint( $site_url, 'update-user' );
$response = wp_safe_remote_post(
$request_url,
@@ -953,7 +975,8 @@ public function update_user_roles_for_sites( \WP_REST_Request $request ): \WP_RE
'role' => $new_role,
],
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
]
);
@@ -986,7 +1009,7 @@ public function update_user_roles_for_sites( \WP_REST_Request $request ): \WP_RE
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
- if ( ! $response_body['success'] ) {
+ if ( ! is_array( $response_body ) || empty( $response_body['success'] ) ) {
$error_log[] = [
'site_name' => $site_url,
'message' => $response_body['message'] ?? __( 'Failed to update user role on site.', 'oneaccess' ),
@@ -1029,7 +1052,7 @@ public function update_user_roles_for_sites( \WP_REST_Request $request ): \WP_RE
public function create_user( \WP_REST_Request $request ): \WP_REST_Response {
$username = sanitize_user( $request->get_param( 'username' ) );
$email = sanitize_email( $request->get_param( 'email' ) );
- $password = sanitize_text_field( $request->get_param( 'password' ) );
+ $password = (string) $request->get_param( 'password' );
$full_name = sanitize_text_field( $request->get_param( 'full_name' ) );
$role = sanitize_text_field( $request->get_param( 'role' ) );
@@ -1043,6 +1066,11 @@ public function create_user( \WP_REST_Request $request ): \WP_REST_Response {
);
}
+ $password_error = self::validate_password( $password );
+ if ( null !== $password_error ) {
+ return $password_error;
+ }
+
if ( ! is_email( $email ) ) {
return new \WP_REST_Response(
[
@@ -1076,7 +1104,7 @@ public function create_user( \WP_REST_Request $request ): \WP_REST_Response {
}
// Create the user.
- $user_id = wp_create_user( $username, $password, $email );
+ $user_id = wp_create_user( $username, wp_slash( $password ), $email );
if ( is_wp_error( $user_id ) ) {
return new \WP_REST_Response(
[
@@ -1093,14 +1121,16 @@ public function create_user( \WP_REST_Request $request ): \WP_REST_Response {
$role = 'subscriber';
}
+ [ $first_name, $last_name ] = self::split_full_name( $full_name );
+
// Set the user's full name and role.
wp_update_user(
[
'ID' => $user_id,
'display_name' => $full_name,
'user_nicename' => sanitize_title( $full_name ),
- 'first_name' => explode( ' ', $full_name )[0] ?: '',
- 'last_name' => explode( ' ', $full_name )[1] ?: '',
+ 'first_name' => $first_name,
+ 'last_name' => $last_name,
'role' => $role ?: 'subscriber',
]
);
@@ -1364,6 +1394,10 @@ public function create_users_for_sites( \WP_REST_Request $request ): \WP_REST_Re
400
);
}
+ $password_error = self::validate_password( (string) $userdata['password'] );
+ if ( null !== $password_error ) {
+ return $password_error;
+ }
if ( ! isset( $userdata['fullName'] ) || empty( $userdata['fullName'] ) ) {
return new \WP_REST_Response(
[
@@ -1389,7 +1423,7 @@ public function create_users_for_sites( \WP_REST_Request $request ): \WP_REST_Re
$processed_sites[] = $site_url;
$api_key = $oneaccess_sites_info[ $site_url ]['api_key'] ?? '';
- $site_name = $oneaccess_sites_info[ $site_url ]['name'] ?? '';
+ $site_name = ! empty( $oneaccess_sites_info[ $site_url ]['name'] ) ? $oneaccess_sites_info[ $site_url ]['name'] : $site_url;
if ( empty( $api_key ) ) {
$error_log[] = [
'site_name' => $site_name,
@@ -1416,7 +1450,8 @@ public function create_users_for_sites( \WP_REST_Request $request ): \WP_REST_Re
'role' => $userdata['role'] ?? 'subscriber',
],
'headers' => [
- 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Token' => $api_key,
+ 'X-OneAccess-Site-URL' => get_site_url(),
],
]
);
@@ -1433,7 +1468,22 @@ public function create_users_for_sites( \WP_REST_Request $request ): \WP_REST_Re
continue;
}
+ $response_code = wp_remote_retrieve_response_code( $response );
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
+
+ if ( ! is_array( $response_body ) ) {
+ $error_log[] = [
+ 'site_name' => $site_name,
+ 'message' => sprintf(
+ /* translators: 1: site name, 2: HTTP status code */
+ __( 'Unreadable response from site %1$s (HTTP %2$d). The user may have been created there; please verify before retrying.', 'oneaccess' ),
+ $site_name,
+ (int) $response_code
+ ),
+ ];
+ continue;
+ }
+
if ( empty( $response_body['success'] ) ) {
$error_log[] = [
'site_name' => $site_name,
@@ -1465,4 +1515,52 @@ public function create_users_for_sites( \WP_REST_Request $request ): \WP_REST_Re
200
);
}
+
+ /**
+ * Validate a new user's password.
+ *
+ * @param string $password The password to validate.
+ *
+ * @return ?\WP_REST_Response Error response if invalid, null otherwise.
+ */
+ private static function validate_password( string $password ): ?\WP_REST_Response {
+ if ( mb_strlen( $password ) < self::MIN_PASSWORD_LENGTH ) {
+ return new \WP_REST_Response(
+ [
+ 'success' => false,
+ 'message' => sprintf(
+ /* translators: %d is the minimum number of characters */
+ __( 'Password must be at least %d characters long.', 'oneaccess' ),
+ self::MIN_PASSWORD_LENGTH
+ ),
+ ],
+ 400
+ );
+ }
+
+ if ( str_contains( $password, '\\' ) ) {
+ return new \WP_REST_Response(
+ [
+ 'success' => false,
+ 'message' => __( 'Passwords cannot contain the "\\" character.', 'oneaccess' ),
+ ],
+ 400
+ );
+ }
+
+ return null;
+ }
+
+ /**
+ * Split a full name into first and last name on the first run of whitespace.
+ *
+ * @param string $full_name The full name.
+ *
+ * @return array{0: string, 1: string} First and last name.
+ */
+ private static function split_full_name( string $full_name ): array {
+ $name_parts = preg_split( '/\s+/', trim( $full_name ), 2 ) ?: [];
+
+ return [ $name_parts[0] ?? '', $name_parts[1] ?? '' ];
+ }
}
diff --git a/inc/Modules/Settings/Settings.php b/inc/Modules/Settings/Settings.php
index 33c056d..e60f943 100644
--- a/inc/Modules/Settings/Settings.php
+++ b/inc/Modules/Settings/Settings.php
@@ -222,7 +222,7 @@ public static function sanitize_shared_sites( $input ): array {
*/
/**
- * Get brand sites configured for this governing site, keyed by the (trailing-slash) URL.
+ * Get brand sites configured for this governing site, keyed by the site URL.
*
* @return array $brand['api_key'] ?? '',
@@ -269,7 +268,7 @@ public static function get_shared_sites(): array {
public static function get_shared_site_by_url( string $site_url ): ?array {
$brand_sites = self::get_shared_sites();
- $normalized_url = trailingslashit( $site_url );
+ $normalized_url = untrailingslashit( trim( $site_url ) );
return $brand_sites[ $normalized_url ] ?? null;
}
diff --git a/inc/Modules/User/Profile_Request.php b/inc/Modules/User/Profile_Request.php
index 3a68d0a..262748d 100644
--- a/inc/Modules/User/Profile_Request.php
+++ b/inc/Modules/User/Profile_Request.php
@@ -31,6 +31,14 @@ public function register_hooks(): void {
add_action( 'personal_options_update', [ $this, 'store_profile_update_request' ] );
add_action( 'edit_user_profile_update', [ $this, 'store_profile_update_request' ] );
+ // the current user is not available until pluggable.php has loaded, so defer.
+ add_action( 'admin_init', [ $this, 'register_brand_admin_hooks' ] );
+ }
+
+ /**
+ * Register the hooks that only apply to brand admins.
+ */
+ public function register_brand_admin_hooks(): void {
// get current user.
$current_user = wp_get_current_user();
diff --git a/tests/phpunit/Integration/Modules/Core/AssetsTest.php b/tests/phpunit/Integration/Modules/Core/AssetsTest.php
index 4577cab..1d2d891 100644
--- a/tests/phpunit/Integration/Modules/Core/AssetsTest.php
+++ b/tests/phpunit/Integration/Modules/Core/AssetsTest.php
@@ -77,5 +77,6 @@ public function test_get_localized_data_returns_expected_keys(): void {
$this->assertArrayHasKey( 'restUrl', $data );
$this->assertArrayHasKey( 'setupUrl', $data );
$this->assertArrayHasKey( 'siteType', $data );
+ $this->assertArrayHasKey( 'siteUrl', $data );
}
}
diff --git a/tests/phpunit/Integration/Modules/Core/RestTest.php b/tests/phpunit/Integration/Modules/Core/RestTest.php
index 7510f75..c458f19 100644
--- a/tests/phpunit/Integration/Modules/Core/RestTest.php
+++ b/tests/phpunit/Integration/Modules/Core/RestTest.php
@@ -30,21 +30,21 @@ public function test_class_instantiation(): void {
}
/**
- * Tests that the OneAccess token header is added once.
+ * Tests that the OneAccess headers are added once.
*/
- public function test_allowed_cors_headers_adds_OneAccess_token_once(): void {
+ public function test_allowed_cors_headers_adds_OneAccess_headers_once(): void {
$rest = new Rest();
$this->assertSame(
- [ 'X-WP-Nonce', 'X-OneAccess-Token' ],
+ [ 'X-WP-Nonce', 'X-OneAccess-Token', 'X-OneAccess-Site-URL' ],
$rest->allowed_cors_headers( [ 'X-WP-Nonce' ] ),
- 'Token should be added to headers'
+ 'Headers should be added'
);
$this->assertSame(
- [ 'X-OneAccess-Token' ],
- $rest->allowed_cors_headers( [ 'X-OneAccess-Token' ] ),
- 'Token should not be readded'
+ [ 'X-OneAccess-Token', 'X-OneAccess-Site-URL' ],
+ $rest->allowed_cors_headers( [ 'X-OneAccess-Token', 'X-OneAccess-Site-URL' ] ),
+ 'Headers should not be readded'
);
}
}