Skip to content

Commit

Permalink
FEATURE: Adds restore button for user impersonation
Browse files Browse the repository at this point in the history
With Neos 8.0 we introduce the impersonation feature. So, it is possible to impersonate as a different user from the user management module.

This change will add related endpoints to the neos-ui to be able to communicate with the Neos.Neos API. The impersonation state will be saved in the Redux store, and a saga handles the restore of the origin user.

Besides the data handling stuff, we also add a new button to the user menu.

Related Neos PR:
neos/neos-development-collection#3648
  • Loading branch information
markusguenther committed Mar 24, 2022
1 parent 20c88da commit ff7a17d
Show file tree
Hide file tree
Showing 10 changed files with 245 additions and 10 deletions.
12 changes: 12 additions & 0 deletions Resources/Private/Fusion/Backend/Root.fusion
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,18 @@ backend = Neos.Fusion:Template {
controller = 'Service\\ContentDimensions'
action = 'index'
}
impersonateStatus = Neos.Fusion:UriBuilder {
package = 'Neos.Neos'
controller = 'Backend\\Impersonate'
action = 'status'
format = 'json'
}
impersonateRestore = Neos.Fusion:UriBuilder {
package = 'Neos.Neos'
controller = 'Backend\\Impersonate'
action = 'restoreWithResponse'
format = 'json'
}
}
modules = Neos.Fusion:DataStructure {
prototype(Neos.Fusion:UriBuilder) {
Expand Down
29 changes: 28 additions & 1 deletion packages/neos-ui-backend-connector/src/Endpoints/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ export interface Routes {
userPreferences: string;
dataSource: string;
contentDimensions: string;
impersonateStatus: string;
impersonateRestore: string;
};
modules: {
workspaces: string;
Expand Down Expand Up @@ -609,6 +611,29 @@ export default (routes: Routes) => {
.then(result => result && result.csrfToken);
};

const impersonateStatus = () => fetchWithErrorHandling.withCsrfToken(() => ({
url: routes.core.service.impersonateStatus,
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
})).then(response => fetchWithErrorHandling.parseJson(response));

const impersonateRestore = () => fetchWithErrorHandling.withCsrfToken(csrfToken => {
const data = new URLSearchParams();
data.set('__csrfToken', csrfToken);

return {
url: routes.core.service.impersonateRestore,
method: 'POST',
credentials: 'include',
body: data
};
})
.then(response => fetchWithErrorHandling.parseJson(response))
.catch(reason => fetchWithErrorHandling.generalErrorHandler(reason));

return {
loadImageMetadata,
change,
Expand Down Expand Up @@ -636,6 +661,8 @@ export default (routes: Routes) => {
getWorkspaceInfo,
getAdditionalNodeMetadata,
tryLogin,
contentDimensions
contentDimensions,
impersonateStatus,
impersonateRestore
};
};
64 changes: 64 additions & 0 deletions packages/neos-ui-redux-store/src/User/Impersonate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {produce} from 'immer';
import {action as createAction, ActionType} from 'typesafe-actions';
import {InitAction} from '@neos-project/neos-ui-redux-store/src/System';
import { WritableDraft } from 'immer/dist/internal';

export interface ImpersonateAccount extends WritableDraft<{
accountIdentifier: string;
fullName: string;
}> {}

export interface State extends Readonly<{
status: boolean;
user?: ImpersonateAccount;
origin?: ImpersonateAccount;
}> {}

export const defaultState: State = {
status: false
};


//
// Export the action types
//
export enum actionTypes {
INIT = '@neos/neos-ui/User/Impersonate/INIT',
FETCH_STATUS = '@neos/neos-ui/User/Impersonate/FETCH_STATUS',
RESTORE = '@neos/neos-ui/User/Impersonate/RESTORE',
}

//
// Export the actions
//
export const actions = {
init: () => createAction(actionTypes.INIT),
fetchStatus: (data: State) => createAction(actionTypes.FETCH_STATUS, data),
restore: () => createAction(actionTypes.RESTORE),
};

//
// Export the union type of all actions
//
export type Action = ActionType<typeof actions>;

export const reducer = (state: State = defaultState, action: Action | InitAction) => produce(state, draft => {
switch (action.type) {
case actionTypes.INIT:
draft.status = false;
break;
case actionTypes.FETCH_STATUS:
draft.status = action.payload.status;
draft.user = action.payload.user;
draft.origin = action.payload.origin;
break;
case actionTypes.RESTORE:
draft.status = false;
break;
}
});

//
// Export the selectors
//
export const selectors = {};
7 changes: 5 additions & 2 deletions packages/neos-ui-redux-store/src/User/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import {combineReducers} from '@neos-project/neos-ui-redux-store/src/combineRedu
import * as Settings from '@neos-project/neos-ui-redux-store/src/User/Settings';
import * as Preferences from '@neos-project/neos-ui-redux-store/src/User/Preferences';
import * as Name from '@neos-project/neos-ui-redux-store/src/User/Name';
import * as Impersonate from '@neos-project/neos-ui-redux-store/src/User/Impersonate';

const all = {Settings, Preferences, Name};
const all = {Settings, Preferences, Name, Impersonate};

//
// Export the subreducer state shape interface
Expand All @@ -13,6 +14,7 @@ export interface State {
settings: Settings.State;
preferences: Preferences.State;
name: Name.State;
impersonate: Impersonate.State;
}

function typedKeys<T>(o: T) : Array<keyof T> {
Expand All @@ -35,7 +37,8 @@ export const actions = typedKeys(all).reduce((acc, cur) => ({...acc, [cur]: all[
export const reducer = combineReducers({
settings: Settings.reducer,
preferences: Preferences.reducer,
name: Name.reducer
name: Name.reducer,
impersonate: Impersonate.reducer
} as any);

//
Expand Down
46 changes: 46 additions & 0 deletions packages/neos-ui-sagas/src/UI/Impersonate/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {put, call, takeEvery} from 'redux-saga/effects';

import {actionTypes, actions} from '@neos-project/neos-ui-redux-store';
import backend from '@neos-project/neos-ui-backend-connector';
import {$get} from 'plow-js';

export function * impersonateRestore({globalRegistry}) {
const {impersonateRestore} = backend.get().endpoints;
const i18nRegistry = globalRegistry.get('i18n');
const errorMessage = i18nRegistry.translate(
'impersonate.error.restoreUser',
'Could not switch back to the original user.',
{},
'Neos.Neos',
'Main'
);

yield takeEvery(actionTypes.User.Impersonate.RESTORE, function * restore(action) {
try {
const feedback = yield call(impersonateRestore, action.payload);
const originUser = $get('origin.accountIdentifier', feedback);
const user = $get('impersonate.accountIdentifier', feedback);
const status = $get('status', feedback);

const restoreMessage = i18nRegistry.translate(
'impersonate.success.restoreUser',
'Switched back from {0} to the orginal user {1}.',
{
0: user,
1: originUser
},
'Neos.Neos',
'Main'
);

if (status) {
yield put(actions.UI.FlashMessages.add('restoreUserImpersonateUser', restoreMessage, 'success'));
} else {
yield put(actions.UI.FlashMessages.add('restoreUserImpersonateUser', errorMessage, 'error'));
}
window.location.reload();
} catch (error) {
yield put(actions.UI.FlashMessages.add('restoreUserImpersonateUser', errorMessage, 'error'));
}
});
}
4 changes: 3 additions & 1 deletion packages/neos-ui-sagas/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as uiEditPreviewMode from './UI/EditPreviewMode/index';
import * as uiInspector from './UI/Inspector/index';
import * as uiPageTree from './UI/PageTree/index';
import * as uiHotkeys from './UI/Hotkeys/index';
import * as impersonate from './UI/Impersonate/index';

module.exports = {
browser,
Expand All @@ -25,5 +26,6 @@ module.exports = {
uiEditPreviewMode,
uiInspector,
uiPageTree,
uiHotkeys
uiHotkeys,
impersonate
};
5 changes: 4 additions & 1 deletion packages/neos-ui-sagas/src/manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
uiEditPreviewMode,
uiInspector,
uiPageTree,
uiHotkeys
uiHotkeys,
impersonate
} from './index';

manifest('main.sagas', {}, globalRegistry => {
Expand Down Expand Up @@ -77,4 +78,6 @@ manifest('main.sagas', {}, globalRegistry => {
sagasRegistry.set('neos-ui/UI/PageTree/watchToggle', {saga: uiPageTree.watchToggle});

sagasRegistry.set('neos-ui/UI/Hotkeys/handleHotkeys', {saga: uiHotkeys.handleHotkeys});

sagasRegistry.set('neos-ui/UI/Impersonate/impersonateRestore', {saga: impersonate.impersonateRestore});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React from 'react';
import PropTypes from 'prop-types';

import {Icon} from '@neos-project/react-ui-components';
import {neos} from '@neos-project/neos-ui-decorators';
import {connect} from 'react-redux';
import {actions} from '@neos-project/neos-ui-redux-store';
import I18n from '@neos-project/neos-ui-i18n';
import {$transform, $get} from 'plow-js';

import buttonTheme from './style.css';

@connect(
$transform({
originUser: $get('user.impersonate.origin'),
user: $get('user.impersonate.user')
}),
{
addFlashMessage: actions.UI.FlashMessages.add,
impersonateRestore: actions.User.Impersonate.restore
}
)
@neos(globalRegistry => ({
i18nRegistry: globalRegistry.get('i18n')
}))
export default class RestoreButtonItem extends React.PureComponent {
static propTypes = {
originUser: PropTypes.object,
user: PropTypes.object,
addFlashMessage: PropTypes.func.isRequired,
impersonateRestore: PropTypes.func.isRequired,
i18nRegistry: PropTypes.object.isRequired
};

render() {
const {originUser, i18nRegistry, impersonateRestore} = this.props;
const title = i18nRegistry.translate(
'impersonate.title.restoreUserButton',
'Switch back to the orginal user account',
{},
'Neos.Neos',
'Main'
);

return (originUser ? (
<li className={buttonTheme.dropDown__item}>
<button
title={title}
onClick={
() => impersonateRestore()
}
>
<Icon
icon="random"
aria-hidden="true"
className={buttonTheme.dropDown__itemIcon}
/>
<I18n
id="impersonate.label.restoreUserButton"
sourceName="Main"
packageKey="Neos.Neos"
fallback={`Back to user "${originUser.fullName}"`}
params={{0: originUser.fullName}}
/>
</button>
</li>
) : null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,26 @@ import {$transform, $get} from 'plow-js';
import {neos} from '@neos-project/neos-ui-decorators';
import Icon from '@neos-project/react-ui-components/src/Icon/';
import DropDown from '@neos-project/react-ui-components/src/DropDown/';
import RestoreButtonItem from './RestoreButtonItem';

import I18n from '@neos-project/neos-ui-i18n';

import style from './style.css';

@connect($transform({
userName: $get('user.name.fullName')
userName: $get('user.name.fullName'),
impersonateStatus: $get('user.impersonate.status')
}))
@neos()
export default class UserDropDown extends PureComponent {
static propTypes = {
userName: PropTypes.string.isRequired
userName: PropTypes.string.isRequired,
impersonateStatus: PropTypes.bool.isRequired
};

render() {
const logoutUri = $get('routes.core.logout', this.props.neos);
const userSettingsUri = $get('routes.core.modules.userSettings', this.props.neos);
const {csrfToken} = document.getElementById('appContainer').dataset;

return (
<div className={style.wrapper}>
<DropDown className={style.dropDown}>
Expand All @@ -47,6 +48,9 @@ export default class UserDropDown extends PureComponent {
<I18n id="userSettings.label" sourceName="Modules" packageKey="Neos.Neos" fallback="User Settings"/>
</a>
</li>
{this.props.impersonateStatus === true ? (
<RestoreButtonItem />
) : null}
</DropDown.Contents>
</DropDown>
</div>
Expand Down
7 changes: 6 additions & 1 deletion packages/neos-ui/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ function * application() {
//
store.dispatch(actions.System.boot());

const {getJsonResource} = backend.get().endpoints;
const {getJsonResource, impersonateStatus} = backend.get().endpoints;

const groupsAndRoles = yield system.getNodeTypes;

Expand Down Expand Up @@ -135,6 +135,11 @@ function * application() {
const mergedState = merge({}, serverState, persistedState);
yield put(actions.System.init(mergedState));

const impersonateState = yield impersonateStatus();
if (impersonateState) {
yield put(actions.User.Impersonate.fetchStatus(impersonateState));
}

//
// Just make sure that everybody does their initialization homework
//
Expand Down

0 comments on commit ff7a17d

Please sign in to comment.