Fix forgot password views

This commit is contained in:
soupette 2019-04-03 17:26:31 +02:00
parent c8d269aeca
commit 59587d02cd
18 changed files with 24 additions and 769 deletions

View File

@ -1,31 +0,0 @@
/**
*
* AdminPage actions
*
*/
import {
GET_ADMIN_DATA,
GET_ADMIN_DATA_SUCCEEDED,
EMIT_EVENT,
} from './constants';
export function getAdminData() {
return {
type: GET_ADMIN_DATA,
};
}
export function getAdminDataSucceeded(data) {
return {
type: GET_ADMIN_DATA_SUCCEEDED,
data,
};
}
export function emitEvent(event, properties) {
return {
type: EMIT_EVENT,
event,
properties,
};
}

View File

@ -1,9 +0,0 @@
/**
*
* AdminPage constants
*
*/
export const GET_ADMIN_DATA = 'app/Admin/GET_ADMIN_DATA';
export const GET_ADMIN_DATA_SUCCEEDED = 'app/Admin/GET_ADMIN_DATA_SUCCEEDED';
export const EMIT_EVENT = 'app/Admin/EMIT_EVENT';

View File

@ -1,375 +0,0 @@
/*
* AdminPage
*
* This is the first thing users see of our AdminPage, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import ReactGA from 'react-ga';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { Switch, Route } from 'react-router-dom';
import { get, includes, isFunction, map, omit } from 'lodash';
import { bindActionCreators, compose } from 'redux';
// Actions required for disabling and enabling the OverlayBlocker
import {
disableGlobalOverlayBlocker,
enableGlobalOverlayBlocker,
} from 'actions/overlayBlocker';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
import OverlayBlocker from 'components/OverlayBlocker';
// Utils
import auth from 'utils/auth';
import { pluginLoaded, updatePlugin } from '../App/actions';
import {
makeSelectAppPlugins,
makeSelectBlockApp,
makeSelectOverlayBlockerProps,
makeSelectIsAppLoading,
makeSelectShowGlobalAppBlocker,
selectHasUserPlugin,
selectPlugins,
} from '../App/selectors';
import injectReducer from '../../utils/injectReducer';
import injectSaga from '../../utils/injectSaga';
// Design
import CTAWrapper from '../../components/CtaWrapper';
import Header from '../../components/Header/index';
import Logout from '../../components/Logout';
import FullStory from '../../components/FullStory';
import ComingSoonPage from '../ComingSoonPage';
import Content from '../Content';
import LocaleToggle from '../LocaleToggle';
import HomePage from '../HomePage/Loadable';
import Marketplace from '../Marketplace/Loadable';
import LeftMenu from '../LeftMenu';
import ListPluginsPage from '../ListPluginsPage/Loadable';
import Onboarding from '../Onboarding';
import NotFoundPage from '../NotFoundPage/Loadable';
import PluginPage from '../PluginPage';
import { emitEvent, getAdminData } from './actions';
import reducer from './reducer';
import saga from './saga';
import selectAdminPage from './selectors';
import styles from './styles.scss';
const PLUGINS_TO_BLOCK_PRODUCTION = [
'content-type-builder',
'settings-manager',
];
export class AdminPage extends React.Component {
// eslint-disable-line react/prefer-stateless-function
state = { hasAlreadyRegistereOtherPlugins: false };
getChildContext = () => ({
currentEnvironment: this.props.adminPage.currentEnvironment,
disableGlobalOverlayBlocker: this.props.disableGlobalOverlayBlocker,
emitEvent: this.props.emitEvent,
enableGlobalOverlayBlocker: this.props.enableGlobalOverlayBlocker,
plugins: this.props.plugins,
updatePlugin: this.props.updatePlugin,
});
componentDidMount() {
this.props.getAdminData();
this.checkLogin(this.props);
ReactGA.initialize('UA-54313258-9');
}
componentDidUpdate(prevProps) {
const {
adminPage: { uuid },
location: { pathname },
plugins,
} = this.props;
if (prevProps.location.pathname !== pathname) {
this.checkLogin(this.props);
if (uuid) {
ReactGA.pageview(pathname);
}
}
const hasAdminPath = ['users-permissions', 'hasAdminUser'];
if (
get(prevProps.plugins.toJS(), hasAdminPath) !==
get(plugins.toJS(), hasAdminPath)
) {
this.checkLogin(this.props, true);
}
if (
!this.hasUserPluginLoaded(prevProps) &&
this.hasUserPluginLoaded(this.props)
) {
this.checkLogin(this.props);
}
}
checkLogin = (props, skipAction = false) => {
if (props.hasUserPlugin && this.isUrlProtected(props) && !auth.getToken()) {
if (!this.hasUserPluginLoaded(props)) {
return;
}
const endPoint = this.hasAdminUser(props) ? 'login' : 'register';
this.props.history.push(`/plugins/users-permissions/auth/${endPoint}`);
}
if (
!this.isUrlProtected(props) &&
includes(props.location.pathname, 'auth/register') &&
this.hasAdminUser(props) &&
!skipAction
) {
this.props.history.push('/plugins/users-permissions/auth/login');
}
if (
props.hasUserPlugin &&
!this.isUrlProtected(props) &&
!includes(props.location.pathname, 'auth/register') &&
!this.hasAdminUser(props)
) {
this.props.history.push('/plugins/users-permissions/auth/register');
}
if (
!props.hasUserPlugin ||
(auth.getToken() && !this.state.hasAlreadyRegistereOtherPlugins)
) {
map(
omit(this.props.plugins.toJS(), ['users-permissions', 'email']),
plugin => {
switch (true) {
case isFunction(plugin.bootstrap) &&
isFunction(plugin.pluginRequirements):
plugin
.pluginRequirements(plugin)
.then(plugin => {
return plugin.bootstrap(plugin);
})
.then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.pluginRequirements):
plugin
.pluginRequirements(plugin)
.then(plugin => this.props.pluginLoaded(plugin));
break;
case isFunction(plugin.bootstrap):
plugin
.bootstrap(plugin)
.then(plugin => this.props.pluginLoaded(plugin));
break;
default:
}
},
);
this.setState({ hasAlreadyRegistereOtherPlugins: true });
}
};
hasUserPluginInstalled = () => {
const { appPlugins } = this.props;
return appPlugins.indexOf('users-permissions') !== -1;
};
hasUserPluginLoaded = props =>
typeof get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']) !==
'undefined';
hasAdminUser = props =>
get(props.plugins.toJS(), ['users-permissions', 'hasAdminUser']);
isUrlProtected = props =>
!includes(
props.location.pathname,
get(props.plugins.toJS(), ['users-permissions', 'nonProtectedUrl']),
);
shouldDisplayLogout = () =>
auth.getToken() &&
this.props.hasUserPlugin &&
this.isUrlProtected(this.props);
showLeftMenu = () =>
!includes(this.props.location.pathname, 'users-permissions/auth/');
showLoading = () => {
const {
isAppLoading,
adminPage: { isLoading },
} = this.props;
return (
isAppLoading ||
isLoading ||
(this.hasUserPluginInstalled() && !this.hasUserPluginLoaded(this.props))
);
};
retrievePlugins = () => {
const {
adminPage: { currentEnvironment },
plugins,
} = this.props;
if (currentEnvironment === 'production') {
let pluginsToDisplay = plugins;
PLUGINS_TO_BLOCK_PRODUCTION.map(
plugin => (pluginsToDisplay = pluginsToDisplay.delete(plugin)),
);
return pluginsToDisplay;
}
return plugins;
};
renderMarketPlace = props => <Marketplace {...props} {...this.props} />;
render() {
const { adminPage } = this.props;
const header = this.showLeftMenu() ? <Header /> : '';
const style = this.showLeftMenu() ? {} : { width: '100%' };
if (this.showLoading()) {
return <LoadingIndicatorPage />;
}
return (
<div className={styles.adminPage}>
{this.props.adminPage.uuid ? <FullStory org="GK708" /> : ''}
{this.showLeftMenu() && (
<LeftMenu
plugins={this.retrievePlugins()}
layout={adminPage.layout}
version={adminPage.strapiVersion}
/>
)}
<CTAWrapper>
{this.shouldDisplayLogout() && <Logout />}
<LocaleToggle isLogged={this.shouldDisplayLogout() === true} />
</CTAWrapper>
<div className={styles.adminPageRightWrapper} style={style}>
{header}
<Content {...this.props} showLeftMenu={this.showLeftMenu()}>
<Switch>
<Route path="/" component={HomePage} exact />
<Route path="/plugins/:pluginId" component={PluginPage} />
<Route path="/plugins" component={ComingSoonPage} />
<Route path="/list-plugins" component={ListPluginsPage} exact />
<Route
path="/marketplace"
render={this.renderMarketPlace}
exact
/>
<Route path="/configuration" component={ComingSoonPage} exact />
<Route path="" component={NotFoundPage} />
<Route path="404" component={NotFoundPage} />
</Switch>
</Content>
</div>
<OverlayBlocker
isOpen={this.props.blockApp && this.props.showGlobalAppBlocker}
{...this.props.overlayBlockerData}
/>
{this.shouldDisplayLogout() && <Onboarding />}
</div>
);
}
}
AdminPage.childContextTypes = {
currentEnvironment: PropTypes.string.isRequired,
emitEvent: PropTypes.func,
disableGlobalOverlayBlocker: PropTypes.func,
enableGlobalOverlayBlocker: PropTypes.func,
plugins: PropTypes.object,
updatePlugin: PropTypes.func,
};
AdminPage.contextTypes = {
emitEvent: PropTypes.func,
router: PropTypes.object.isRequired,
};
AdminPage.defaultProps = {
adminPage: {},
appPlugins: [],
hasUserPlugin: true,
isAppLoading: true,
overlayBlockerData: {},
};
AdminPage.propTypes = {
adminPage: PropTypes.object,
appPlugins: PropTypes.array,
blockApp: PropTypes.bool.isRequired,
disableGlobalOverlayBlocker: PropTypes.func.isRequired,
emitEvent: PropTypes.func.isRequired,
enableGlobalOverlayBlocker: PropTypes.func.isRequired,
getAdminData: PropTypes.func.isRequired,
hasUserPlugin: PropTypes.bool,
history: PropTypes.object.isRequired,
isAppLoading: PropTypes.bool,
location: PropTypes.object.isRequired,
overlayBlockerData: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
pluginLoaded: PropTypes.func.isRequired,
plugins: PropTypes.object.isRequired,
showGlobalAppBlocker: PropTypes.bool.isRequired,
updatePlugin: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
adminPage: selectAdminPage(),
appPlugins: makeSelectAppPlugins(),
blockApp: makeSelectBlockApp(),
overlayBlockerData: makeSelectOverlayBlockerProps(),
hasUserPlugin: selectHasUserPlugin(),
isAppLoading: makeSelectIsAppLoading(),
plugins: selectPlugins(),
showGlobalAppBlocker: makeSelectShowGlobalAppBlocker(),
});
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
disableGlobalOverlayBlocker,
emitEvent,
enableGlobalOverlayBlocker,
getAdminData,
pluginLoaded,
updatePlugin,
},
dispatch,
);
}
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
const withReducer = injectReducer({ key: 'adminPage', reducer });
const withSaga = injectSaga({ key: 'adminPage', saga });
export default compose(
withReducer,
withSaga,
withConnect,
)(AdminPage);

View File

@ -1,37 +0,0 @@
/**
*
* AdminPage reducer
*
*/
import { fromJS, Map } from 'immutable';
import {
GET_ADMIN_DATA_SUCCEEDED,
} from './constants';
const initialState = fromJS({
uuid: false,
currentEnvironment: 'development',
isLoading: true,
layout: Map({}),
strapiVersion: '3',
eventName: '',
shouldEmit: true,
});
function adminPageReducer(state = initialState, action) {
switch (action.type) {
case GET_ADMIN_DATA_SUCCEEDED:
return state
.update('uuid', () => action.data.uuid)
.update('currentEnvironment', () => action.data.currentEnvironment)
.update('layout', () => Map(action.data.layout))
.update('strapiVersion', () => action.data.strapiVersion)
.update('isLoading', () => false);
default:
return state;
}
}
export default adminPageReducer;

