updated React-App to React as of Spring 2020

This commit is contained in:
Godmar Back 2020-04-30 11:40:47 -04:00
parent cd09eb1954
commit b0f08b3e8a
19 changed files with 11568 additions and 8240 deletions

19242
react-app/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,20 +1,24 @@
{
"name": "react-app",
"version": "0.1.0",
"version": "0.2.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"bootstrap": "^4.1.0",
"formik": "^0.11.11",
"formik": "2.1.4",
"prop-types": "^15.6.1",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.4",
"reactstrap": "^5.0.0",
"react-redux": "7.2.0",
"react-router-dom": "5.1.2",
"react-script": "^2.0.5",
"react-scripts": "3.4.1",
"reactstrap": "8.4.1",
"redux": "^4.0.0",
"redux-thunk": "^2.2.0",
"superagent": "^3.8.2",
"superagent": "5.2.2",
"toastr": "^2.1.4"
},
"scripts": {
@ -23,5 +27,17 @@
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:9999/"
"proxy": "http://localhost:9999/",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -1,3 +1,6 @@
https://reacttraining.com/react-router/web/guides/redux-integration
Updated Spring 2020 to React 16.13.1 and react-redux 7.2.0

View File

@ -14,6 +14,9 @@ export function login(username, password) {
onSuccess(dispatch, data, getState) {
toastr.success(`Success logging in: ${JSON.stringify(data)}`);
},
onError(dispatch, data, getState) {
toastr.success(`Error logging in: ${JSON.stringify(data && data.response && data.response.text)}`);
},
});
}

View File

