This commit is contained in:
oitsjustjose 2020-10-17 23:34:27 -05:00
commit 231adbe93f
123 changed files with 16683 additions and 62496 deletions

27
frontend/src/App.jsx Normal file
View file

@ -0,0 +1,27 @@
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import LoadAuth from './auth/load';
import RequiresAuth from './components/modules/Auth';
import NavBar from './components/modules/NavBar';
import Dashboard from './components/view/Dashboard';
import Posts from './components/view/Posts';
import store from './redux/store';
export default () => {
LoadAuth();
ReactDOM.render(
<Provider store={store}>
<Router>
<NavBar />
<div style={{ paddingTop: `${3.5}em` }} />
<Route exact path="/" component={Posts} />
<RequiresAuth exact path="/manage" component={Dashboard} />
</Router>
</Provider>,
document.getElementById('root'),
);
};

13
frontend/src/auth/load.js Normal file
View file

@ -0,0 +1,13 @@
/* eslint-disable no-underscore-dangle */
import jwtDecode from 'jwt-decode';
import store from '../redux/store';
import setAuthToken from '../axios/AuthToken';
export default () => {
const token = window.localStorage.getItem('auth-token');
if (token) {
const user = jwtDecode(token);
store.dispatch({ type: 'SET_USER', user });
setAuthToken(token);
}
};

View file

@ -0,0 +1,9 @@
import setAuthToken from '../axios/AuthToken';
import store from '../redux/store';
export default () => {
localStorage.removeItem('auth-token');
setAuthToken(null);
store.dispatch({ type: 'CLEAR_USER' });
window.location.reload();
};

View file

@ -0,0 +1,9 @@
import axios from 'axios';
export default (token) => {
if (token) {
axios.defaults.headers.common['auth-token'] = token;
} else {
delete axios.defaults.headers.common['auth-token'];
}
};

View file

@ -0,0 +1,20 @@
/* eslint-disable no-underscore-dangle */
import axios from 'axios';
import jwtDecode from 'jwt-decode';
import store from '../redux/store';
import setAuthToken from './AuthToken';
export default (data) => {
const path = '/api/users/login';
return axios.post(path, data)
.then((resp) => {
const token = resp.data;
localStorage.setItem('auth-token', token);
const user = jwtDecode(token);
store.dispatch({ type: 'SET_USER', user: user._doc });
setAuthToken(token);
});
};

View file

@ -0,0 +1,33 @@
import { faSignOutAlt } from '@fortawesome/free-solid-svg-icons';
import React from 'react';
import { Nav, Navbar, NavItem } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import NavLinkItem from './NavLinkItem';
import store from '../../redux/store';
import LogOut from '../../auth/logout';
export default () => (
<Navbar expand="lg" collapseOnSelect bg="dark" variant="dark" fixed="top">
<Navbar.Brand>Geolosys Configurator</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse>
<Nav className="mr-auto">
<NavLinkItem name="Blog" dest="/" icon={faBook} />
{store.getState().isAuthenticated && (
<div>
<NavLinkItem name="Your Configs" dest="/manage" icon={faEdit} />
<NavItem style={{ cursor: 'pointer' }} onClick={LogOut}>
<div className="nav-link nav-sign-out">
<span>
<FontAwesomeIcon icon={faSignOutAlt} />
{' '}
Sign Out
</span>
</div>
</NavItem>
</div>
)}
</Nav>
</Navbar.Collapse>
</Navbar>
);

View file

@ -0,0 +1,18 @@
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React from 'react';
import { NavLink } from 'react-router-dom';
import { NavItem } from 'react-bootstrap';
export default ({
name, dest, icon,
}) => (
<NavItem>
<NavLink exact className="nav-link" activeClassName="nav-link active" to={dest}>
<span>
{icon && (<FontAwesomeIcon icon={icon} />)}
{' '}
{name}
</span>
</NavLink>
</NavItem>
);

View file

@ -0,0 +1,21 @@
import React from 'react';
import { Modal } from 'react-bootstrap';
export default ({
title, contents, show, onHide,
}) => (
<Modal
show={show}
onHide={onHide}
>
<Modal.Header closeButton>
<Modal.Title className="text-center">
{title}
</Modal.Title>
</Modal.Header>
<Modal.Body>
{contents}
</Modal.Body>
</Modal>
);

View file

@ -0,0 +1,90 @@
import React, { useEffect, useState } from 'react';
import { Button, Container, Form } from 'react-bootstrap';
import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSignInAlt } from '@fortawesome/free-solid-svg-icons';
import { CSSTransition } from 'react-transition-group';
import postLogin from '../../axios/Login';
import Notification from '../modules/Notification';
const LoginComponent = ({
isAuthenticated,
}) => {
const [state, setState] = useState({
username: null,
password: null,
});
const [error, setError] = useState(null);
useEffect(() => {
if (isAuthenticated) {
window.location.reload();
}
}, [isAuthenticated]);
const submit = (evt) => {
evt.preventDefault();
postLogin(state).catch((ex) => {
setError(`${ex.response.data}`);
});
};
return (
<CSSTransition classNames="react-router" appear in timeout={300}>
<div>
<div className="v-center">
<Container
className="mx-auto perfect-width"
>
<h2 className="text-center">
Admin Login
</h2>
<Form onSubmit={submit}>
<Form.Group>
<Form.Label>
Username
</Form.Label>
<Form.Control
type="text"
onChange={(evt) => { setState({ ...state, username: evt.target.value }); }}
/>
</Form.Group>
<Form.Group>
<Form.Label>
Password
</Form.Label>
<Form.Control
type="password"
onChange={(evt) => { setState({ ...state, password: evt.target.value }); }}
/>
</Form.Group>
<Button
type="submit"
>
<FontAwesomeIcon icon={faSignInAlt} />
{' '}
Log In
</Button>
</Form>
</Container>
</div>
<Notification
title="Failed to Log In"
contents={error}
show={!!error}
onHide={() => setError(null)}
/>
</div>
</CSSTransition>
);
};
const mapStateToProps = (state) => ({
isAuthenticated: state.isAuthenticated,
user: state.user,
});
export default connect(mapStateToProps)(LoginComponent);

7
frontend/src/index.js Normal file
View file

@ -0,0 +1,7 @@
import RenderApp from './App';
import './css/App.css';
import * as serviceWorker from './serviceWorker';
RenderApp();
serviceWorker.unregister();

View file

@ -0,0 +1,36 @@
const defaultState = {
isAuthenticated: false,
user: null,
posts: null,
editingPost: null,
// editingPost: {
// id: null,
// title: null,
// contents: null,
// },
};
export default function reducer(
state = defaultState,
action,
) {
switch (action.type) {
case 'SET_USER':
return {
...state,
user: {
...action.user,
},
isAuthenticated: true,
};
case 'CLEAR_USER':
return {
...state,
user: null,
isAuthenticated: false,
};
default:
return state;
}
}

View file

@ -0,0 +1,10 @@
import { createStore } from 'redux';
import reducer from './reducers';
// TODO: This should only initialize for development
// eslint-disable-next-line no-underscore-dangle
const enhancer = window.__REDUX_DEVTOOLS_EXTENSION__
// eslint-disable-next-line no-underscore-dangle
&& window.__REDUX_DEVTOOLS_EXTENSION__();
export default createStore(reducer, enhancer);

View file

@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}