Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ function getLoginToken(): string | null {
return new URLSearchParams(window.location.search).get("loginToken");
}

function getBackendUserId(): string | null {
return new URLSearchParams(window.location.search).get("backendUserId");
function getLocalStorageKey(): string | null {
return new URLSearchParams(window.location.search).get("localStorageKey");
}

async function main() {
Expand All @@ -60,8 +60,8 @@ async function main() {
root.className = "hydrogen";
const config = await fetchConfig();

const backendUserId = getBackendUserId();
const platform = new ChatrixPlatform({container: root, assetPaths, config: {}, options: { development: import.meta.env.DEV }}, config.instance_id, backendUserId);
const localStorageKey = getLocalStorageKey();
const platform = new ChatrixPlatform({container: root, assetPaths, config: {}, options: { development: import.meta.env.DEV }}, localStorageKey);
attachLogExportToWindow(platform);
const navigation = new Navigation(allowsChild);
platform.setNavigation(navigation);
Expand Down
4 changes: 2 additions & 2 deletions src/parent/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ function loadIframe(minimized = false) {
throw new Error("CHATRIX_CONFIG_LOCATION is not set");
}

const backendUserId = (window as any).CHATRIX_BACKEND_USER_ID || null;
const localStorageKey = (window as any).CHATRIX_LOCAL_STORAGE_KEY || null;

const urlParams = new URLSearchParams(window.location.search);
const loginToken = urlParams.get("loginToken");
urlParams.delete("loginToken");
window.history.replaceState( null, '', (urlParams.entries.length ? '?' + urlParams : './' ) + location.hash );

iframe.src = new URL(
`${htmlLocation}?config=${configLocation}${minimized? "&minimized=true": ""}${loginToken? "&loginToken="+encodeURIComponent(loginToken): ""}${backendUserId? "&backendUserId="+encodeURIComponent(backendUserId): ""}`,
`${htmlLocation}?config=${configLocation}${minimized? "&minimized=true": ""}${loginToken? "&loginToken="+encodeURIComponent(loginToken): ""}${localStorageKey? "&localStorageKey="+encodeURIComponent(localStorageKey): ""}`,
hostRoot
).href;
iframe.className = "chatrix-iframe";
Expand Down
37 changes: 3 additions & 34 deletions src/platform/ChatrixPlatform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,40 +18,9 @@ import { Platform } from "hydrogen-view-sdk";
import { SessionInfoStorage } from "./SessionInfoStorage";

export class ChatrixPlatform extends Platform {
constructor(options, instanceId: string | null, backendUserId: string | null) {
constructor(options, localStorageKey: string) {
super(options);
let sessionPrefix = "hydrogen_sessions_v1";
let sessionName = sessionPrefix;
if (instanceId && instanceId !== "") {
sessionName = `${sessionName}_${instanceId}`;
}
if (backendUserId && backendUserId !== "") {
sessionName = `${sessionName}_${backendUserId}`;
this.cleanupSessions(sessionPrefix,backendUserId);
}

this.sessionInfoStorage = new SessionInfoStorage(sessionName);
}

cleanupSessions(sessionPrefix: string, backendUserId: string) {
for (let i=0; i<localStorage.length; i++) {
let key = localStorage.key(i);
if (!key.startsWith(sessionPrefix) || key.endsWith(backendUserId)) {
continue;
}
this.invalidateSession(
JSON.parse(localStorage.getItem(key))[0]
);
localStorage.removeItem(key);
}
}

async invalidateSession(session: {[key: string]: string}) {
await fetch(session.homeserver + '/_matrix/client/v3/logout', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + session.accessToken,
},
});
localStorageKey = localStorageKey ?? "hydrogen_sessions_v1";
this.sessionInfoStorage = new SessionInfoStorage(localStorageKey);
}
}
60 changes: 52 additions & 8 deletions wordpress/chatrix/src/plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Automattic\Chatrix;

const LOCAL_STORAGE_KEY_PREFIX = 'hydrogen_sessions_v1';

function asset_url( $asset_path ): string {
return plugins_url( "../frontend/$asset_path", __FILE__ );
}
Expand Down Expand Up @@ -51,13 +53,14 @@ function () {

// The instance id is the $uri without the trailing '/'.
$instance_id = rtrim( $page_uri, '/' );
if ( ! array_key_exists( $instance_id, $instances ) ) {
if ( ! $instances || ! array_key_exists( $instance_id, $instances ) ) {
return null;
}

return array(
'url' => rest_url( "chatrix/config/$instance_id" ),
'config' => $instances[ $instance_id ],
'url' => rest_url( "chatrix/config/$instance_id" ),
'config' => $instances[ $instance_id ],
'instance_id' => $instance_id,
);
}
);
Expand All @@ -71,21 +74,62 @@ function () {
$config = chatrix_config();
if ( $config ) {
$current_user = wp_get_current_user();

$local_storage_key = LOCAL_STORAGE_KEY_PREFIX;

if ( ! empty( $config['instance_id'] ) ) {
$local_storage_key = $local_storage_key . '_' . $config['instance_id'];
}

if ( 0 !== $current_user->ID ) {
$local_storage_key = $local_storage_key . '_' . $current_user->user_login;
}
?>
<script type="text/javascript">
window.CHATRIX_HTML_LOCATION = "<?php echo esc_url( asset_url( 'chatrix.html' ) ); ?>";
window.CHATRIX_CONFIG_LOCATION = "<?php echo esc_url( $config['url'] ); ?>";
<?php if ( 0 === $current_user->ID ) { ?>
window.CHATRIX_BACKEND_USER_ID = null;
<?php } else { ?>
window.CHATRIX_BACKEND_USER_ID = "<?php echo esc_js( $current_user->user_login ); ?>";
<?php } ?>
window.CHATRIX_LOCAL_STORAGE_KEY = "<?php echo esc_js( $local_storage_key ); ?>";
</script>
<?php
}
}
);

// Logs out user from Chatrix on non-logged in page load, if any session exists in localStorage.
foreach ( array( 'wp_footer', 'login_footer' ) as $footer_hook ) {
add_action(
$footer_hook,
function() {
if ( ! is_user_logged_in() ) {
?>
<script type="text/javascript">
async function invalidateChatrixSession(session) {
await fetch(session.homeserver + '/_matrix/client/v3/logout', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + session.accessToken,
},
});
}
(function() {
for (let i=0; i<localStorage.length; i++) {
let key = localStorage.key(i);
if (!key.startsWith(LOCAL_STORAGE_KEY_PREFIX)) {
continue;
}
this.invalidateChatrixSession(
JSON.parse(localStorage.getItem(key))[0]
);
localStorage.removeItem(key);
}
})();
</script>
<?php
}
}
);
}

// Enqueue the script only when chatrix_configuration filter is set.
add_action(
'wp_enqueue_scripts',
Expand Down