@ -1,17 +1,14 @@
import React from 'react';
import React, { useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import store from '../store';
class Logout extends React.Component {
componentWillMount() {
// normally, we would inform the server just in case.
document.cookie = "auth_token=";
const Logout = () => {
// normally, we would inform the server just in case.
document.cookie = "auth_token=";
useEffect(() => {
store.dispatch({ type: "LOGOUT" });
}
render() {
return (<Redirect to="/" />);
}
}
}, []);
return (<Redirect to="/" />);
};
export default Logout;

View File

@ -1,5 +1,4 @@
import React from 'react';
import PropTypes from 'prop-types';
import React, { useState } from 'react';
import {
Collapse,
Navbar,
@ -55,69 +54,50 @@ const DropDowns = (props) => {
/**
* Navigation bar component
*/
class NavBar extends React.Component {
static propTypes = {
menus: PropTypes.object,
user: PropTypes.object,
branding: PropTypes.string,
}
const NavBar = (props) => {
let [isOpen, setOpen] = useState(false);
constructor(props) {
super(props);
const menus = props.menus
const user = props.user
const toggle = () => { setOpen(!isOpen); }
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
return (
<div>
<Navbar color="light" light expand="md">
<NavbarToggler onClick={toggle} />
<NavbarBrand to="/">{props.branding}</NavbarBrand>
<Collapse isOpen={isOpen} navbar>
<Nav className="mr-auto" navbar>
{menus.topbar.map((item) =>
<NavItem key={item.path}>
<NavLink to={item.path} activeClassName="active" tag={RRNavLink}>
{item.label}
</NavLink>
</NavItem>
)}
{menus.leftdropdowns &&
<DropDowns className="mr-auto" dropdowns={menus.leftdropdowns} user={user} />
}
</Nav>
<Nav className="ml-auto">
{menus.rightdropdowns &&
<DropDowns className="ml-auto" dropdowns={menus.rightdropdowns} user={user} />
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
const menus = this.props.menus
const user = this.props.user
return (
<div>
<Navbar color="light" light expand="md">
<NavbarToggler onClick={this.toggle} />
<NavbarBrand to="/">{this.props.branding}</NavbarBrand>
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="mr-auto" navbar>
{menus.topbar.map((item) =>
<NavItem key={item.path}>
<NavLink to={item.path} activeClassName="active" tag={RRNavLink}>
{item.label}
</NavLink>
</NavItem>
)}
{ menus.leftdropdowns &&
<DropDowns className="mr-auto" dropdowns={menus.leftdropdowns} user={user} />
}
</Nav>
<Nav className="ml-auto">
{ menus.rightdropdowns &&
<DropDowns className="ml-auto" dropdowns={menus.rightdropdowns} user={user} />
}
{isLoaded(user) ?
<NavItem>
<NavLink activeClassName="active" tag={RRNavLink} to={this.props.logoutUrl}>Logout ({user.sub})</NavLink>
</NavItem>
:
<NavItem>
<NavLink activeClassName="active" tag={RRNavLink} to={this.props.loginUrl}>Login</NavLink>
</NavItem>
}
</Nav>
</Collapse>
</Navbar>
</div>
);
}
{isLoaded(user) ?
<NavItem>
<NavLink activeClassName="active" tag={RRNavLink} to={props.logoutUrl}>Logout ({user.sub})</NavLink>
</NavItem>
:
<NavItem>
<NavLink activeClassName="active" tag={RRNavLink} to={props.loginUrl}>Login</NavLink>
</NavItem>
}
</Nav>
</Collapse>
</Navbar>
</div>
);
}
export default NavBar;

View File

@ -3,80 +3,70 @@ import { Row, Label, Input, Alert, Button, ButtonToolbar, Form, FormGroup } from
import { withFormik } from 'formik';
/*
* This is a connected form that display username/password.
* This is a form that display username/password.
* When the user hits submit, the 'onSubmit' method is called
* in the parent, which receives the username/password the user
* entered. It also performs validation.
*/
class LoginForm extends React.Component {
render() {
const {
handleSubmit, // rest is from HOC
isSubmitting,
handleReset,
handleBlur,
handleChange,
// errors,
dirty,
// touched,
values,
// valid
} = this.props;
const LoginForm = (props) => {
const {
handleSubmit, // rest is from HOC
isSubmitting,
handleReset,
handleBlur,
handleChange,
// errors,
dirty,
// touched,
values,
// valid
} = props;
return (
<Form onSubmit={handleSubmit}>
<Row>
return (
<Form onSubmit={handleSubmit}>
<Row>
<FormGroup>
<Label for="username">User Name</Label>
<Input type="text" name="username" value={values.username}
onChange={handleChange}
onBlur={handleBlur}
/>
</FormGroup>
<FormGroup>
<Label for="password">Password</Label>
<Input type="password" name="password"
onChange={handleChange}
onBlur={handleBlur}
/>
</FormGroup>
{ props.autherror &&
<FormGroup>
<Label for="username">User Name</Label>
<Input type="text" name="username" value={values.username}
onChange={handleChange}
onBlur={handleBlur}
/>
</FormGroup>
<FormGroup>
<Label for="password">Password</Label>
<Input type="password" name="password"
onChange={handleChange}
onBlur={handleBlur}
/>
<Alert bsstyle='danger'>
{props.autherror.message || 'Login failed'}
</Alert>
</FormGroup>
}
</Row>
{ this.props.autherror &&
<FormGroup>
<Alert bsstyle='danger'>
{this.props.autherror.message || 'Login failed'}
</Alert>
</FormGroup>
}
</Row>
<Row>
<ButtonToolbar>
<Button
type='submit'
bsstyle='success' className="mr-2">
Submit
</Button>
<Button
type="button"
onClick={handleReset}
disabled={!dirty || isSubmitting}>
Reset
</Button>
</ButtonToolbar>
</Row>
</Form>
);
}
}
/*
function mapStateToProps(state) {
return {
autherror: state.auth.error
};
}
*/
<Row>
<ButtonToolbar>
<Button
type='submit'
bsstyle='success' className="mr-2">
Submit
</Button>
<Button
type="button"
onClick={handleReset}
disabled={!dirty || isSubmitting}>
Reset
</Button>
</ButtonToolbar>
</Row>
</Form>
);
};
export default withFormik({
mapPropsToValues: () => ({ username: '', password: '' }),

View File

@ -1,42 +0,0 @@
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { isLoaded } from '../util/loadingObject';
// From https://github.com/gillisd/react-router-v4-redux-auth
const PrivateRoute = ({component: ComposedComponent, ...rest}) => {
class Authentication extends React.Component {
// redirect if not authenticated; otherwise,
// return the component input into <PrivateRoute />
handleRender(props) {
if (!this.props.authenticated) {
return <Redirect to={{
pathname: '/login',
state: {
from: props.location
}
}}/>
} else {
return <ComposedComponent {...props}/>
}
}
render() {
return (
<Route {...rest} render={this.handleRender.bind(this)}/>
)
}
}
function mapStateToProps(state) {
return {authenticated: isLoaded(state.auth)};
}
const AuthenticationContainer = connect(mapStateToProps)(Authentication)
return <AuthenticationContainer/>
}
export { PrivateRoute };

View File

@ -3,13 +3,13 @@ const publicUrl = process.env.PUBLIC_URL
const menus = {
topbar : [
{ path: `${publicUrl}/`, label: "Home" },
{ path: `/`, label: "Home" },
],
leftdropdowns : [
{
label: "Public",
entries: [
{ path: `${publicUrl}/public`, label: "Public Content" }
{ path: `/public`, label: "Public Content" }
]
}
],
@ -18,7 +18,7 @@ const menus = {
label: "Private",
onlyifauthenticated: true,
entries: [
{ path: `${publicUrl}/protected`, label: "Private Content" }
{ path: `/protected`, label: "Private Content" }
]
}
]

View File

@ -7,7 +7,6 @@ import PublicPage from '../pages/PublicPage';
import NotFoundPage from '../pages/NotFoundPage';
import HomePage from '../pages/HomePage';
import PrivatePage from '../pages/PrivatePage';
import { PrivateRoute } from '../components/privateroute';
import { Switch, Route, withRouter } from 'react-router-dom';
@ -17,30 +16,26 @@ import config from '../config/';
* children in the main part of the page. Its children will
* be chosen based on the selected route.
*/
class AppContainer extends React.Component {
render() {
return (
<div>
<TopNavBar branding="CS3214 Demo App"
menus={config.menus}
user={this.props.user}
loginUrl={`${config.publicUrl}/login`}
logoutUrl={`${config.publicUrl}/logout`}
/>
<div className="container-fluid marketing">
<Switch>
<Route exact path={`${config.publicUrl}/`} component={HomePage} />
<Route path={`${config.publicUrl}/logout`} component={Logout} />
<Route path={`${config.publicUrl}/login`} component={LoginPage} />
<Route path={`${config.publicUrl}/public`} component={PublicPage} />
<PrivateRoute path={`${config.publicUrl}/protected`} component={PrivatePage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</div>
);
}
}
const AppContainer = (props) => (
<div>
<TopNavBar branding="CS3214 Demo App 2020"
menus={config.menus}
user={props.user}
loginUrl={`/login`}
logoutUrl={`/logout`}
/>
<div className="container-fluid marketing">
<Switch>
<Route exact path={`/`} component={HomePage} />
<Route path={`/logout`} component={Logout} />
<Route path={`/login`} component={LoginPage} />
<Route path={`/public`} component={PublicPage} />
<Route path={`/protected`} component={PrivatePage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</div>
);
function mapStateToProps(state) {
return {

View File

@ -0,0 +1,36 @@
/*
* This HOC can be used to wrap components so that if they are rendered without authentication,
* they redirect to '/login' first and then come back.
*/
import React from 'react';
import { Redirect, withRouter } from 'react-router';
import { connect } from 'react-redux';
import { isLoaded } from '../util/loadingObject';
function mapStateToProps(state) {
return {
user: state.auth
};
}
export default function RequireAuthentication(Component) {
const wrapper = props => {
if (isLoaded(props.user)) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: `/login`,
state: {
from: props.history.location
}
}}
/>
);
}
};
return withRouter(connect(mapStateToProps)(wrapper));
}

View File

@ -13,6 +13,7 @@ import jQuery from 'jquery'; // for toastr;
import AppContainer from './containers/AppContainer';
import store from './store';
import {checklogin} from './actions/auth';
import config from './config';
toastr.options.closeButton = true;
toastr.options.positionClass = 'toast-bottom-right';
@ -23,7 +24,7 @@ store.dispatch(checklogin());
const mountPoint = document.getElementById('root');
const rootNode = (
<Provider store={store}>
<Router>
<Router basename={config.publicUrl}>
<AppContainer />
</Router>
</Provider>

View File

@ -1,32 +1,27 @@
import React from 'react';
import { Container, Row, Col } from 'reactstrap';
import { Link } from 'react-router-dom';
import config from '../config/';
import logo from './logo.svg';
class HomePage extends React.Component {
render() {
return (
<Container>
<h1>CS3214 Demo App</h1>
<img alt="" src={logo} className="app-logo" />
<Row>
<Col>
<p>
This small <a href="https://reactjs.org/">React {React.version}</a> app
let HomePage = (props) => (
<Container>
<h1>CS3214 Demo App</h1>
<img alt="" src={logo} className="app-logo" />
<Row>
<Col>
<p>
This small <a href="https://reactjs.org/">React {React.version}</a> app
shows how to use the JWT authentication facilities of your
server in a progressive single-page web application.
</p>
</Col>
</Row>
<Row>
<Col>
Click <Link to={`${config.publicUrl}/protected`}>here</Link> to
</Col>
</Row>
<Row>
<Col>
Click <Link to={`/protected`}>here</Link> to
navigate to a protected section of the app.
</Col>
</Row>
</Container>);
}
}
</Row>
</Container >);
export default HomePage

View File

@ -1,6 +1,5 @@
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { Card, CardHeader, CardBody, Container, Row, Col } from 'reactstrap';
import { login } from '../actions/auth.js';
@ -8,28 +7,20 @@ import { isLoading, isLoaded } from '../util/loadingObject'
import LoginForm from '../components/forms/LoginForm';
import { Redirect } from 'react-router-dom';
class LoginPage extends React.Component {
static contextTypes = {
router: PropTypes.object.isRequired
const LoginPage = (props) => {
let dispatch = useDispatch();
function doLogin({username, password}) {
dispatch(login(username, password));
}
static propTypes = {
user: PropTypes.object.isRequired
const user = useSelector(state => state.auth);
const isAuthenticated = isLoaded(user);
const { from } = props.location.state || { from: { pathname: "/" } };
if (isAuthenticated) {
return (<Redirect to={from} />);
}
doLogin({username, password}) {
this.props.dispatch(login(username, password));
}
render() {
const user = this.props.user;
const isAuthenticated = isLoaded(user);
const { from } = this.props.location.state || { from: { pathname: "/" } };
if (isAuthenticated) {
return (<Redirect to={from} />);
}
return (
return (
<Container>
<Row className="pb-5 pt-5">
<Col xsoffset={0} xs={10} smoffset={4} sm={4}>
@ -39,21 +30,12 @@ class LoginPage extends React.Component {
<LoginForm
loading={isLoading(user)}
autherror={user.error}
onSubmit={v => this.doLogin(v)} />
onSubmit={v => doLogin(v)} />
</CardBody>
</Card>
</Col>
</Row>
</Container>
);
}
</Container>);
}
function mapStateToProps(state) {
return {
user: state.auth
};
}
export default connect(mapStateToProps)(LoginPage);
export default LoginPage;

View File

@ -4,12 +4,12 @@ import React from 'react';
* See https://facebook.github.io/react/docs/reusable-components.html#stateless-functions
*/
const NotFound = (props) =>
<div><h1>Route not found Error</h1>
(<div><h1>Route not found Error</h1>
<div>
Something went wrong: {window.location.pathname} could not be found!
</div>
{/* JSON.stringify(props) */}
</div>
</div>);
export default NotFound

View File

@ -1,21 +1,24 @@
import React from 'react';
import { useSelector } from 'react-redux';
import { Container } from 'reactstrap';
import RequireAuthentication from '../containers/RequireAuthentication';
class PrivatePage extends React.Component {
render() {
return (
<Container>
<h1>Welcome to a private page</h1>
<div>
You have successfully authenticated.
</div>
<div>
This page is "private" only inasmuch as the front-end does not
display it to unauthenticated users. In a fully-fledged app,
this page would now perform API requests that require authentication.
</div>
</Container>);
}
const PrivatePage = () => {
let user = useSelector(state => state.auth);
return (<Container>
<h1>Welcome to a private page</h1>
<div>
You have successfully authenticated as user <tt>{user.sub}</tt>.
Your token was issued at {new Date(user.iat*1000).toString()},
it expires {new Date(user.exp*1000).toString()}
</div>
<div>
This page is "private" only inasmuch as the front-end does not
display it to unauthenticated users. In a fully-fledged app,
this page would now perform API requests that require authentication.
</div>
</Container>);
}
export default PrivatePage
export default RequireAuthentication(PrivatePage);

View File

@ -1,16 +1,12 @@
import React from 'react';
import { Container } from 'reactstrap';
class PublicPage extends React.Component {
render() {
return (
<Container>
<h1>Welcome to a public page</h1>
<div>
This public page is accessible to anyone.
const PublicPage = () => (
<Container>
<h1>Welcome to a public page</h1>
<div>
This public page is accessible to anyone.
</div>
</Container>);
}
}
</Container>);
export default PublicPage
export default PublicPage;

View File

@ -20,7 +20,7 @@ const checkloginHandler = asyncHandler('CHECKLOGIN', initialState);
export default function(state = initialState, action) {
let newState;
if (action.type === 'LOGIN:OK') {
if (action.type.startsWith('LOGIN:')) {
newState = loginHandler(state, action);
}
if (action.type === 'CHECKLOGIN:OK') {

View File

@ -3,9 +3,10 @@ import thunk from 'redux-thunk';
import rootReducer from './reducers/root';
const createStoreWithMiddleware = compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
// https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const createStoreWithMiddleware = composeEnhancers(
applyMiddleware(thunk)
)(createStore);
const store = createStoreWithMiddleware(rootReducer);