View File

@ -1,64 +0,0 @@
import { all, fork, call, put, select, takeLatest } from 'redux-saga/effects';
import auth from 'utils/auth';
import request from 'utils/request';
import { makeSelectAppPlugins } from '../App/selectors';
import {
getAdminDataSucceeded,
} from './actions';
import { makeSelectUuid } from './selectors';
import { EMIT_EVENT, GET_ADMIN_DATA } from './constants';
function* emitter(action) {
try {
const requestURL = 'https://analytics.strapi.io/track';
const uuid = yield select(makeSelectUuid());
const { event, properties } = action;
if (uuid) {
yield call(
fetch, // eslint-disable-line no-undef
requestURL,
{
method: 'POST',
body: JSON.stringify({ event, uuid, properties }),
headers: {
'Content-Type': 'application/json',
},
},
);
}
} catch(err) {
console.log(err); // eslint-disable-line no-console
}
}
function* getData() {
try {
const appPlugins = yield select(makeSelectAppPlugins());
const hasUserPlugin = appPlugins.indexOf('users-permissions') !== -1;
if (hasUserPlugin && auth.getToken() !== null) {
yield call(request, `${strapi.backendURL}/users/me`, { method: 'GET' });
}
const [{ uuid }, { strapiVersion }, { currentEnvironment }, { layout }] = yield all([
call(request, '/admin/gaConfig', { method: 'GET' }),
call(request, '/admin/strapiVersion', { method: 'GET' }),
call(request, '/admin/currentEnvironment', { method: 'GET' }),
call(request, '/admin/layout', { method: 'GET' }),
]);
yield put(getAdminDataSucceeded({ uuid, strapiVersion, currentEnvironment, layout }));
} catch(err) {
console.log(err); // eslint-disable-line no-console
}
}
function* defaultSaga() {
yield all([
fork(takeLatest, GET_ADMIN_DATA, getData),
fork(takeLatest, EMIT_EVENT, emitter),
]);
}
export default defaultSaga;

View File

@ -1,28 +0,0 @@
/**
*
* AdminPage selectors
*/
import { createSelector } from 'reselect';
/**
* Direct selector to the homePage state domain
*/
const selectAdminPageDomain = () => state => state.get('adminPage');
/**
* Default selector used by HomePage
*/
const makeSelectUuid = () => createSelector(
selectAdminPageDomain(),
substate => substate.get('uuid'),
);
const selectAdminPage = () => createSelector(
selectAdminPageDomain(),
(substate) => substate.toJS(),
);
export default selectAdminPage;
export { makeSelectUuid };

View File

@ -1,18 +0,0 @@
/* Import */
@import '../../styles/variables/variables';
.adminPage { /* stylelint-disable */
display: flex;
overflow-x: hidden;
}
.adminPageRightWrapper {
width: calc(100% - #{$left-menu-width});
}
.adminPageSeparator {
height: 6rem;
display: flex;
flex-direction: column;
justify-content: center;
}

View File

@ -1,8 +0,0 @@
import Loadable from 'react-loadable';
import LoadingIndicatorPage from 'components/LoadingIndicatorPage';
export default Loadable({
loader: () => import('./index'),
loading: LoadingIndicatorPage,
});

View File

@ -1,74 +0,0 @@
/*
*
* PluginPage
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createSelector } from 'reselect';
import BlockerComponent from 'components/BlockerComponent';
import ErrorBoundary from 'components/ErrorBoundary';
import { selectPlugins } from '../App/selectors';
export class PluginPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
let pluginName;
// Detect plugin id from url params
const pluginId = this.props.match.params.pluginId;
const plugins = this.props.plugins.toJS();
const containers = Object.keys(plugins).map((name) => {
const plugin = plugins[name];
if (plugin.id === pluginId) {
pluginName = plugin.name;
const blockerComponentProps = plugin.preventComponentRendering ? plugin.blockerComponentProps : {};
let Elem = plugin.preventComponentRendering ? BlockerComponent : plugin.mainComponent;
if (plugin.preventComponentRendering && plugin.blockerComponent) {
Elem = plugin.blockerComponent;
}
return (
<ErrorBoundary key={plugin.id}>
<Elem {...this.props} {...blockerComponentProps} />
</ErrorBoundary>
);
}
});
return (
<div>
<Helmet
title={`Strapi - ${pluginName}`}
/>
{containers}
</div>
);
}
}
PluginPage.propTypes = {
match: PropTypes.object.isRequired,
plugins: PropTypes.object.isRequired,
};
const mapStateToProps = createSelector(
selectPlugins(),
(plugins) => ({ plugins })
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(PluginPage);

View File

@ -19,16 +19,13 @@ const LoadableApp = Loadable({
loading: LoadingIndicatorPage,
});
const tryRequireRoot = source => {
try {
return require('../../../../admin/src/' + source + '.js').default; // eslint-disable-line prefer-template
} catch (err) {
return null;
}
};
const bootstrap = tryRequireRoot('bootstrap');
const pluginRequirements = tryRequireRoot('requirements');
// const tryRequireRoot = source => {
// try {
// return require('../../../../admin/src/' + source + '.js').default; // eslint-disable-line prefer-template
// } catch (err) {
// return null;
// }
// };
const layout = (() => {
try {
@ -71,7 +68,9 @@ if (module.hot) {
if (strapi) {
System.import('./i18n').then(result => {
const translationMessagesUpdated = result.translationMessages;
strapi.refresh(pluginId).translationMessages(translationMessagesUpdated);
strapi
.refresh(pluginId)
.translationMessages(translationMessagesUpdated);
});
}
});
@ -99,7 +98,6 @@ const lifecycles = (() => {
strapi.registerPlugin({
blockerComponent: null,
blockerComponentProps: {},
bootstrap,
description: pluginDescription,
icon: pluginPkg.strapi.icon,
id: pluginId,
@ -110,7 +108,6 @@ strapi.registerPlugin({
leftMenuLinks: [],
mainComponent: Comp,
name: pluginPkg.strapi.name,
pluginRequirements,
preventComponentRendering: false,
translationMessages,
});

View File

@ -1,27 +0,0 @@
import { map, omit } from 'lodash';
import request from 'utils/request';
// This method is executed before the load of the plugin
const bootstrap = plugin =>
new Promise((resolve, reject) => {
request('/content-manager/models', { method: 'GET' })
.then(models => {
const menu = [
{
name: 'Content Types',
links: map(omit(models.models.models, 'plugins'), (model, key) => ({
label: model.labelPlural || model.label || key,
destination: key,
})),
},
];
plugin.leftMenuSections = menu;
resolve(plugin);
})
.catch(e => {
strapi.notification.error('content-manager.error.model.fetch');
reject(e);
});
});
export default bootstrap;

View File

@ -1,3 +0,0 @@
const shouldRenderCompo = (plugin) => Promise.resolve(plugin);
export default shouldRenderCompo;

View File

@ -1,3 +0,0 @@
const bootstrap = (plugin) => Promise.resolve(plugin);
export default bootstrap;

View File

@ -1,19 +0,0 @@
import request from 'utils/request';
const shouldRenderCompo = (plugin) => new Promise((resolve, reject) => {
request(`${strapi.backendURL}/content-type-builder/autoReload`)
.then(response => {
plugin.preventComponentRendering = !response.autoReload.enabled;
plugin.blockerComponentProps = {
blockerComponentTitle: 'components.AutoReloadBlocker.header',
blockerComponentDescription: 'components.AutoReloadBlocker.description',
blockerComponentIcon: 'fa-refresh',
blockerComponentContent: 'renderIde',
};
return resolve(plugin);
})
.catch(err => reject(err));
});
export default shouldRenderCompo;

View File

@ -1,3 +0,0 @@
const bootstrap = (plugin) => Promise.resolve(plugin);
export default bootstrap;

View File

@ -1,29 +0,0 @@
import request from 'utils/request';
const shouldRenderCompo = (plugin) => new Promise((resolve, reject) => {
request('/settings-manager/autoReload')
.then(response => {
plugin.preventComponentRendering = !response.autoReload.enabled;
plugin.blockerComponentProps = {
blockerComponentTitle: 'components.AutoReloadBlocker.header',
blockerComponentDescription: 'components.AutoReloadBlocker.description',
blockerComponentIcon: 'fa-refresh',
blockerComponentContent: 'renderIde',
};
if (response.environment !== 'development') {
plugin.preventComponentRendering = true;
plugin.blockerComponentProps = {
blockerComponentTitle: 'components.ProductionBlocker.header',
blockerComponentDescription: 'components.ProductionBlocker.description',
blockerComponentIcon: 'fa-ban',
blockerComponentContent: 'renderButton',
};
}
return resolve(plugin);
})
.catch(err => reject(err));
});
export default shouldRenderCompo;

View File

@ -1,24 +0,0 @@
import request from 'utils/request';
// This method is executed before the load of the plugin
const bootstrap = (plugin) => new Promise((resolve, reject) => {
request('/users-permissions/init')
.then(response => {
plugin.hasAdminUser = response.hasAdmin;
plugin.nonProtectedUrl = '/plugins/users-permissions/auth';
// Add Users to Content Types section.
plugin.leftMenuSections.push({
links: [{
label: 'Users',
destination: 'user',
plugin: 'content-manager',
}],
name: 'Content Types',
});
return resolve(plugin);
})
.catch(err => reject(err));
});
export default bootstrap;

View File

@ -1,4 +1,3 @@
const { includes } = require('lodash');
const auth = require('utils/auth').default;
module.exports = function willSecure() {
@ -23,9 +22,11 @@ module.exports = function willSecure() {
shouldSecureAfterAllPluginsAreMounted: false,
});
const initializerReducer = store.getState().getIn(['users-permissions_initializer']);
const initializerReducer = store
.getState()
.getIn(['users-permissions_initializer']);
const nonProtectedURLs = ['/plugins/users-permissions/auth'];
const nonProtectedURLs = '/plugins/users-permissions/auth';
const redirectEndPoint = initializerReducer.get('hasAdminUser')
? '/plugins/users-permissions/auth/login'
: '/plugins/users-permissions/auth/register';
@ -39,7 +40,7 @@ module.exports = function willSecure() {
return cb();
}
if (!includes(nonProtectedURLs, pathname)) {
if (!pathname.includes(nonProtectedURLs)) {
hideLeftMenu();
hideLogout();
setLocaleCustomClassName('localeDropdownMenuNotLogged'); // NOTE: Temporary should be removed when we switch to administrators
@ -62,6 +63,15 @@ module.exports = function willSecure() {
return cb();
}
if (pathname.includes(nonProtectedURLs)) {
hideLeftMenu();
hideLogout();
setLocaleCustomClassName('localeDropdownMenuNotLogged'); // NOTE: Temporary should be removed when we switch to administrators
unsetAppSecured();
return cb();
}
resetLocaleDefaultClassName(); // NOTE: Temporary should be removed when we switch to administrators
showLeftMenu();
showLogout();