├── flask-api ├── flask_api │ ├── common │ │ ├── __init__.py │ │ ├── utils.py │ │ └── constants.py │ ├── __init__.py │ ├── resources │ │ ├── __init__.py │ │ └── auth.py │ ├── extensions.py │ ├── user │ │ ├── helpers.py │ │ ├── __init__.py │ │ ├── serializers.py │ │ ├── constants.py │ │ ├── manager.py │ │ └── models.py │ └── app.py ├── config │ ├── __init__.py │ ├── secret_generator.py │ └── cfg.py ├── run.py ├── manage.py ├── requirements.txt ├── .gitignore └── README.md ├── website ├── src │ ├── common │ │ ├── index.js │ │ ├── appRoutes.js │ │ └── APIResources.js │ ├── redux │ │ ├── actions │ │ │ ├── index.js │ │ │ ├── fetch.js │ │ │ ├── ui.js │ │ │ └── auth.js │ │ ├── saga │ │ │ ├── index.js │ │ │ └── appSaga │ │ │ │ ├── index.js │ │ │ │ └── fetchSaga.js │ │ ├── reducers │ │ │ ├── index.js │ │ │ ├── ui.js │ │ │ └── auth.js │ │ ├── index.js │ │ └── store │ │ │ └── index.js │ ├── ui │ │ ├── containers │ │ │ ├── Auth │ │ │ │ ├── index.js │ │ │ │ ├── AuthRequired.js │ │ │ │ └── UnauthRequired.js │ │ │ ├── defaultTheme.js │ │ │ ├── Layout │ │ │ │ ├── AppBar.js │ │ │ │ ├── SideBar.js │ │ │ │ ├── Menu.js │ │ │ │ ├── Layout.js │ │ │ │ └── UserBox.js │ │ │ ├── Waiting │ │ │ │ └── Waiting.js │ │ │ ├── Home │ │ │ │ ├── Home.js │ │ │ │ └── logo.svg │ │ │ ├── Wrapper │ │ │ │ └── Wrapper.js │ │ │ ├── NotFound │ │ │ │ └── NotFound.js │ │ │ └── Login │ │ │ │ └── Login.js │ │ └── components │ │ │ └── TextInput.js │ ├── APIManager │ │ ├── index.js │ │ ├── HttpError.js │ │ ├── HttpProvider.js │ │ └── APIManager.js │ ├── index.js │ ├── App.js │ └── Routes.js ├── public │ ├── favicon.ico │ └── index.html ├── .gitignore ├── package.json └── README.md └── README.md /flask-api/flask_api/common/__init__.py: -------------------------------------------------------------------------------- 1 | from .constants import * 2 | from .utils import * -------------------------------------------------------------------------------- /website/src/common/index.js: -------------------------------------------------------------------------------- 1 | export * from './APIResources'; 2 | export * from './appRoutes'; -------------------------------------------------------------------------------- /flask-api/config/__init__.py: -------------------------------------------------------------------------------- 1 | from .cfg import set_config 2 | 3 | __all__ = [ 4 | 'set_config', 5 | ] -------------------------------------------------------------------------------- /flask-api/flask_api/__init__.py: -------------------------------------------------------------------------------- 1 | from .app import create_app 2 | 3 | __all__ = [ 4 | 'create_app', 5 | ] -------------------------------------------------------------------------------- /flask-api/flask_api/resources/__init__.py: -------------------------------------------------------------------------------- 1 | from .auth import auth_bp 2 | 3 | bp_list = [ 4 | auth_bp, 5 | ] -------------------------------------------------------------------------------- /website/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ey-lab/flask-react-boilerplate/HEAD/website/public/favicon.ico -------------------------------------------------------------------------------- /website/src/redux/actions/index.js: -------------------------------------------------------------------------------- 1 | export * from './ui'; 2 | export * from './auth'; 3 | export * from './fetch'; 4 | -------------------------------------------------------------------------------- /flask-api/run.py: -------------------------------------------------------------------------------- 1 | from flask_api import create_app 2 | 3 | app = create_app() 4 | 5 | if __name__ == '__main__': 6 | app.run() 7 | -------------------------------------------------------------------------------- /website/src/ui/containers/Auth/index.js: -------------------------------------------------------------------------------- 1 | export const AuthRequired = require('./AuthRequired').default; 2 | export const UnauthRequired = require('./UnauthRequired').default; -------------------------------------------------------------------------------- /website/src/APIManager/index.js: -------------------------------------------------------------------------------- 1 | import APIManager from './APIManager'; 2 | import HttpProvider from './HttpProvider'; 3 | 4 | export * from './APIManager'; 5 | 6 | export default APIManager(HttpProvider); -------------------------------------------------------------------------------- /website/src/common/appRoutes.js: -------------------------------------------------------------------------------- 1 | /* App routes */ 2 | export const HOME_ROUTE = '/' 3 | export const AUTH = 'auth' 4 | export const LOGIN = 'login' 5 | 6 | export const AUTH_LOGIN_ROUTE = `/${AUTH}/${LOGIN}` -------------------------------------------------------------------------------- /website/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | ReactDOM.render( 6 | , 7 | document.getElementById('root') 8 | ); 9 | -------------------------------------------------------------------------------- /flask-api/flask_api/common/utils.py: -------------------------------------------------------------------------------- 1 | from .constants import CSRF_TOKEN_KEY 2 | 3 | from flask_wtf.csrf import generate_csrf 4 | 5 | def insert_csrf_token(elements): 6 | return dict(elements, **{CSRF_TOKEN_KEY: generate_csrf()}) -------------------------------------------------------------------------------- /flask-api/flask_api/extensions.py: -------------------------------------------------------------------------------- 1 | from flask_sqlalchemy import SQLAlchemy 2 | db = SQLAlchemy() 3 | 4 | from flask_security import Security 5 | security = Security() 6 | 7 | from flask_wtf.csrf import CSRFProtect 8 | csrf = CSRFProtect() 9 | -------------------------------------------------------------------------------- /website/src/ui/containers/defaultTheme.js: -------------------------------------------------------------------------------- 1 | export default { 2 | tabs: { 3 | backgroundColor: 'white', 4 | selectedTextColor: '#00bcd4', 5 | textColor: '#757575', 6 | }, 7 | inkBar: { 8 | backgroundColor: '#00bcd4', 9 | }, 10 | appBar: { 11 | height: 50, 12 | } 13 | }; -------------------------------------------------------------------------------- /flask-api/flask_api/user/helpers.py: -------------------------------------------------------------------------------- 1 | from flask_security import SQLAlchemyUserDatastore 2 | 3 | from .models import User, Role, db 4 | 5 | user_datastore = SQLAlchemyUserDatastore(db, User, Role) 6 | 7 | def _commit(response=None): 8 | user_datastore.commit() 9 | return response 10 | 11 | -------------------------------------------------------------------------------- /website/src/common/APIResources.js: -------------------------------------------------------------------------------- 1 | /* API Resources */ 2 | /* Auth API base URL */ 3 | export const AUTH_API_BASE_URL = 'http://localhost:5000/auth'; 4 | 5 | /* Auth Resources */ 6 | export const LOAD_AUTH_RESOURCE = 'loadAuth'; 7 | export const LOGIN_RESOURCE = 'login'; 8 | export const LOGOUT_RESOURCE = 'logout'; -------------------------------------------------------------------------------- /website/src/redux/actions/fetch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Fetch actions options 3 | */ 4 | 5 | /* General fetch action */ 6 | export const FETCH_REQUEST = 'FETCH_REQUEST'; 7 | export const FETCH_SUCCESS = 'FETCH_SUCCESS'; 8 | export const FETCH_FAILURE = 'FETCH_FAILURE'; 9 | export const FETCH_CANCEL = 'FETCH_CANCEL'; 10 | -------------------------------------------------------------------------------- /website/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | node_modules 5 | 6 | # testing 7 | coverage 8 | 9 | # production 10 | build 11 | 12 | # misc 13 | .DS_Store 14 | .env 15 | npm-debug.log* 16 | yarn-debug.log* 17 | yarn-error.log* 18 | 19 | -------------------------------------------------------------------------------- /flask-api/flask_api/user/__init__.py: -------------------------------------------------------------------------------- 1 | from .models import User, Role 2 | from .helpers import user_datastore, _commit 3 | from .serializers import user_schema 4 | from .manager import manager 5 | 6 | __all__ = [ 7 | 'User', 8 | 'Role', 9 | 'user_datastore', 10 | '_commit', 11 | 'user_schema', 12 | 'manager', 13 | ] -------------------------------------------------------------------------------- /flask-api/flask_api/common/constants.py: -------------------------------------------------------------------------------- 1 | # Limit String Length in databases 2 | STRING_LENGTH = 255 3 | 4 | # Key used to stored csrf token transmitted to the client 5 | CSRF_TOKEN_KEY = 'csrfToken' 6 | 7 | # Allowed domains for Cross Origin Requests 8 | ALLOWED_CROSS_ORIGIN_DOMAIN = [ 9 | 'http://localhost:3000', 10 | ] 11 | 12 | 13 | -------------------------------------------------------------------------------- /website/src/ui/components/TextInput.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import TextField from 'material-ui/TextField'; 4 | 5 | const TextInput = ({meta: { touched, error}, input: {...input}, ...props }) => { 6 | return ( 7 | 13 | ); 14 | }; 15 | 16 | export default TextInput -------------------------------------------------------------------------------- /website/src/redux/saga/index.js: -------------------------------------------------------------------------------- 1 | import createAppSaga from './appSaga'; 2 | 3 | /** 4 | * Function that run all the sagas to be run 5 | * @param {function} APIManager - function that perform API fetch calls 6 | */ 7 | function createSaga(APIManager) { 8 | function* saga() { 9 | yield [ 10 | createAppSaga(APIManager)(), 11 | ]; 12 | }; 13 | return saga; 14 | } 15 | 16 | export default createSaga; -------------------------------------------------------------------------------- /website/src/redux/reducers/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | combineReducers, 3 | } from 'redux'; 4 | import { 5 | reducer as form, 6 | } from 'redux-form'; 7 | import { 8 | routerReducer as routing, 9 | } from 'react-router-redux'; 10 | 11 | import ui from './ui'; 12 | import auth from './auth'; 13 | 14 | /* Build app reducers */ 15 | const reducer = combineReducers({ 16 | auth, 17 | ui, 18 | routing, 19 | form, 20 | }); 21 | 22 | export default reducer; -------------------------------------------------------------------------------- /flask-api/manage.py: -------------------------------------------------------------------------------- 1 | from flask_script import Manager 2 | from flask_api import create_app 3 | from flask_api.extensions import db 4 | from flask_api.user import manager as user_manager 5 | 6 | 7 | manager = Manager(create_app(register_blueprints=False)) 8 | 9 | @manager.command 10 | def init_db(): 11 | """ 12 | Initializes the tables in the database 13 | """ 14 | db.drop_all() 15 | db.create_all() 16 | db.session.commit() 17 | 18 | manager.add_command("user", user_manager) 19 | 20 | if __name__ == "__main__": 21 | manager.run() 22 | -------------------------------------------------------------------------------- /website/src/APIManager/HttpError.js: -------------------------------------------------------------------------------- 1 | class HttpError extends Error { 2 | constructor(message, status) { 3 | super(message); 4 | this.message = message; 5 | this.status = status; 6 | 7 | this.name = this.constructor.name; 8 | if (typeof Error.captureStackTrace === 'function') { 9 | Error.captureStackTrace(this, this.constructor); 10 | } else { 11 | this.stack = (new Error(message)).stack; 12 | } 13 | this.stack = new Error().stack; 14 | } 15 | } 16 | 17 | export default HttpError; -------------------------------------------------------------------------------- /flask-api/config/secret_generator.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import os 3 | 4 | def generate_secrets_file(path): 5 | config = configparser.ConfigParser() 6 | 7 | # SECRETS 8 | secrets = ['SECRET_KEY', 'WTF_CSRF_SECRET_KEY', 'CSRF_SESSION_KEY', 9 | 'SECURITY_PASSWORD_SALT', 'SECURITY_CHANGE_SALT', 'SECURITY_RESET_SALT', 10 | 'SECURITY_CONFIRM_DEVICE_SALT', 'SECURITY_HISTORIC_COOKIE_SIGNING_SALT'] 11 | config['SECRETS'] = {secret: os.urandom(32).hex() for secret in secrets} 12 | 13 | with open(path, 'w') as configfile: 14 | config.write(configfile) 15 | 16 | if __name__ == '__main__': 17 | generate_secrets_file('secrets.cfg') -------------------------------------------------------------------------------- /website/src/ui/containers/Auth/AuthRequired.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | import { 5 | connect, 6 | } from 'react-redux'; 7 | 8 | import Waiting from '../Waiting/Waiting'; 9 | 10 | const AuthRequired = (props) => { 11 | const { 12 | children, 13 | auth: { 14 | user 15 | } 16 | } = props; 17 | 18 | if (user) { 19 | return children ; 20 | } else { 21 | return ; 22 | } 23 | } 24 | 25 | AuthRequired.propTypes = { 26 | children: PropTypes.node, 27 | auth: PropTypes.object.isRequired, 28 | } 29 | 30 | const mapStateToProps = (state) => ({ 31 | auth: state.auth, 32 | }) 33 | 34 | export default connect( 35 | mapStateToProps 36 | )(AuthRequired); -------------------------------------------------------------------------------- /flask-api/flask_api/user/serializers.py: -------------------------------------------------------------------------------- 1 | from marshmallow import Schema, fields 2 | from .constants import ROLE_NAME_KEY, \ 3 | USER_EMAIL_ADDRESS_KEY, USER_LAST_NAME_KEY, USER_FIRST_NAME_KEY, USER_USER_NAME_KEY 4 | 5 | 6 | class RoleSchema(Schema): 7 | id = fields.Int() 8 | name = fields.Str(dump_to=ROLE_NAME_KEY) 9 | 10 | 11 | class UserSchema(Schema): 12 | id = fields.Int() 13 | 14 | email = fields.Str(dump_to=USER_EMAIL_ADDRESS_KEY) 15 | 16 | last_name = fields.Str(dump_to=USER_LAST_NAME_KEY) 17 | first_name = fields.Str(dump_to=USER_FIRST_NAME_KEY) 18 | user_name = fields.Str(dump_to=USER_USER_NAME_KEY) 19 | 20 | roles = fields.Nested(RoleSchema, many=True) 21 | 22 | user_schema = UserSchema() 23 | -------------------------------------------------------------------------------- /website/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "stack-lab-react-v2", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "react-scripts": "0.9.5" 7 | }, 8 | "dependencies": { 9 | "material-ui": "^0.17.1", 10 | "react": "^15.4.2", 11 | "react-dom": "^15.4.2", 12 | "react-redux": "^5.0.3", 13 | "react-router": "^2.8.1", 14 | "react-router-redux": "^4.0.8", 15 | "react-tap-event-plugin": "^2.0.1", 16 | "redux": "^3.6.0", 17 | "redux-form": "^6.5.0", 18 | "redux-saga": "^0.14.3" 19 | }, 20 | "scripts": { 21 | "start": "react-scripts start", 22 | "build": "react-scripts build", 23 | "test": "react-scripts test --env=jsdom", 24 | "eject": "react-scripts eject" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /website/src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | Provider, 4 | } from 'react-redux'; 5 | import { 6 | Router, 7 | browserHistory, 8 | } from 'react-router'; 9 | import { 10 | syncHistoryWithStore, 11 | } from 'react-router-redux'; 12 | 13 | import APIManager from './APIManager'; 14 | import createStore from './redux' 15 | import getRoutes from './Routes'; 16 | 17 | const store = createStore(APIManager, browserHistory); 18 | 19 | const history = syncHistoryWithStore(browserHistory, store); 20 | 21 | const App = () => { 22 | return ( 23 | 24 | 25 | { getRoutes() } 26 | 27 | 28 | ); 29 | }; 30 | 31 | export default App; 32 | -------------------------------------------------------------------------------- /website/src/ui/containers/Auth/UnauthRequired.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | import { 5 | connect, 6 | } from 'react-redux'; 7 | 8 | import Waiting from '../Waiting/Waiting'; 9 | 10 | const UnauthRequired = (props) => { 11 | const { 12 | children, 13 | auth: { 14 | user, 15 | status: { 16 | load, 17 | } 18 | } 19 | } = props; 20 | 21 | if (!user && !load.loading) { 22 | return children ; 23 | } else { 24 | return ; 25 | } 26 | } 27 | 28 | UnauthRequired.propTypes = { 29 | children: PropTypes.node, 30 | auth: PropTypes.object.isRequired, 31 | } 32 | 33 | const mapStateToProps = (state) => ({ 34 | auth: state.auth, 35 | }) 36 | 37 | export default connect( 38 | mapStateToProps 39 | )(UnauthRequired); -------------------------------------------------------------------------------- /website/src/redux/actions/ui.js: -------------------------------------------------------------------------------- 1 | /** 2 | * ui actions 3 | */ 4 | 5 | /* Actions related to sidebar visibility */ 6 | export const TOGGLE_SIDEBAR = 'TOGGLE_SIDEBAR'; 7 | export const toggleSidebar = () => ({ 8 | type: TOGGLE_SIDEBAR, 9 | }); 10 | 11 | export const SET_SIDEBAR_VISIBILITY = 'SET_SIDEBAR_VISIBILITY'; 12 | export const setSidebarVisibility = (isOpen) => ({ 13 | type: SET_SIDEBAR_VISIBILITY, 14 | payload: isOpen, 15 | }); 16 | 17 | /* Actions related to userbox visibility */ 18 | export const TOGGLE_USER_BOX = 'TOGGLE_USER_BOX'; 19 | export const toggleUserBox = () => ({ 20 | type: TOGGLE_USER_BOX, 21 | }); 22 | 23 | export const SET_USER_BOX_VISIBILITY = 'SET_USER_BOX_VISIBILITY'; 24 | export const setUserBoxVisibility = (isOpen) => ({ 25 | type: SET_USER_BOX_VISIBILITY, 26 | payload: isOpen, 27 | }); -------------------------------------------------------------------------------- /flask-api/requirements.txt: -------------------------------------------------------------------------------- 1 | aniso8601==1.2.0 2 | appdirs==1.4.3 3 | bcrypt==3.1.2 4 | blinker==1.4 5 | cffi==1.9.1 6 | click==6.7 7 | enum-compat==0.0.2 8 | eventlet==0.20.1 9 | Flask==0.12 10 | Flask-Login==0.3.2 11 | Flask-Mail==0.9.1 12 | Flask-Moment==0.5.1 13 | Flask-Principal==0.4.0 14 | Flask-RESTful==0.3.5 15 | Flask-Script==2.0.5 16 | Flask-Security==1.7.5 17 | Flask-SocketIO==2.8.2 18 | Flask-SQLAlchemy==2.1 19 | Flask-WTF==0.14.2 20 | greenlet==0.4.11 21 | gunicorn==19.6.0 22 | itsdangerous==0.24 23 | Jinja2==2.9.4 24 | MarkupSafe==0.23 25 | marshmallow==2.13.5 26 | numpy==1.12.0 27 | packaging==16.8 28 | pandas==0.19.2 29 | passlib==1.7.0 30 | pycparser==2.17 31 | pyparsing==2.2.0 32 | python-dateutil==2.6.0 33 | python-engineio==1.1.1 34 | python-socketio==1.6.3 35 | pytz==2016.10 36 | requests==2.13.0 37 | six==1.10.0 38 | SQLAlchemy==1.1.4 39 | Werkzeug==0.11.15 40 | WTForms==2.1 41 | -------------------------------------------------------------------------------- /website/src/redux/index.js: -------------------------------------------------------------------------------- 1 | import createSagaMiddleware from 'redux-saga'; 2 | import { 3 | routerMiddleware, 4 | } from 'react-router-redux'; 5 | 6 | import _createStore from './store'; 7 | import reducer from './reducers'; 8 | import createSaga from './saga'; 9 | 10 | /** 11 | * High level createStore function 12 | * @param {function} APIManager function that builds and handles API calls (will be transmitted to every saga performing API calls) 13 | * @param {object} history router history (used by react-router) 14 | */ 15 | function createStore(APIManager, history) { 16 | const sagaMiddleware = createSagaMiddleware(); 17 | 18 | const middlewares = [ 19 | sagaMiddleware, 20 | routerMiddleware(history), 21 | ]; 22 | 23 | const store = _createStore(reducer, middlewares); 24 | const saga = createSaga(APIManager); 25 | sagaMiddleware.run(saga); 26 | 27 | return store; 28 | }; 29 | 30 | export default createStore; -------------------------------------------------------------------------------- /website/src/redux/store/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | applyMiddleware, 3 | compose, 4 | createStore as _createStore, 5 | } from 'redux'; 6 | 7 | /** 8 | * Create store functions that take into account the NODE_ENV environment variable 9 | * @param {function} reducer - App reducer 10 | * @param {Array} middlewares - Array containing all middlewares to apply 11 | */ 12 | function createStore(reducer, middlewares) { 13 | if (process.env.NODE_ENV === 'development') { 14 | return _createStore( 15 | reducer, 16 | undefined, 17 | compose( 18 | applyMiddleware(...middlewares), 19 | window.devToolsExtension ? window.devToolsExtension() : f => f, // include devToolsExtension 20 | ) 21 | ); 22 | } else if (process.env.NODE_ENV === 'production') { 23 | return _createStore( 24 | reducer, 25 | undefined, 26 | applyMiddleware(...middlewares) 27 | ); 28 | } 29 | } 30 | 31 | export default createStore; -------------------------------------------------------------------------------- /website/src/ui/containers/Layout/AppBar.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes, 3 | } from 'react'; 4 | import { 5 | connect , 6 | } from 'react-redux'; 7 | import MuiAppBar from 'material-ui/AppBar'; 8 | 9 | import { 10 | toggleSidebar, 11 | } from '../../../redux/actions'; 12 | import UserBoxIcon from './UserBox'; 13 | 14 | 15 | const AppBar = (props) => { 16 | const { 17 | title, 18 | toggleSidebar 19 | } = props 20 | 21 | return ( 22 | } 26 | zDepth={2} 27 | /> 28 | ); 29 | } 30 | 31 | AppBar.propTypes = { 32 | title: PropTypes.oneOfType([ 33 | PropTypes.string, 34 | PropTypes.element 35 | ]).isRequired, 36 | toggleSidebar: PropTypes.func.isRequired, 37 | } 38 | 39 | const mapDispatchToProps = { 40 | toggleSidebar, 41 | }; 42 | 43 | export default connect( 44 | null, 45 | mapDispatchToProps 46 | )(AppBar); -------------------------------------------------------------------------------- /website/src/redux/reducers/ui.js: -------------------------------------------------------------------------------- 1 | import { 2 | TOGGLE_SIDEBAR, 3 | SET_SIDEBAR_VISIBILITY, 4 | TOGGLE_USER_BOX, 5 | SET_USER_BOX_VISIBILITY, 6 | LOGOUT 7 | } from '../actions'; 8 | 9 | const initialState = { 10 | sidebarOpen: true, 11 | userBoxOpen: false, 12 | } 13 | 14 | /* ui reducer */ 15 | export default (state = initialState, { type, payload }) => { 16 | switch (type) { 17 | case TOGGLE_SIDEBAR: 18 | return { 19 | ...state, 20 | sidebarOpen: !state.sidebarOpen, 21 | }; 22 | 23 | case TOGGLE_USER_BOX: 24 | return { 25 | ...state, 26 | userBoxOpen: !state.userBoxOpen, 27 | }; 28 | 29 | case SET_SIDEBAR_VISIBILITY: 30 | return { 31 | ...state, 32 | sidebarOpen: payload, 33 | }; 34 | 35 | case SET_USER_BOX_VISIBILITY: 36 | return { 37 | ...state, 38 | userBoxOpen: payload, 39 | }; 40 | 41 | case `${LOGOUT}_SUCCESS`: 42 | return initialState; 43 | 44 | default: 45 | return state; 46 | } 47 | } -------------------------------------------------------------------------------- /website/src/ui/containers/Layout/SideBar.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes, 3 | } from 'react'; 4 | import Paper from 'material-ui/Paper'; 5 | import { 6 | connect, 7 | } from 'react-redux'; 8 | 9 | const styles = { 10 | sidebarOpen: { 11 | flex: '0 0 12em', 12 | marginLeft: 0, 13 | order: -1, 14 | transition: 'margin 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms' 15 | }, 16 | sidebarClosed: { 17 | flex: '0 0 12em', 18 | marginLeft: '-8.5em', 19 | order: -1, 20 | transition: 'margin 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms' 21 | }, 22 | }; 23 | 24 | const SideBar = (props) => { 25 | const { open, children } = props; 26 | return ( 27 | 28 | { children } 29 | 30 | ); 31 | }; 32 | 33 | SideBar.propTypes = { 34 | open: PropTypes.bool, 35 | children: PropTypes.node, 36 | } 37 | 38 | const mapStateToProps = (state) => ({ 39 | open: state.ui.sidebarOpen, 40 | }); 41 | 42 | export default connect( 43 | mapStateToProps 44 | )(SideBar); 45 | -------------------------------------------------------------------------------- /website/src/ui/containers/Layout/Menu.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | import { 5 | connect, 6 | } from 'react-redux'; 7 | import { 8 | Link, 9 | } from 'react-router'; 10 | 11 | import MenuItem from 'material-ui/MenuItem'; 12 | 13 | const styles = { 14 | menu: { 15 | display: 'flex', 16 | flexDirection: 'column', 17 | justifyContent: 'flex-start', 18 | height: '100%', 19 | } 20 | } 21 | 22 | const Menu = ({items, open}) => ( 23 |
24 | { 25 | items.map(item => ( 26 | : null} 30 | rightIcon={!open ? : null} 31 | containerElement={} 32 | /> 33 | ) 34 | )} 35 |
36 | ) 37 | 38 | Menu.propTypes = { 39 | open: PropTypes.bool.isRequired, 40 | items: PropTypes.array.isRequired, 41 | } 42 | 43 | const mapStateToProps = (state) => ({ 44 | open: state.ui.sidebarOpen 45 | }); 46 | 47 | export default connect( 48 | mapStateToProps 49 | )(Menu); 50 | -------------------------------------------------------------------------------- /flask-api/flask_api/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | from config import set_config 4 | from .user import user_datastore 5 | 6 | __all__ = [ 7 | 'create_app', 8 | ] 9 | 10 | 11 | def create_app(register_blueprints=True): 12 | app = Flask(__name__) 13 | 14 | set_config(app) 15 | configure_extensions(app) 16 | 17 | if register_blueprints: 18 | configure_blueprints(app) 19 | configure_hook(app) 20 | 21 | return app 22 | 23 | 24 | def configure_extensions(app): 25 | from .extensions import db, security, csrf 26 | # flask-sqlalchemy 27 | db.init_app(app) 28 | 29 | # Flask csrf protection 30 | csrf.init_app(app) 31 | 32 | # flask-security 33 | security.init_app(app, user_datastore, register_blueprint=False) 34 | 35 | 36 | def configure_blueprints(app): 37 | from .resources import bp_list 38 | for bp in bp_list: 39 | app.register_blueprint(bp) 40 | 41 | 42 | def configure_hook(app): 43 | from flask import session 44 | 45 | @app.before_request 46 | def before_request(): 47 | # Update session cookie expiration date 48 | session.permanent = True 49 | session.modified = True 50 | -------------------------------------------------------------------------------- /website/src/ui/containers/Waiting/Waiting.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | 5 | import getMuiTheme from 'material-ui/styles/getMuiTheme'; 6 | import autoprefixer from 'material-ui/utils/autoprefixer'; 7 | import CircularProgress from 'material-ui/CircularProgress'; 8 | 9 | import defaultTheme from '../defaultTheme'; 10 | 11 | const styles = { 12 | body: { 13 | display: 'flex', 14 | flexDirection: 'column', 15 | minHeight: '100vh', 16 | alignItems: 'center', 17 | justifyContent: 'center', 18 | }, 19 | }; 20 | 21 | const prefixedStyles = {}; 22 | 23 | const Waiting = (props) => { 24 | const { 25 | theme 26 | } = props; 27 | const muiTheme = getMuiTheme(theme); 28 | 29 | if (!prefixedStyles.main) { 30 | const prefix = autoprefixer(muiTheme); 31 | prefixedStyles.body = prefix(styles.body); 32 | } 33 | 34 | return ( 35 |
36 | 37 |
38 | ); 39 | } 40 | 41 | Waiting.propTypes = { 42 | theme: PropTypes.object.isRequired, 43 | } 44 | 45 | Waiting.defaultProps = { 46 | theme: defaultTheme, 47 | } 48 | 49 | export default Waiting; -------------------------------------------------------------------------------- /website/src/ui/containers/Home/Home.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { 3 | connect 4 | } from 'react-redux'; 5 | import { 6 | Card, 7 | CardTitle, 8 | CardHeader, 9 | CardText 10 | } from 'material-ui/Card'; 11 | import Paper from 'material-ui/Paper' 12 | import Avatar from 'material-ui/Avatar' 13 | 14 | import { 15 | white 16 | } from 'material-ui/styles/colors'; 17 | 18 | import logo from './logo.svg'; 19 | 20 | const Home = (props) => { 21 | const { 22 | user 23 | } = props; 24 | 25 | return ( 26 | 27 | 28 | } 30 | title="Home" 31 | subtitle="React App" 32 | /> 33 | 36 | 37 | {"Love React + Python <3"} 38 | 39 | 40 | 41 | ) 42 | }; 43 | 44 | const mapStateToProps = (state) => ({ 45 | user: state.auth.user, 46 | }) 47 | 48 | export default connect( 49 | mapStateToProps 50 | )(Home); -------------------------------------------------------------------------------- /flask-api/flask_api/user/constants.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | # ORM constants 4 | ROLE_TABLE_NAME = "roles" 5 | ROLE_NAME_LENGTH = 15 6 | ROLE_ADMIN = 0 7 | ROLE_USER = 1 8 | ROLES = { 9 | ROLE_ADMIN: 'admin', 10 | ROLE_USER: 'user', 11 | } 12 | ROLES = OrderedDict(sorted(ROLES.items())) 13 | 14 | USER_TABLE_NAME = "users" 15 | USER_EMAIL_LENGTH = 255 16 | USER_PASSWORD_LENGTH = 255 17 | USER_LAST_NAME_LENGTH = 255 18 | USER_FIRST_NAME_LENGTH = 255 19 | USER_USER_NAME_LENGTH = 255 20 | 21 | 22 | SEX_MALE = 1 23 | SEX_FEMALE = 2 24 | SEX_OTHER = 3 25 | SEX_TYPES = { 26 | SEX_MALE: 'Male', 27 | SEX_FEMALE: 'Female', 28 | SEX_OTHER: 'Other' 29 | } 30 | SEX_TYPES = OrderedDict(sorted(SEX_TYPES.items())) 31 | 32 | 33 | STATUS_INACTIVE = 0 34 | STATUS_NEW = 1 35 | STATUS_ACTIVE = 2 36 | USER_STATUS = { 37 | STATUS_INACTIVE: 'inactive', 38 | STATUS_NEW: 'new', 39 | STATUS_ACTIVE: 'active', 40 | } 41 | USER_STATUS = OrderedDict(sorted(USER_STATUS.items())) 42 | 43 | # Serializer constants 44 | ROLE_NAME_KEY = "name" 45 | 46 | USER_EMAIL_ADDRESS_KEY = "email" 47 | USER_LAST_NAME_KEY = "lastName" 48 | USER_FIRST_NAME_KEY = "firstName" 49 | USER_USER_NAME_KEY = "userName" 50 | -------------------------------------------------------------------------------- /website/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 16 | React App 17 | 18 | 19 |
20 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /website/src/ui/containers/Wrapper/Wrapper.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | import injectTapEventPlugin from 'react-tap-event-plugin'; 5 | 6 | import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; 7 | import getMuiTheme from 'material-ui/styles/getMuiTheme'; 8 | import autoprefixer from 'material-ui/utils/autoprefixer'; 9 | 10 | import defaultTheme from '../defaultTheme'; 11 | 12 | injectTapEventPlugin(); 13 | 14 | const styles = { 15 | wrapper: { 16 | display: 'flex', 17 | flexDirection: 'column', 18 | backgroundColor: '#edecec', 19 | }, 20 | }; 21 | 22 | const prefixedStyles = {}; 23 | 24 | const Wrapper = (props) => { 25 | const { 26 | children, 27 | theme, 28 | } = props 29 | 30 | const muiTheme = getMuiTheme(theme); 31 | 32 | if (!prefixedStyles.wrapper) { 33 | const prefix = autoprefixer(muiTheme); 34 | prefixedStyles.wrapper = prefix(styles.wrapper); 35 | } 36 | 37 | return ( 38 | 39 |
40 | { children } 41 |
42 |
43 | ); 44 | }; 45 | 46 | Wrapper.propTypes = { 47 | children: PropTypes.node, 48 | theme: PropTypes.object.isRequired, 49 | } 50 | 51 | Wrapper.defaultProps = { 52 | theme: defaultTheme, 53 | } 54 | 55 | export default Wrapper; -------------------------------------------------------------------------------- /website/src/ui/containers/NotFound/NotFound.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes, 3 | } from 'react'; 4 | import { 5 | connect, 6 | } from 'react-redux'; 7 | import { 8 | push, 9 | } from 'react-router-redux'; 10 | 11 | import { 12 | Card, 13 | CardTitle, 14 | CardText, 15 | CardActions, 16 | } from 'material-ui/Card'; 17 | 18 | import RaisedButton from 'material-ui/RaisedButton'; 19 | import Paper from 'material-ui/Paper'; 20 | 21 | import { 22 | HOME_ROUTE, 23 | } from '../../../common'; 24 | 25 | const NotFound = (props) => { 26 | const { 27 | onClick, 28 | } = props; 29 | 30 | return ( 31 | 32 | 33 | 36 | 37 | The page {window.location.href} could not be found. 38 | 39 | 40 | 45 | 46 | 47 | 48 | ) 49 | }; 50 | 51 | NotFound.propTypes = { 52 | onClick:PropTypes.func.isRequired, 53 | }; 54 | 55 | const mapDispatchToProps = { 56 | onClick: () => push(HOME_ROUTE), 57 | }; 58 | 59 | export default connect( 60 | null, 61 | mapDispatchToProps 62 | )(NotFound); -------------------------------------------------------------------------------- /website/src/APIManager/HttpProvider.js: -------------------------------------------------------------------------------- 1 | import HttpError from './HttpError'; 2 | 3 | /** 4 | * complete an API call 5 | * @param {String} url - URL to request 6 | * @param {Object} options - Useful options to build the request 7 | */ 8 | const HttpProvider = (url, options={}) => { 9 | 10 | /* Set request headers */ 11 | const requestHeaders = options.headers || new Headers({Accept: 'application/json'}); 12 | 13 | requestHeaders.set('Content-Type', 'application/json'); 14 | 15 | if (options.csrfToken) { 16 | requestHeaders.set('X-CSRFToken', options.csrfToken); 17 | } 18 | 19 | return ( 20 | fetch(url, { 21 | ...options, 22 | headers: requestHeaders, 23 | mode: 'cors', // indicates that cross origin request must be perform 24 | credentials: 'include', // indicates the user agent to include cookies from other domain 25 | }) 26 | .then(response => ( 27 | response.text() 28 | .then(text => ({ 29 | status: response.status, 30 | statusText: response.statusText, 31 | headers: response.headers, 32 | body: text, 33 | }) 34 | ) 35 | ) 36 | ) 37 | .then(({status, statusText, headers, body}) => { 38 | let json; 39 | try { 40 | json = JSON.parse(body); 41 | } catch (e) { 42 | } 43 | 44 | if (status < 200 || status >= 300) { 45 | return Promise.reject(new HttpError({statusText, ...json}, status)); 46 | } 47 | return { status, headers, body, json }; 48 | }) 49 | ); 50 | }; 51 | 52 | export default HttpProvider; -------------------------------------------------------------------------------- /flask-api/.gitignore: -------------------------------------------------------------------------------- 1 | # Data 2 | *.db 3 | *.db-journal 4 | data/ 5 | *.csv 6 | *.xlsx 7 | *.xls 8 | *.pickle 9 | *.log 10 | config/*.cfg 11 | 12 | 13 | *.ipynb 14 | .idea/ 15 | .ipynb_checkpoints/* 16 | *.py[co] 17 | *.DS_* 18 | # Packages 19 | *.egg 20 | *.egg-info 21 | dist 22 | build 23 | eggs 24 | parts 25 | bin 26 | var 27 | sdist 28 | develop-eggs 29 | .installed.cfg 30 | 31 | # Installer logs 32 | pip-log.txt 33 | 34 | # Unit test / coverage reports 35 | .coverage 36 | .tox 37 | 38 | #Translations 39 | *.mo 40 | 41 | #Mr Developer 42 | venv 43 | *.pyc 44 | 45 | 46 | 47 | 48 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 49 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 50 | 51 | # User-specific stuff: 52 | .idea/workspace.xml 53 | .idea/tasks.xml 54 | .idea/dictionaries 55 | .idea/vcs.xml 56 | .idea/jsLibraryMappings.xml 57 | 58 | # Sensitive or high-churn files: 59 | .idea/dataSources.ids 60 | .idea/dataSources.xml 61 | .idea/dataSources.local.xml 62 | .idea/sqlDataSources.xml 63 | .idea/dynamic.xml 64 | .idea/uiDesigner.xml 65 | 66 | # Gradle: 67 | .idea/gradle.xml 68 | .idea/libraries 69 | 70 | # Mongo Explorer plugin: 71 | .idea/mongoSettings.xml 72 | 73 | ## File-based project format: 74 | *.iws 75 | 76 | ## Plugin-specific files: 77 | 78 | # IntelliJ 79 | /out/ 80 | 81 | # mpeltonen/sbt-idea plugin 82 | .idea_modules/ 83 | 84 | # JIRA plugin 85 | atlassian-ide-plugin.xml 86 | 87 | # Crashlytics plugin (for Android Studio and IntelliJ) 88 | com_crashlytics_export_strings.xml 89 | crashlytics.properties 90 | crashlytics-build.properties 91 | fabric.properties -------------------------------------------------------------------------------- /website/src/ui/containers/Layout/Layout.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | 5 | import getMuiTheme from 'material-ui/styles/getMuiTheme'; 6 | import autoprefixer from 'material-ui/utils/autoprefixer'; 7 | 8 | import AppBar from './AppBar'; 9 | import SideBar from './SideBar'; 10 | import defaultTheme from '../defaultTheme'; 11 | 12 | const styles = { 13 | main: { 14 | display: 'flex', 15 | flexDirection: 'column', 16 | minHeight: '100vh', 17 | }, 18 | body: { 19 | display: 'flex', 20 | flex: 1, 21 | overflow: 'hidden', 22 | }, 23 | content: { 24 | flex: 1, 25 | padding: '1em', 26 | }, 27 | }; 28 | 29 | const prefixedStyles = {}; 30 | 31 | const Layout = (props) => { 32 | const { 33 | children, 34 | menu, 35 | theme, 36 | title, 37 | } = props 38 | 39 | const muiTheme = getMuiTheme(theme); 40 | 41 | if (!prefixedStyles.main) { 42 | const prefix = autoprefixer(muiTheme); 43 | prefixedStyles.main = prefix(styles.main); 44 | prefixedStyles.body = prefix(styles.body); 45 | prefixedStyles.content = prefix(styles.content); 46 | } 47 | 48 | return ( 49 |
50 | 51 |
52 |
{ children }
53 | 54 | { menu } 55 | 56 |
57 |
58 | ); 59 | }; 60 | 61 | Layout.propTypes = { 62 | children: PropTypes.node, 63 | menu: PropTypes.element, 64 | title: PropTypes.string.isRequired, 65 | theme: PropTypes.object.isRequired, 66 | } 67 | 68 | Layout.defaultProps = { 69 | theme: defaultTheme, 70 | } 71 | 72 | export default Layout; -------------------------------------------------------------------------------- /website/src/Routes.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { 3 | IndexRoute, 4 | Route, 5 | } from 'react-router'; 6 | import HomeIcon from 'material-ui/svg-icons/action/home'; 7 | import VisibilityOffIcon from 'material-ui/svg-icons/action/visibility-off'; 8 | 9 | import Wrapper from './ui/containers/Wrapper/Wrapper'; 10 | import Login from './ui/containers/Login/Login'; 11 | import Layout from './ui/containers/Layout/Layout'; 12 | import Menu from './ui/containers/Layout/Menu'; 13 | import Home from './ui/containers/Home/Home'; 14 | import NotFound from './ui/containers/NotFound/NotFound'; 15 | import { 16 | AuthRequired, 17 | UnauthRequired, 18 | } from './ui/containers/Auth'; 19 | import { 20 | HOME_ROUTE, 21 | AUTH, 22 | LOGIN, 23 | } from './common'; 24 | 25 | const menuItems = [ 26 | { 27 | name: "Home", 28 | path: HOME_ROUTE, 29 | icon: HomeIcon, 30 | }, 31 | { 32 | name: "Nowhere", 33 | path: '/no-where', 34 | icon: VisibilityOffIcon, 35 | }, 36 | ]; 37 | 38 | const MenuComponent = () => ( 39 | 40 | ); 41 | 42 | const LayoutComponent = ({children}) => { 43 | return ( 44 | } 47 | > 48 | { children } 49 | 50 | ); 51 | }; 52 | 53 | const getRoutes = () => { 54 | return ( 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | ); 69 | }; 70 | 71 | export default getRoutes; -------------------------------------------------------------------------------- /flask-api/flask_api/user/manager.py: -------------------------------------------------------------------------------- 1 | from flask_script import Manager, prompt, prompt_pass, prompt_choices 2 | from flask_security.utils import encrypt_password 3 | from .helpers import user_datastore 4 | 5 | 6 | manager = Manager(usage="Perform user database management") 7 | 8 | 9 | @manager.command 10 | def create_role(): 11 | """ 12 | Creates a role in the database" 13 | """ 14 | name = prompt("Please enter the name of the Role ?", default='user') 15 | user_datastore.find_or_create_role(name) 16 | user_datastore.commit() 17 | 18 | 19 | @manager.command 20 | def create_user(): 21 | """ 22 | Creates a user in the database 23 | """ 24 | email = prompt("Please enter your email address ?", default='user.name@domain.com') 25 | 26 | password_match = False 27 | while not password_match: 28 | password = prompt_pass("Please enter your password ?", default='password') 29 | confirm_password = prompt_pass("Please confirm your password ?", default='password') 30 | password_match = password == confirm_password 31 | 32 | role = prompt_choices("Please enter your role ?", 33 | choices=[role.name for role in user_datastore.role_model.query], 34 | resolve=str, 35 | default='user') 36 | 37 | first_name = prompt("Please enter your first name ?", default="user") 38 | last_name = prompt("Please enter your first name ?", default="name") 39 | user_name = prompt("Please enter your first name ?", default="uname") 40 | 41 | user_datastore.create_user(email=email, 42 | password=encrypt_password(password), 43 | roles=[role], 44 | first_name=first_name.capitalize(), 45 | last_name=last_name.capitalize(), 46 | user_name=user_name) 47 | user_datastore.commit() 48 | -------------------------------------------------------------------------------- /flask-api/config/cfg.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import datetime 3 | import os 4 | from os.path import dirname, abspath 5 | 6 | 7 | class BaseConfig: 8 | APP_NAME = 'Flask-React Boilerplate' 9 | SERVER_NAME = 'localhost:5000' 10 | 11 | # Define the application directory 12 | BASE_DIR = abspath(dirname(dirname(__file__))) 13 | 14 | 15 | class DatabaseConfig: 16 | # Define the database 17 | SQLALCHEMY_TRACK_MODIFICATIONS = True 18 | DATABASE_CONNECT_OPTIONS = {} 19 | SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BaseConfig.BASE_DIR, 'app.db') 20 | 21 | 22 | class SessionCookieConfig: 23 | PERMANENT_SESSION_LIFETIME = datetime.timedelta(days=7) 24 | SESSION_COOKIE_HTTPONLY = False 25 | 26 | 27 | class CSRFConfig: 28 | # Enable protection agains *Cross-site Request Forgery (CSRF)* 29 | CSRF_ENABLED = True 30 | WTF_CSRF_FIELD_NAME = 'csrfToken' 31 | WTF_CSRF_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'] 32 | 33 | 34 | class PasswordSecurityConfig: 35 | # Config related to password security 36 | SECURITY_PASSWORD_HASH = 'bcrypt' 37 | SECURITY_PASSWORD_MINIMAL_LENGTH = 8 38 | 39 | 40 | class DevelopmentConfig(BaseConfig, DatabaseConfig, SessionCookieConfig, CSRFConfig, PasswordSecurityConfig): 41 | DEBUG = True 42 | 43 | 44 | config = { 45 | 'development': DevelopmentConfig, 46 | } 47 | 48 | 49 | def set_config(app, config_name='development'): 50 | if not os.path.isfile('config/secrets.cfg'): 51 | from config.secret_generator import generate_secrets_file 52 | generate_secrets_file('config/secrets.cfg') 53 | 54 | secrets_config = read_config_file('config/secrets.cfg') 55 | 56 | app.config.from_object(config[config_name]) 57 | app.config = {**app.config, **secrets_config} 58 | 59 | return app.config 60 | 61 | 62 | def read_config_file(path): 63 | if not os.path.isfile(path): 64 | raise FileExistsError(path + ' configuration file does not exist. Please create it.') 65 | 66 | config_parser = configparser.ConfigParser() 67 | config_parser.read(path) 68 | return {key.upper(): config_parser[section][key] for section in config_parser.sections() for key in config_parser[section]} 69 | -------------------------------------------------------------------------------- /website/src/redux/actions/auth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Authentification actions 3 | */ 4 | import { 5 | GET, 6 | POST, 7 | PUT, 8 | } from '../../APIManager'; 9 | import { 10 | AUTH_API_BASE_URL, 11 | LOAD_AUTH_RESOURCE, 12 | LOGIN_RESOURCE, 13 | LOGOUT_RESOURCE, 14 | } from '../../common'; 15 | 16 | /* For loading user authentification from server */ 17 | export const LOAD_AUTH = 'LOAD_AUTH'; 18 | export const LOAD_AUTH_REQUEST = 'LOAD_AUTH_REQUEST'; 19 | export const LOAD_AUTH_SUCCESS = 'LOAD_AUTH_SUCCESS'; 20 | export const LOAD_AUTH_FAILURE = 'LOAD_AUTH_FAILURE'; 21 | export const LOAD_AUTH_CANCEL = 'LOAD_AUTH_CANCEL'; 22 | 23 | /** 24 | * Load authentification action creator 25 | */ 26 | export const loadAuth = () => ({ 27 | type: LOAD_AUTH, 28 | meta: { 29 | APIBaseUrl: AUTH_API_BASE_URL, 30 | resource: LOAD_AUTH_RESOURCE, 31 | requestType: GET, 32 | } 33 | }) 34 | 35 | /* For login user on server */ 36 | export const LOGIN = 'LOGIN'; 37 | export const LOGIN_REQUEST = 'LOGIN_REQUEST'; 38 | export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; 39 | export const LOGIN_FAILURE = 'LOGIN_FAILURE'; 40 | export const LOGIN_CANCEL = 'LOGIN_CANCEL'; 41 | 42 | /** 43 | * Login action creator 44 | * @param {object} values - Login credentials 45 | * @param {string} [formName] - if the login action is dispatched using redux-form () 46 | * @param {string} [csrfToken] - csrf token 47 | */ 48 | export const login = (values, formName, csrfToken) => ({ 49 | type: LOGIN, 50 | payload: values, 51 | meta: { 52 | APIBaseUrl: AUTH_API_BASE_URL, 53 | resource: LOGIN_RESOURCE, 54 | requestType: POST, 55 | formName, 56 | csrfToken, 57 | }, 58 | }) 59 | 60 | /* For logout user on server */ 61 | export const LOGOUT= 'LOGOUT'; 62 | export const LOGOUT_REQUEST = 'LOGOUT_REQUEST'; 63 | export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; 64 | export const LOGOUT_FAILURE = 'LOGOUT_FAILURE'; 65 | export const LOGOUT_CANCEL = 'LOGOUT_CANCEL'; 66 | 67 | /** 68 | * Logout action creator 69 | * @param {string} [csrfToken] csrf token 70 | */ 71 | export const logout = (csrfToken) => ({ 72 | type: LOGOUT, 73 | meta: { 74 | APIBaseUrl: AUTH_API_BASE_URL, 75 | resource: LOGOUT_RESOURCE, 76 | requestType: PUT, 77 | csrfToken, 78 | }, 79 | }) 80 | 81 | export const AUTH_ACTION_TYPES = [LOAD_AUTH, LOGIN, LOGOUT] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Flask-React-Boilerplate 2 | This project has been developped in order to gather best practices at 3 | - **Building React Single Page Applications** that allow to fetch data from Web APIs 4 | - **Building Python Flask REST APIs** that efficiently and safely expose data to the Web 5 | 6 | This project is intended for developpers who desire to accomodate with React and/or Flask technologies. It covers a large panel of librairies and aims to include best practices at developping robust Web Applications. 7 | 8 | This boilerplate is made of 2 independant projects one for React Single Page Application and one for Python Flask API. A reader interested in only one of these 2 technologies can totally give focus on it without meeting any misunderstanding. Nevertheless both projects are designed to be compatible. 9 | 10 | ## Packages 11 | ### React 12 | - [Create-React-App](https://github.com/facebookincubator/create-react-app) - Facebook project intended to easily package React Applications 13 | - [Redux](https://github.com/reactjs/redux) - Very popular package that allows proper Application State management 14 | - [React-Router](https://github.com/ReactTraining/react-router) - Package that allows to dynamically manage Applications Route 15 | - [Redux-Saga](https://github.com/redux-saga/redux-saga) - Package that properly handles side effects (e.g. asynchronous fetch calls) 16 | - [Redux-Form](https://github.com/erikras/redux-form) - Package that allows to easily synchonize forms and Redux state 17 | - [Material-UI](https://github.com/callemall/material-ui) - Library of React components that implements *Google Material Design* specification 18 | 19 | ### Python 20 | - [Flask](https://github.com/pallets/flask) - Python microframework for Web development. 21 | - [Flask-RESTful](https://github.com/flask-restful/flask-restful) - Flask extension that allows to easily expose REST APIs 22 | - [Flask-Login](https://github.com/maxcountryman/flask-login) - Flask extension that manages user session (login, logout, etc.) 23 | - [Flask-WTF](https://github.com/lepture/flask-wtf) - Flask extension that allows to handle forms. It also includes CSRF protection 24 | - [SQLAlchemy](https://github.com/zzzeek/sqlalchemy) - Object Relationship Mapper (ORM) that allows easy dialog with SQL databases 25 | - [Marshmallow](https://github.com/marshmallow-code/marshmallow) - Convenient package to serialize/deserialize Python objects into json format 26 | - [Flask-Script](https://github.com/smurfix/flask-script) - Convenient Flask extension that allows to implement CLI commands -------------------------------------------------------------------------------- /flask-api/flask_api/user/models.py: -------------------------------------------------------------------------------- 1 | from flask_security import RoleMixin, UserMixin 2 | 3 | from ..extensions import db 4 | from ..common.constants import STRING_LENGTH 5 | from ..user.constants import ROLE_TABLE_NAME, ROLE_NAME_LENGTH, \ 6 | USER_TABLE_NAME, USER_EMAIL_LENGTH, USER_PASSWORD_LENGTH, \ 7 | USER_LAST_NAME_LENGTH, USER_FIRST_NAME_LENGTH, USER_USER_NAME_LENGTH, \ 8 | SEX_TYPES, SEX_OTHER, USER_STATUS, STATUS_NEW 9 | 10 | # n-n mapping table between users and roles 11 | user_role = db.Table('%s_%s' % (USER_TABLE_NAME, ROLE_TABLE_NAME), 12 | db.Column('user_id', db.Integer(), db.ForeignKey('%s.id' % USER_TABLE_NAME)), 13 | db.Column('role_id', db.Integer(), db.ForeignKey('%s.id' % ROLE_TABLE_NAME))) 14 | 15 | 16 | class Role(db.Model, RoleMixin): 17 | __tablename__ = ROLE_TABLE_NAME 18 | 19 | id = db.Column(db.Integer(), primary_key=True) 20 | name = db.Column(db.String(ROLE_NAME_LENGTH), unique=True) 21 | description = db.Column(db.String(STRING_LENGTH)) 22 | 23 | def __repr__(self): 24 | return '' % self.name 25 | 26 | 27 | class User(db.Model, UserMixin): 28 | __tablename__ = USER_TABLE_NAME 29 | 30 | id = db.Column(db.Integer, primary_key=True) 31 | 32 | email = db.Column(db.String(USER_EMAIL_LENGTH), nullable=False, unique=True) 33 | password = db.Column(db.String(USER_PASSWORD_LENGTH), nullable=False) 34 | 35 | last_name = db.Column(db.String(USER_LAST_NAME_LENGTH)) 36 | first_name = db.Column(db.String(USER_FIRST_NAME_LENGTH)) 37 | user_name = db.Column(db.String(USER_USER_NAME_LENGTH)) 38 | 39 | _sex = db.Column(db.Integer(), nullable=False, default=SEX_OTHER) 40 | 41 | def _get_sex(self): 42 | return SEX_TYPES.get(self._sex) 43 | 44 | def _set_sex(self, sex): 45 | self._sex = sex 46 | 47 | sex = db.synonym('_sex', descriptor=property(_get_sex, _set_sex)) 48 | 49 | active = db.Column(db.Boolean()) 50 | _status = db.Column(db.Integer(), nullable=False, default=STATUS_NEW) 51 | 52 | def _get_status(self): 53 | return USER_STATUS.get(self._status) 54 | 55 | def _set_status(self, status): 56 | self._status = status 57 | 58 | status = db.synonym('_status', descriptor=property(_get_status, _set_status)) 59 | 60 | confirmed_at = db.Column(db.DateTime()) 61 | 62 | roles = db.relationship('Role', 63 | secondary=user_role, 64 | backref=db.backref('users', lazy='dynamic')) 65 | 66 | def __repr__(self): 67 | return '' % self.email 68 | 69 | -------------------------------------------------------------------------------- /website/src/ui/containers/Layout/UserBox.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes, 3 | } from 'react'; 4 | import { 5 | connect, 6 | } from 'react-redux'; 7 | 8 | import MenuItem from 'material-ui/MenuItem'; 9 | import IconMenu from 'material-ui/IconMenu'; 10 | import IconButton from 'material-ui/IconButton'; 11 | import InputIcon from 'material-ui/svg-icons/action/input'; 12 | import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; 13 | import CircularProgress from 'material-ui/CircularProgress'; 14 | import { 15 | getStyles as getAppBarStyles, 16 | } from 'material-ui/AppBar/AppBar'; 17 | import { 18 | logout as logoutAction, 19 | setUserBoxVisibility, 20 | } from '../../../redux/actions'; 21 | 22 | 23 | const UserBoxIcon = (props, context) => { 24 | const { 25 | onLogout, 26 | open, 27 | auth: { 28 | status: { 29 | logout, 30 | } 31 | }, 32 | onRequestChange, 33 | } = props; 34 | 35 | const styles = getAppBarStyles(props, context); 36 | 37 | return ( 38 | 41 | 42 | 43 | } 44 | anchorOrigin={{vertical:'bottom', horizontal:'right',}} 45 | targetOrigin={{vertical:'top', horizontal:'right',}} 46 | open={open} 47 | onRequestChange={onRequestChange} 48 | > 49 | : } 53 | /> 54 | 55 | ); 56 | }; 57 | 58 | UserBoxIcon.propTypes = { 59 | onLogout: PropTypes.func.isRequired, 60 | open: PropTypes.bool.isRequired, 61 | logout: PropTypes.oneOfType([ 62 | PropTypes.object, 63 | ]), 64 | onRequestChange: PropTypes.func.isRequired 65 | }; 66 | 67 | UserBoxIcon.contextTypes = { 68 | muiTheme: PropTypes.object.isRequired, 69 | }; 70 | 71 | const mapStateToProps = (state) => ({ 72 | auth: state.auth, 73 | open: state.ui.userBoxOpen, 74 | }); 75 | 76 | const mapDispatchToProps = (dispatch) => ({ 77 | onLogout: (csrfToken) => dispatch(logoutAction(csrfToken)), 78 | onRequestChange: (value) => dispatch(setUserBoxVisibility(value)), 79 | }); 80 | 81 | const mergeProps = (stateProps, dispatchProps) => ({ 82 | ...stateProps, 83 | ...dispatchProps, 84 | onLogout: () => dispatchProps.onLogout(stateProps.auth.csrfToken), 85 | }); 86 | 87 | export default connect( 88 | mapStateToProps, 89 | mapDispatchToProps, 90 | mergeProps 91 | )(UserBoxIcon); 92 | -------------------------------------------------------------------------------- /website/src/ui/containers/Home/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /website/src/redux/saga/appSaga/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | put, 3 | take, 4 | call, 5 | fork, 6 | takeEvery, 7 | takeLatest, 8 | race, 9 | } from 'redux-saga/effects'; 10 | import { 11 | push, 12 | } from 'react-router-redux'; 13 | 14 | import createFetchSaga from './fetchSaga'; 15 | 16 | import { 17 | loadAuth, 18 | LOAD_AUTH, 19 | LOGIN, 20 | LOGOUT, 21 | FETCH_FAILURE, 22 | AUTH_ACTION_TYPES, 23 | } from '../../actions'; 24 | import { 25 | HOME_ROUTE, 26 | AUTH_LOGIN_ROUTE, 27 | } from '../../../common'; 28 | 29 | /** 30 | * App Saga creator 31 | * @param {function} APIManager - function that perform API fetch calls 32 | */ 33 | function createAppSaga(APIManager) { 34 | 35 | const handleFetch = createFetchSaga(APIManager); 36 | /** 37 | * App saga ran each time a user connects to the app 38 | */ 39 | function* appSaga() { 40 | while (true) { 41 | /* Make an API call to load user authentification */ 42 | yield fork(handleFetch, loadAuth()); 43 | 44 | /* Waits for outcome from the authentification loading task */ 45 | const authTaskOutcomeAction = yield take([`${LOAD_AUTH}_FAILURE`, `${LOAD_AUTH}_SUCCESS`]); 46 | 47 | if (authTaskOutcomeAction.type === `${LOAD_AUTH}_FAILURE`) { 48 | /* If Authentification loading failed then user is redirected to the login page */ 49 | yield put(push(AUTH_LOGIN_ROUTE)); 50 | 51 | function* loginCycle() { 52 | yield takeLatest(LOGIN, handleFetch); 53 | } 54 | 55 | /** 56 | * Starts a race that accepts LOGIN requests and finishes when a succesful login action is dispatched to the server 57 | */ 58 | yield race({ 59 | loginCycle: call(loginCycle), 60 | loginSuccess: take(`${LOGIN}_SUCCESS`), 61 | }); 62 | } 63 | 64 | yield put(push(HOME_ROUTE)); 65 | 66 | /** 67 | * Reaching this point means user is correctly logged in. 68 | * From now on user can 69 | * - load authentification 70 | * - perform fetch request 71 | * - logout 72 | * In case we detect 73 | * - a successful logout 74 | * - any fetch authentification error with status 401 75 | */ 76 | 77 | function* loadAuthCycle() { 78 | yield takeLatest(LOAD_AUTH, handleFetch); 79 | }; 80 | 81 | function* logoutCycle() { 82 | yield takeLatest(LOGOUT, handleFetch); 83 | }; 84 | 85 | function* fetchCycle() { 86 | yield takeEvery(action => action.meta && action.meta.fetch && !AUTH_ACTION_TYPES.includes(action.type), handleFetch); 87 | }; 88 | 89 | yield race({ 90 | logoutSuccess: take(`${LOGOUT}_SUCCESS`), 91 | unauthFailure: take(action => (action.type === FETCH_FAILURE && action.payload.status === 401)), 92 | loadAuthCycle: call(loadAuthCycle), 93 | logoutCycle: call(logoutCycle), 94 | fetchCycle: call(fetchCycle), 95 | }); 96 | 97 | /* Come back to the beginning of the loop */ 98 | } 99 | }; 100 | 101 | return appSaga; 102 | }; 103 | 104 | export default createAppSaga; -------------------------------------------------------------------------------- /website/src/APIManager/APIManager.js: -------------------------------------------------------------------------------- 1 | export const GET = 'GET'; 2 | export const POST = 'POST'; 3 | export const PUT = 'PUT'; 4 | 5 | /** 6 | * Request manager that build API calls and handles responses from API. 7 | * @param {Func} httpClient - HTTP client that return a fetch promise base on a given url and options 8 | */ 9 | const APIManager = (httpClient) => { 10 | /** 11 | * Function that computes the url to fetch and options to be used for fetching 12 | * @param {String} type - extended type of request 13 | * @param {String} APIBaseURL - url of the API to fetch data from 14 | * @param {String} resource - resource to fetch 15 | * @param {Object} params - provided parameters 16 | */ 17 | const makeOptions = (type, APIBaseURL, resource, params) => { 18 | let url; 19 | const options = {}; 20 | 21 | switch (type) { 22 | case GET: 23 | url = `${APIBaseURL}/${resource}`; 24 | options.method = 'GET'; 25 | break; 26 | 27 | case POST: 28 | url = `${APIBaseURL}/${resource}`; 29 | options.method = 'POST'; 30 | options.body = JSON.stringify(params.data); 31 | break; 32 | 33 | case PUT: 34 | url = `${APIBaseURL}/${resource}`; 35 | options.method = 'PUT'; 36 | break; 37 | 38 | default: 39 | throw new Error(`Unsupported fetch action type ${type}`); 40 | } 41 | 42 | if (params && params.csrfToken) { 43 | options.csrfToken = params.csrfToken 44 | } 45 | 46 | return {url, options}; 47 | }; 48 | 49 | /** 50 | * Function that handles responses from API 51 | * @param {Object} response - HTTP response 52 | * @param {String} type - extended type of request 53 | * @param {String} APIBaseURL - url of the API to fetch data from 54 | * @param {String} resource - resource to fetch 55 | * @param {String} params - provided parameters 56 | */ 57 | const handleResponse = (response, type, APIBaseURL, resource, params) => { 58 | switch (type) { 59 | default: 60 | return response && response.json ? response.json : undefined; 61 | } 62 | }; 63 | 64 | /** 65 | * Function that handles errors from API 66 | * @param {Object} error - error 67 | * @param {String} type - extended type of request 68 | * @param {String} APIBaseURL - url of the API to fetch data from 69 | * @param {String} resource - resource to fetch 70 | * @param {String} params - provided parameters 71 | */ 72 | const handleError = (error, type, APIBaseURL, resource, params) => { 73 | switch (type) { 74 | default: 75 | return Promise.reject(error); 76 | } 77 | }; 78 | 79 | /** 80 | * Function that perform fetch 81 | * @param {String} type - extended type of request 82 | * @param {String} APIBaseURL - url of the API to fetch data from 83 | * @param {String} resource - resource to fetch 84 | * @param {String} params - provided parameters 85 | */ 86 | const manageFetch = (type, APIBaseURL, resource, params) => { 87 | const { 88 | url, 89 | options 90 | } = makeOptions(type, APIBaseURL, resource, params); 91 | return ( 92 | httpClient(url, options).then( 93 | response => handleResponse(response, type, APIBaseURL, resource, params), 94 | error => handleError(error, type, APIBaseURL, resource, params) 95 | ) 96 | ); 97 | }; 98 | 99 | return manageFetch; 100 | }; 101 | 102 | export default APIManager; -------------------------------------------------------------------------------- /website/src/ui/containers/Login/Login.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | PropTypes 3 | } from 'react'; 4 | import { 5 | connect, 6 | } from 'react-redux'; 7 | import { 8 | propTypes, 9 | reduxForm, 10 | Field, 11 | } from 'redux-form'; 12 | import { 13 | login, 14 | } from '../../../redux/actions'; 15 | import compose from 'recompose/compose'; 16 | 17 | import getMuiTheme from 'material-ui/styles/getMuiTheme'; 18 | import autoprefixer from 'material-ui/utils/autoprefixer'; 19 | import LockIcon from 'material-ui/svg-icons/action/lock-outline'; 20 | import { 21 | Card, 22 | CardActions, 23 | } from 'material-ui/Card'; 24 | import Avatar from 'material-ui/Avatar'; 25 | import RaisedButton from 'material-ui/RaisedButton'; 26 | import CircularProgress from 'material-ui/CircularProgress'; 27 | 28 | import defaultTheme from '../defaultTheme'; 29 | 30 | import TextInput from '../../components/TextInput'; 31 | 32 | const styles = { 33 | body: { 34 | display: 'flex', 35 | flexDirection: 'column', 36 | minHeight: '100vh', 37 | alignItems: 'center', 38 | justifyContent: 'center', 39 | }, 40 | 41 | card: { 42 | minWidth: 300, 43 | }, 44 | 45 | avatar: { 46 | margin: '1em', 47 | textAlign: 'center', 48 | }, 49 | 50 | form: { 51 | padding: '0 1em 1em 1em' 52 | }, 53 | 54 | input: { 55 | display: 'flex', 56 | }, 57 | }; 58 | 59 | const prefixedStyles = {}; 60 | 61 | const Login = (props) => { 62 | const { 63 | handleSubmit, 64 | onSubmit, 65 | submitting, 66 | theme 67 | } = props; 68 | 69 | const muiTheme = getMuiTheme(theme); 70 | if (!prefixedStyles.main) { 71 | const prefix = autoprefixer(muiTheme); 72 | prefixedStyles.body = prefix(styles.body); 73 | prefixedStyles.card = prefix(styles.card); 74 | prefixedStyles.avatar = prefix(styles.avatar); 75 | prefixedStyles.form = prefix(styles.form); 76 | prefixedStyles.input = prefix(styles.input); 77 | } 78 | 79 | return ( 80 |
81 | 82 |
83 | } size={60} /> 84 |
85 | 86 |
87 |
88 |
89 | 96 |
97 |
98 | 105 |
106 |
107 | 108 | } 114 | fullWidth 115 | /> 116 | 117 |
118 |
119 |
120 | ); 121 | } 122 | 123 | Login.propTypes = { 124 | ...propTypes, 125 | theme: PropTypes.object.isRequired, 126 | csrfToken: PropTypes.string, 127 | } 128 | 129 | Login.defaultProps = { 130 | theme: defaultTheme, 131 | } 132 | 133 | const mapStateToProps = (state) => ({ 134 | csrfToken: state.auth.csrfToken, 135 | }); 136 | 137 | const onSubmit = (values, dispatch, props) => { 138 | dispatch(login(values, props.form, props.csrfToken)) 139 | }; // when dispatching a LOGIN action it triggers a fetch saga 140 | 141 | const enhance = compose( 142 | connect(mapStateToProps), 143 | reduxForm({ 144 | form: "login", 145 | onSubmit, 146 | }) 147 | ); 148 | 149 | export default enhance(Login); 150 | 151 | -------------------------------------------------------------------------------- /flask-api/flask_api/resources/auth.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from flask import Blueprint, request, after_this_request, jsonify 4 | from flask_restful import Api, Resource 5 | from flask_restful.utils.cors import crossdomain 6 | from flask_security import login_user, logout_user, current_user 7 | from flask_security.forms import LoginForm 8 | from werkzeug.datastructures import MultiDict 9 | from werkzeug.exceptions import BadRequest, Unauthorized 10 | from werkzeug.wrappers import Response 11 | 12 | from ..user import _commit, user_schema 13 | 14 | from ..common import ALLOWED_CROSS_ORIGIN_DOMAIN 15 | 16 | from ..common.utils import insert_csrf_token 17 | 18 | # Convenient constants 19 | # Resources 20 | AUTH_URL_PREFIX = '/auth' 21 | LOAD_AUTH_RESOURCE = '/loadAuth' 22 | LOGIN_RESOURCE = '/login' 23 | LOGOUT_RESOURCE = '/logout' 24 | 25 | # Messages 26 | UNAUTHORIZED_ERROR_MESSAGE = "User unauthorized to access the requested resource" 27 | LOGIN_ERROR_MESSAGE = "Invalid provided credentials" 28 | 29 | # Make auth API 30 | AUTH_BLUEPRINT_NAME = 'auth' 31 | auth_bp = Blueprint(AUTH_BLUEPRINT_NAME, __name__, url_prefix=AUTH_URL_PREFIX) 32 | auth_api = Api(auth_bp) 33 | 34 | 35 | class LoadAuth(Resource): 36 | """ 37 | Resource responsible for us er authentification loading 38 | """ 39 | @crossdomain(origin=ALLOWED_CROSS_ORIGIN_DOMAIN, credentials=True) 40 | def get(self): 41 | if not current_user.is_authenticated: 42 | # Generate a 401 error response including a csrf token 43 | unauth_error = Unauthorized(UNAUTHORIZED_ERROR_MESSAGE) 44 | content = insert_csrf_token({'data': unauth_error.get_body()}) 45 | return Response(json.dumps(content), unauth_error.code, unauth_error.get_headers()) 46 | else: 47 | return jsonify(insert_csrf_token({'data': user_schema.dump(current_user).data})) 48 | 49 | # Handles preflight OPTIONS http request 50 | @crossdomain(origin=ALLOWED_CROSS_ORIGIN_DOMAIN, methods=['GET'], headers=['content-type'], credentials=True) 51 | def options(self): 52 | # When cross domain decorator is fired on OPTIONS http request a response is automatically sent 53 | # (change param automatic_options to False in order to call the function) 54 | pass 55 | 56 | 57 | class Login(Resource): 58 | """ 59 | Resource responsible for login 60 | """ 61 | @crossdomain(origin=ALLOWED_CROSS_ORIGIN_DOMAIN, credentials=True) 62 | def post(self): 63 | login_form = LoginForm(MultiDict(request.get_json())) 64 | 65 | if login_form.validate_on_submit(): 66 | login_user(login_form.user, remember=login_form.remember.data) 67 | after_this_request(_commit) 68 | return jsonify({'data': user_schema.dump(current_user).data}) 69 | 70 | # login failed 71 | login_error = BadRequest(LOGIN_ERROR_MESSAGE) 72 | return Response(json.dumps({"errors": login_form.errors, "_error": LOGIN_ERROR_MESSAGE}), login_error.code, login_error.get_headers()) 73 | 74 | # Handles preflight OPTIONS http requests 75 | # Since a POST request is expected x-csrftoken header must be allowed in order to enable the main request to transmit the csrf token to the server 76 | @crossdomain(origin=ALLOWED_CROSS_ORIGIN_DOMAIN, methods=['POST'], headers=['content-type', 'x-csrftoken'], credentials=True) 77 | def options(self): 78 | # When cross domain decorator is fired on OPTIONS http request a response is automatically sent 79 | # (change param automatic_options to False in order to call the function) 80 | pass 81 | 82 | 83 | class Logout(Resource): 84 | """ 85 | Resource responsible for logout 86 | """ 87 | @crossdomain(origin=ALLOWED_CROSS_ORIGIN_DOMAIN, credentials=True) 88 | def put(self): 89 | if current_user.is_authenticated: 90 | logout_user() 91 | return jsonify({}) 92 | else: 93 | return Unauthorized(UNAUTHORIZED_ERROR_MESSAGE).get_response() 94 | 95 | # Handles preflight OPTIONS http requests 96 | # Since a POST request is expected x-csrftoken header must be allowed in order to transmit csrf token to the server 97 | @crossdomain(origin=ALLOWED_CROSS_ORIGIN_DOMAIN, methods=['PUT'], headers=['content-type', 'x-csrftoken'], credentials=True) 98 | def options(self): 99 | # When cross domain decorator is fired on OPTIONS http request a response is automatically sent 100 | # (change param automatic_options to False in order to call the function) 101 | pass 102 | 103 | # Add ressources 104 | auth_api.add_resource(LoadAuth, LOAD_AUTH_RESOURCE) 105 | auth_api.add_resource(Login, LOGIN_RESOURCE) 106 | auth_api.add_resource(Logout, LOGOUT_RESOURCE) 107 | -------------------------------------------------------------------------------- /website/src/redux/saga/appSaga/fetchSaga.js: -------------------------------------------------------------------------------- 1 | import { 2 | put, 3 | call, 4 | cancelled, 5 | } from 'redux-saga/effects'; 6 | import { 7 | startSubmit, 8 | stopSubmit, 9 | setSubmitSucceeded, 10 | setSubmitFailed, 11 | } from 'redux-form'; 12 | import { 13 | FETCH_REQUEST, 14 | FETCH_SUCCESS, 15 | FETCH_FAILURE, 16 | FETCH_CANCEL, 17 | } from '../../actions'; 18 | 19 | /** 20 | * Fetch Saga creator 21 | * @param {function} APIManager - function that perform API fetch calls 22 | */ 23 | const createFetchSaga = (APIManager) => { 24 | /** 25 | * Fetch saga to be run on a fetch action 26 | * @param {object} action - fetch action that triggered the saga 27 | */ 28 | function* fetchSaga(action) { 29 | const { 30 | type, 31 | payload, 32 | meta: { 33 | APIBaseUrl, 34 | resource, 35 | requestType, 36 | csrfToken, 37 | formName, 38 | ...meta 39 | } 40 | } = action; 41 | 42 | /* Request dispatchs */ 43 | yield [ 44 | put({ type: FETCH_REQUEST }), // general request dispatch coming with every fetch action 45 | put({ 46 | type: `${type}_REQUEST`, 47 | payload, 48 | meta : { 49 | date: Date.now(), 50 | ...meta, 51 | }, 52 | }), // relative request dispatch for this particular fetch action 53 | formName ? put(startSubmit(formName)) : undefined, // dispatch redux-form START_SUBMIT action 54 | ]; 55 | 56 | let sagaTerminated; // will hold a boolean value indicating wheter the saga has terminated or not 57 | try { 58 | /* Run the API call (this call is blocking) */ 59 | const response = yield call( 60 | APIManager, 61 | requestType, 62 | APIBaseUrl, 63 | resource, 64 | { 65 | data: payload, 66 | csrfToken 67 | } 68 | ); 69 | 70 | /* Indicates that the saga terminated */ 71 | sagaTerminated = true; 72 | 73 | /* Success dispatch */ 74 | yield [ 75 | formName ? put(stopSubmit(formName)) : undefined, // dispatch redux-form STOP_SUBMIT action 76 | formName ? put(setSubmitSucceeded(formName)) : undefined, // dispatch redux-form SET_SUBMIT_SUCCEEDED action 77 | put({ type: FETCH_SUCCESS }), // general success dispatch coming with every fetch action 78 | put({ 79 | type: `${type}_SUCCESS`, 80 | payload: response.data, 81 | meta: { 82 | resource, 83 | payload, 84 | date: Date.now(), 85 | csrfToken: response.csrfToken, 86 | ...meta, 87 | }, 88 | }),// relative success dispatch for this particular fetch action 89 | ]; 90 | } catch(error) { 91 | /* Indicates that the saga terminated */ 92 | sagaTerminated = true; 93 | 94 | /* Failure dispatch */ 95 | yield [ 96 | formName ? put(stopSubmit( 97 | formName, 98 | error && error.message ? error.message.errors : undefined 99 | )) : undefined, // dispatch redux-form STOP_SUBMIT action 100 | formName ? put(setSubmitFailed( 101 | formName, 102 | error && error.message && error.message.errors ? Object.keys(error.message.errors) : undefined 103 | )) : undefined, // dispatch redux-form SET_SUBMIT_FAILED action 104 | put({ 105 | type: FETCH_FAILURE, 106 | payload: error, 107 | error: true, 108 | }), // general failure dispatch coming with every fetch action 109 | put({ 110 | type: `${type}_FAILURE`, 111 | payload: error, 112 | error: true, 113 | meta: { 114 | resource, 115 | payload, 116 | date: Date.now(), 117 | csrfToken: error.message && error.message.csrfToken, 118 | ...meta, 119 | }, 120 | }), // relative failure dispatch for this particular fetch action 121 | ]; 122 | } finally { 123 | /* In case the saga is cancelled before terminating */ 124 | if (!sagaTerminated) { 125 | if (yield cancelled()) { 126 | yield [ 127 | formName ? put(stopSubmit(formName )) : undefined, 128 | put({ type: FETCH_CANCEL }), 129 | put({ 130 | type: `${type}_CANCEL`, 131 | meta: { 132 | resource, 133 | payload, 134 | ...meta, 135 | }, 136 | }), 137 | ]; 138 | } 139 | } 140 | } 141 | }; 142 | 143 | return fetchSaga; 144 | }; 145 | 146 | export default createFetchSaga; -------------------------------------------------------------------------------- /flask-api/README.md: -------------------------------------------------------------------------------- 1 | # Flask-API 2 | This project aims to build a robust Python Flask RESTful API that efficiently and safely exposes data to the Web. It uses [Flask](https://github.com/pallets/flask) as main underlying technology. Choosing Flask can be argued by multiple reasons, main ones being 3 | - Flask is a light weighted framework that has proven its robustness and efficiency 4 | - Flask makes no assumptions on the rest of your stack so it easily integrates with any other Python librairies 5 | - It naturally fits in dockerized microservices architectures 6 | - Flask is very popular and the community is very active, making it very straight forward to skill up on 7 | - More generally, Python is amazing ! :-) 8 | 9 | ## Table of Contents 10 | 1. [Packages](#Packages) 11 | 2. [Getting Started](#getting-started) 12 | 3. [Application Structure](#application-structure) 13 | 4. [Implementation](#implementation) 14 | 5. [Testing](#testing) 15 | 6. [Deployment](#deployment) 16 | 17 | 18 | ## Packages 19 | This project covers usage of multiple libraries that facilitates creating REST APIs with Python, main ones being 20 | - [Flask](https://github.com/pallets/flask) - Python microframework for Web development. 21 | - [Flask-RESTful](https://github.com/flask-restful/flask-restful) - Flask extension that allows to easily expose REST APIs 22 | - [Flask-Login](https://github.com/maxcountryman/flask-login) - Flask extension that manages user session (login, logout, etc.) 23 | - [Flask-WTF](https://github.com/lepture/flask-wtf) - Flask extension that allows to handle forms. It also includes CSRF protection 24 | - [SQLAlchemy](https://github.com/zzzeek/sqlalchemy) - Object Relationship Mapper (ORM) that allows easy dialog with SQL databases 25 | - [Marshmallow](https://github.com/marshmallow-code/marshmallow) - Convenient package to serialize/deserialize Python objects into json format 26 | - [Flask-Script](https://github.com/smurfix/flask-script) - Convenient Flask extension that allows to implement CLI commands 27 | 28 | ## Getting Started 29 | ### Installation 30 | You can get all scripts from this project by cloning the Github repository 31 | ```bash 32 | $ git clone 33 | $ cd flask-api 34 | ``` 35 | 36 | In order to run this project, we highly recommend to use a python virtual environment with a version of Python 3.4 or higher. Assuming you have a Python 3 version installed that is bound to ```python3```, you can create a virtual environment by typing 37 | ```bash 38 | $ virtualenv venv -p python3 39 | ``` 40 | If ```virtualenv``` command is not recognized, you can try to install it via 41 | 42 | ```bash 43 | $ pip install virtualenv 44 | ``` 45 | Once the virtual environment is created you can install all python dependencies 46 | ```bash 47 | $ . venv/bin/activate # on linux and MacOS 48 | $ pip install -r requirements.txt 49 | ``` 50 | For full information concerning ```virtualenv``` please refer to the [official documentation](https://virtualenv.pypa.io/en/stable/). 51 | 52 | ### Running 53 | ***TODO : to be completed*** 54 | 55 | ## Application Structure 56 | The application structure is inspired from [fbone](https://github.com/imwilsonxu/fbone) 57 | ``` 58 | . 59 | ├── config/ # Flask configuration module 60 | │ ├── __init__.py # Manage exports 61 | │ ├── cfg.py # Flask and Flask extensions configurations 62 | │ └── secret_generator.py # Secret keys file generator 63 | ├── flask_api/ # Application source code 64 | │ ├── resources/ # API Resources implementation 65 | │ │ │── __init__.py # Manage exports 66 | │ │ └── auth.py # Main file for layout 67 | │ ├── user/ # User module that allow to access users' information 68 | │ │ ├── __init__.py # Manage exports 69 | │ │ ├── models.py # SQLAlchemy models (User, Role) 70 | │ │ ├── helpers.py # Convenient functions to manipulate SQLAlchemy models 71 | │ │ ├── serializers.py # Marshmallow schema to serialize User SQLAlchemy objects 72 | │ │ ├── manager.py # Flask-Script CLI commands to manipulate User database 73 | │ │ └── constants.py # Set of convenient constants 74 | │ ├── common/ # Set of elements useful for the whole application 75 | │ │ ├── __init__.py # Manage exports 76 | │ │ ├── utils.py # Functions that every-where in the application 77 | │ │ └── constants.py # Set of convenient constants 78 | │ ├── __init__.py # Main HTML page container for app 79 | │ ├── app.py # Functions that allow App instantiation 80 | │ ├── decorators.py # Set of useful decorators 81 | │ └── extensions.py # Instantiate flask extensions () 82 | ├── run.py # Script that run the application 83 | └── manage.py # Flask-Script CLI commands to manipulate initialize databases 84 | ``` 85 | 86 | ## Implementation 87 | ***TODO : to be completed*** 88 | 89 | ## Testing 90 | ***TODO : to be completed and implemented*** 91 | 92 | ## Deployment 93 | ***TODO : to be completed*** 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /website/src/redux/reducers/auth.js: -------------------------------------------------------------------------------- 1 | import { 2 | combineReducers 3 | } from 'redux'; 4 | import { 5 | LOAD_AUTH, 6 | LOGIN, 7 | LOGOUT, 8 | FETCH_ERROR, 9 | } from '../actions'; 10 | /** 11 | * Reducers related to authentification handling 12 | */ 13 | 14 | /* reducer responsible for auth.user management */ 15 | const userReducer = (state = null, action) => { 16 | switch (action.type) { 17 | case `${LOGIN}_SUCCESS`: 18 | return action.payload; 19 | 20 | case `${LOAD_AUTH}_SUCCESS`: 21 | return action.payload; 22 | 23 | case `${LOAD_AUTH}_FAILURE`: 24 | if (action.payload.status === 401) { 25 | return null; 26 | } else { 27 | return state; 28 | } 29 | 30 | case `${LOGOUT}_SUCCESS`: 31 | return null; 32 | 33 | case `${FETCH_ERROR}_FAILURE`: 34 | if (action.payload.status === 401) { 35 | return null; 36 | } else { 37 | return state; 38 | } 39 | 40 | default: 41 | return state; 42 | } 43 | }; 44 | 45 | /* reducer responsible for login status management */ 46 | const loginStatusReducer = (state = null, action) => { 47 | switch (action.type) { 48 | case `${LOGIN}_REQUEST`: 49 | return { 50 | loggingIn: true, 51 | requestDate: action.meta.date, 52 | }; 53 | 54 | case `${LOGIN}_SUCCESS`: 55 | return { 56 | ...state, 57 | loggingIn: false, 58 | successDate: action.meta.date, 59 | }; 60 | 61 | case `${LOGIN}_FAILURE`: 62 | return { 63 | ...state, 64 | loggingIn: false, 65 | failureDate: action.meta.date, 66 | error: action.payload, 67 | }; 68 | 69 | case `${LOGIN}_CANCEL`: 70 | return { 71 | ...state, 72 | loggingIn: false, 73 | cancelDate: action.meta.date, 74 | }; 75 | 76 | case `${LOGOUT}_SUCCESS`: 77 | return null; 78 | 79 | case `${LOAD_AUTH}_FAILURE`: 80 | if (action.payload.status === 401) { 81 | return null; 82 | } else { 83 | return state; 84 | } 85 | 86 | default: 87 | return state; 88 | } 89 | }; 90 | 91 | /* reducer responsible for load authentification status management */ 92 | const loadAuthStatusReducer = (state = null, action) => { 93 | switch (action.type) { 94 | case `${LOAD_AUTH}_REQUEST`: 95 | return { 96 | loading: true, 97 | requestDate: action.meta.date, 98 | }; 99 | 100 | case `${LOAD_AUTH}_SUCCESS`: 101 | return { 102 | ...state, 103 | loading: false, 104 | successDate: action.meta.date, 105 | }; 106 | 107 | case `${LOAD_AUTH}_FAILURE`: 108 | return { 109 | ...state, 110 | loading: false, 111 | failureDate: action.meta.date, 112 | error: action.payload, 113 | }; 114 | 115 | case `${LOAD_AUTH}_CANCEL`: 116 | return { 117 | ...state, 118 | loading: false, 119 | cancelDate: action.meta.date, 120 | }; 121 | 122 | case `${LOGOUT}_SUCCESS`: 123 | return null; 124 | 125 | default: 126 | return state; 127 | } 128 | }; 129 | 130 | /* reducer responsible for logout status management */ 131 | const logoutStatusReducer = (state = null, action) => { 132 | switch (action.type) { 133 | case `${LOGOUT}_REQUEST`: 134 | return { 135 | loggingOut: true, 136 | requestDate: action.meta.date, 137 | }; 138 | 139 | case `${LOGOUT}_SUCCESS`: 140 | return { 141 | ...state, 142 | loggingOut: false, 143 | successDate: action.meta.date, 144 | }; 145 | 146 | case `${LOGOUT}_FAILURE`: 147 | return { 148 | ...state, 149 | loggingOut: false, 150 | failureDate: action.meta.date, 151 | error: action.payload, 152 | }; 153 | 154 | case `${LOGOUT}_CANCEL`: 155 | return { 156 | ...state, 157 | loggingOut: false, 158 | cancelDate: action.meta.date, 159 | }; 160 | 161 | case `${LOGIN}_SUCCESS`: 162 | return null; 163 | 164 | case `${LOAD_AUTH}_SUCCESS`: 165 | return null; 166 | 167 | default: 168 | return state; 169 | } 170 | }; 171 | 172 | /* Reducer responsible for csrf token management */ 173 | const csrfTokenReducer = (state = null, action) => { 174 | switch (action.type) { 175 | case `${LOAD_AUTH}_SUCCESS`: 176 | return action.meta.csrfToken; 177 | 178 | case `${LOAD_AUTH}_FAILURE`: 179 | return action.meta.csrfToken ? action.meta.csrfToken : state; 180 | 181 | default: 182 | return state; 183 | } 184 | }; 185 | 186 | /* Combine all reducers into the auth reducers */ 187 | export default combineReducers({ 188 | user: userReducer, 189 | status: combineReducers({ 190 | load: loadAuthStatusReducer, 191 | login: loginStatusReducer, 192 | logout: logoutStatusReducer, 193 | }), 194 | csrfToken: csrfTokenReducer, 195 | }); 196 | -------------------------------------------------------------------------------- /website/README.md: -------------------------------------------------------------------------------- 1 | # React-SPA 2 | This project aims to build a Single Page Application that properly retrieve data by fecthing some REST API. It uses [React](https://github.com/facebook/react) as main underlying technology. Choosing React can be argued by multiple reasons, main ones being 3 | - React is an high performing Front End library 4 | - React makes no assumptions on the rest of your stack. In particular it can be easily combined with any Back End technology 5 | - React is Component-Based so it allows to write very clear and predictable code (this is even more true when using Redux) 6 | - React is very popular and the community is very active, making it very straight forward to skill up on 7 | 8 | ## Table of Contents 9 | 1. [Packages](#Packages) 10 | 2. [Getting Started](#getting-started) 11 | 3. [Application Structure](#application-structure) 12 | 4. [Implementation](#implementation) 13 | 5. [Testing](#testing) 14 | 6. [Deployment](#deployment) 15 | 16 | ## Packages 17 | This project covers most of what we believe as being the best React libraries 18 | - [Create-React-App](https://github.com/facebookincubator/create-react-app) - Facebook project intended to easily package React Applications 19 | - [Redux](https://github.com/reactjs/redux) - Very popular package that allows proper Application State management 20 | - [React-Router](https://github.com/ReactTraining/react-router) - Package that allows to dynamically manage Applications Route 21 | - [Redux-Saga](https://github.com/redux-saga/redux-saga) - Package that properly handles side effects (e.g. asynchronous fetch calls) 22 | - [Redux-Form](https://github.com/erikras/redux-form) - Package that allows to easily synchonize forms and Redux state 23 | - [Material-UI](https://github.com/callemall/material-ui) - Library of React components that implements *Google Material Design* specification 24 | 25 | ## Getting Started 26 | 27 | ### Requirements 28 | ***TODO : to be completed*** 29 | 30 | ### Installation 31 | You can get all scripts from this project by cloning the Github repository 32 | ```bash 33 | $ git clone 34 | $ cd 35 | ``` 36 | Once the repository is cloned you only need to install all the dependencies for this project 37 | ```bash 38 | $ npm install 39 | ``` 40 | You are ready go ! 41 | 42 | ### Running 43 | ***TODO : to be completed*** 44 | 45 | ## Application Structure 46 | The application structure is inspired from [fbone](https://github.com/imwilsonxu/fbone) 47 | ``` 48 | . 49 | ├── config # Flask configuration module 50 | │ ├── __init__.py # Manage exports 51 | │ ├── cfg.py # Flask and Flask extensions configurations 52 | │ └── secret_generator.py # Secret keys file generator 53 | ├── flask_api # Application source code 54 | │ ├── resources # API Resources implementation 55 | │ │ │── __init__.py # Manage exports 56 | │ │ └── auth.py # Main file for layout 57 | │ ├── user # User module that allow to access users' information 58 | │ │ ├── __init__.py # Manage exports 59 | │ │ ├── models.py # SQLAlchemy models (User, Role) 60 | │ │ ├── helpers.py # Convenient functions to manipulate SQLAlchemy models 61 | │ │ ├── serializers.py # Marshmallow schema to serialize User SQLAlchemy objects 62 | │ │ ├── manager.py # Flask-Script CLI commands to manipulate User database 63 | │ │ └── constants.py # Set of convenient constants 64 | │ ├── common # Set of elements useful for the whole application 65 | │ │ ├── __init__.py # Manage exports 66 | │ │ ├── utils.py # Functions that every-where in the application 67 | │ │ └── constants.py # Set of convenient constants 68 | │ ├── __init__.py # Main HTML page container for app 69 | │ ├── app.py # Functions that allow App instantiation 70 | │ ├── decorators.py # Set of useful decorators 71 | │ └── extensions.py # Instantiate flask extensions () 72 | ├── run.py # Script that run the application 73 | └── manage.py # Flask-Script CLI commands to manipulate initialize databases 74 | ``` 75 | 76 | ## Implementation 77 | ***TODO : to be completed*** 78 | 79 | ## Testing 80 | ***TODO : to be completed and implemented*** 81 | 82 | ## Deployment 83 | ***TODO : to be completed*** 84 | 85 | # 86 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 87 | 88 | Below you will find some information on how to perform common tasks.
89 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 90 | 91 | ## Table of Contents 92 | 93 | - [Updating to New Releases](#updating-to-new-releases) 94 | - [Sending Feedback](#sending-feedback) 95 | - [Folder Structure](#folder-structure) 96 | - [Available Scripts](#available-scripts) 97 | - [npm start](#npm-start) 98 | - [npm test](#npm-test) 99 | - [npm run build](#npm-run-build) 100 | - [npm run eject](#npm-run-eject) 101 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 102 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 103 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 104 | - [Debugging in the Editor](#debugging-in-the-editor) 105 | - [Changing the Page ``](#changing-the-page-title) 106 | - [Installing a Dependency](#installing-a-dependency) 107 | - [Importing a Component](#importing-a-component) 108 | - [Adding a Stylesheet](#adding-a-stylesheet) 109 | - [Post-Processing CSS](#post-processing-css) 110 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 111 | - [Adding Images and Fonts](#adding-images-and-fonts) 112 | - [Using the `public` Folder](#using-the-public-folder) 113 | - [Changing the HTML](#changing-the-html) 114 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 115 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 116 | - [Using Global Variables](#using-global-variables) 117 | - [Adding Bootstrap](#adding-bootstrap) 118 | - [Using a Custom Theme](#using-a-custom-theme) 119 | - [Adding Flow](#adding-flow) 120 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 121 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 122 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 123 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 124 | - [Can I Use Decorators?](#can-i-use-decorators) 125 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 126 | - [Node](#node) 127 | - [Ruby on Rails](#ruby-on-rails) 128 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 129 | - [Using HTTPS in Development](#using-https-in-development) 130 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 131 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 132 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 133 | - [Running Tests](#running-tests) 134 | - [Filename Conventions](#filename-conventions) 135 | - [Command Line Interface](#command-line-interface) 136 | - [Version Control Integration](#version-control-integration) 137 | - [Writing Tests](#writing-tests) 138 | - [Testing Components](#testing-components) 139 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 140 | - [Initializing Test Environment](#initializing-test-environment) 141 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 142 | - [Coverage Reporting](#coverage-reporting) 143 | - [Continuous Integration](#continuous-integration) 144 | - [Disabling jsdom](#disabling-jsdom) 145 | - [Snapshot Testing](#snapshot-testing) 146 | - [Editor Integration](#editor-integration) 147 | - [Developing Components in Isolation](#developing-components-in-isolation) 148 | - [Making a Progressive Web App](#making-a-progressive-web-app) 149 | - [Deployment](#deployment) 150 | - [Static Server](#static-server) 151 | - [Other Solutions](#other-solutions) 152 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 153 | - [Building for Relative Paths](#building-for-relative-paths) 154 | - [Azure](#azure) 155 | - [Firebase](#firebase) 156 | - [GitHub Pages](#github-pages) 157 | - [Heroku](#heroku) 158 | - [Modulus](#modulus) 159 | - [Netlify](#netlify) 160 | - [Now](#now) 161 | - [S3 and CloudFront](#s3-and-cloudfront) 162 | - [Surge](#surge) 163 | - [Advanced Configuration](#advanced-configuration) 164 | - [Troubleshooting](#troubleshooting) 165 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 166 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 167 | - [`npm run build` silently fails](#npm-run-build-silently-fails) 168 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 169 | - [Something Missing?](#something-missing) 170 | 171 | ## Updating to New Releases 172 | 173 | Create React App is divided into two packages: 174 | 175 | * `create-react-app` is a global command-line utility that you use to create new projects. 176 | * `react-scripts` is a development dependency in the generated projects (including this one). 177 | 178 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 179 | 180 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 181 | 182 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 183 | 184 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 185 | 186 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 187 | 188 | ## Sending Feedback 189 | 190 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 191 | 192 | ## Folder Structure 193 | 194 | After creation, your project should look like this: 195 | 196 | ``` 197 | my-app/ 198 | README.md 199 | node_modules/ 200 | package.json 201 | public/ 202 | index.html 203 | favicon.ico 204 | src/ 205 | App.css 206 | App.js 207 | App.test.js 208 | index.css 209 | index.js 210 | logo.svg 211 | ``` 212 | 213 | For the project to build, **these files must exist with exact filenames**: 214 | 215 | * `public/index.html` is the page template; 216 | * `src/index.js` is the JavaScript entry point. 217 | 218 | You can delete or rename the other files. 219 | 220 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 221 | You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them. 222 | 223 | Only files inside `public` can be used from `public/index.html`.<br> 224 | Read instructions below for using assets from JavaScript and HTML. 225 | 226 | You can, however, create more top-level directories.<br> 227 | They will not be included in the production build so you can use them for things like documentation. 228 | 229 | ## Available Scripts 230 | 231 | In the project directory, you can run: 232 | 233 | ### `npm start` 234 | 235 | Runs the app in the development mode.<br> 236 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 237 | 238 | The page will reload if you make edits.<br> 239 | You will also see any lint errors in the console. 240 | 241 | ### `npm test` 242 | 243 | Launches the test runner in the interactive watch mode.<br> 244 | See the section about [running tests](#running-tests) for more information. 245 | 246 | ### `npm run build` 247 | 248 | Builds the app for production to the `build` folder.<br> 249 | It correctly bundles React in production mode and optimizes the build for the best performance. 250 | 251 | The build is minified and the filenames include the hashes.<br> 252 | Your app is ready to be deployed! 253 | 254 | See the section about [deployment](#deployment) for more information. 255 | 256 | ### `npm run eject` 257 | 258 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 259 | 260 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 261 | 262 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 263 | 264 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 265 | 266 | ## Supported Language Features and Polyfills 267 | 268 | This project supports a superset of the latest JavaScript standard.<br> 269 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 270 | 271 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 272 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 273 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 274 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 275 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 276 | 277 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 278 | 279 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. 280 | 281 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 282 | 283 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 284 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 285 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 286 | 287 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 288 | 289 | ## Syntax Highlighting in the Editor 290 | 291 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 292 | 293 | ## Displaying Lint Output in the Editor 294 | 295 | >Note: this feature is available with `react-scripts@0.2.0` and higher. 296 | 297 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 298 | 299 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 300 | 301 | You would need to install an ESLint plugin for your editor first. 302 | 303 | >**A note for Atom `linter-eslint` users** 304 | 305 | >If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked: 306 | 307 | ><img src="http://i.imgur.com/yVNNHJM.png" width="300"> 308 | 309 | 310 | >**For Visual Studio Code users** 311 | 312 | >VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line: 313 | 314 | >```js 315 | { 316 | // ... 317 | "extends": "react-app" 318 | } 319 | ``` 320 | 321 | Then add this block to the `package.json` file of your project: 322 | 323 | ```js 324 | { 325 | // ... 326 | "eslintConfig": { 327 | "extends": "react-app" 328 | } 329 | } 330 | ``` 331 | 332 | Finally, you will need to install some packages *globally*: 333 | 334 | ```sh 335 | npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@4.0.0 eslint-plugin-flowtype@2.21.0 336 | ``` 337 | 338 | We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months. 339 | 340 | ## Debugging in the Editor 341 | 342 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** 343 | 344 | Visual Studio Code supports live-editing and debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. 345 | 346 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. 347 | 348 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 349 | 350 | ```json 351 | { 352 | "version": "0.2.0", 353 | "configurations": [{ 354 | "name": "Chrome", 355 | "type": "chrome", 356 | "request": "launch", 357 | "url": "http://localhost:3000", 358 | "webRoot": "${workspaceRoot}/src", 359 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 360 | "sourceMapPathOverrides": { 361 | "webpack:///src/*": "${webRoot}/*" 362 | } 363 | }] 364 | } 365 | ``` 366 | 367 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. 368 | 369 | ## Changing the Page `<title>` 370 | 371 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 372 | 373 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 374 | 375 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 376 | 377 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). 378 | 379 | ## Installing a Dependency 380 | 381 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 382 | 383 | ``` 384 | npm install --save <library-name> 385 | ``` 386 | 387 | ## Importing a Component 388 | 389 | This project setup supports ES6 modules thanks to Babel.<br> 390 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 391 | 392 | For example: 393 | 394 | ### `Button.js` 395 | 396 | ```js 397 | import React, { Component } from 'react'; 398 | 399 | class Button extends Component { 400 | render() { 401 | // ... 402 | } 403 | } 404 | 405 | export default Button; // Don’t forget to use export default! 406 | ``` 407 | 408 | ### `DangerButton.js` 409 | 410 | 411 | ```js 412 | import React, { Component } from 'react'; 413 | import Button from './Button'; // Import a component from another file 414 | 415 | class DangerButton extends Component { 416 | render() { 417 | return <Button color="red" />; 418 | } 419 | } 420 | 421 | export default DangerButton; 422 | ``` 423 | 424 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 425 | 426 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 427 | 428 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 429 | 430 | Learn more about ES6 modules: 431 | 432 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 433 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 434 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 435 | 436 | ## Adding a Stylesheet 437 | 438 | This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: 439 | 440 | ### `Button.css` 441 | 442 | ```css 443 | .Button { 444 | padding: 20px; 445 | } 446 | ``` 447 | 448 | ### `Button.js` 449 | 450 | ```js 451 | import React, { Component } from 'react'; 452 | import './Button.css'; // Tell Webpack that Button.js uses these styles 453 | 454 | class Button extends Component { 455 | render() { 456 | // You can use them as regular CSS styles 457 | return <div className="Button" />; 458 | } 459 | } 460 | ``` 461 | 462 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 463 | 464 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 465 | 466 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 467 | 468 | ## Post-Processing CSS 469 | 470 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 471 | 472 | For example, this: 473 | 474 | ```css 475 | .App { 476 | display: flex; 477 | flex-direction: row; 478 | align-items: center; 479 | } 480 | ``` 481 | 482 | becomes this: 483 | 484 | ```css 485 | .App { 486 | display: -webkit-box; 487 | display: -ms-flexbox; 488 | display: flex; 489 | -webkit-box-orient: horizontal; 490 | -webkit-box-direction: normal; 491 | -ms-flex-direction: row; 492 | flex-direction: row; 493 | -webkit-box-align: center; 494 | -ms-flex-align: center; 495 | align-items: center; 496 | } 497 | ``` 498 | 499 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 500 | 501 | ## Adding a CSS Preprocessor (Sass, Less etc.) 502 | 503 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 504 | 505 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 506 | 507 | First, let’s install the command-line interface for Sass: 508 | 509 | ``` 510 | npm install node-sass --save-dev 511 | ``` 512 | 513 | Then in `package.json`, add the following lines to `scripts`: 514 | 515 | ```diff 516 | "scripts": { 517 | + "build-css": "node-sass src/ -o src/", 518 | + "watch-css": "npm run build-css && node-sass src/ -o src/ --watch --recursive", 519 | "start": "react-scripts start", 520 | "build": "react-scripts build", 521 | "test": "react-scripts test --env=jsdom", 522 | ``` 523 | 524 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 525 | 526 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 527 | 528 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 529 | 530 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 531 | 532 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 533 | 534 | ``` 535 | npm install --save-dev npm-run-all 536 | ``` 537 | 538 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 539 | 540 | ```diff 541 | "scripts": { 542 | "build-css": "node-sass src/ -o src/", 543 | "watch-css": "npm run build-css && node-sass src/ -o src/ --watch --recursive", 544 | - "start": "react-scripts start", 545 | - "build": "react-scripts build", 546 | + "start-js": "react-scripts start", 547 | + "start": "npm-run-all -p watch-css start-js", 548 | + "build": "npm run build-css && react-scripts build", 549 | "test": "react-scripts test --env=jsdom", 550 | "eject": "react-scripts eject" 551 | } 552 | ``` 553 | 554 | Now running `npm start` and `npm run build` also builds Sass files. Note that `node-sass` seems to have an [issue recognizing newly created files on some systems](https://github.com/sass/node-sass/issues/1891) so you might need to restart the watcher when you create a file until it’s resolved. 555 | 556 | ## Adding Images and Fonts 557 | 558 | With Webpack, using static assets like images and fonts works similarly to CSS. 559 | 560 | You can **`import` an image right in a JavaScript module**. This tells Webpack to include that image in the bundle. Unlike CSS imports, importing an image or a font gives you a string value. This value is the final image path you can reference in your code. 561 | 562 | Here is an example: 563 | 564 | ```js 565 | import React from 'react'; 566 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 567 | 568 | console.log(logo); // /logo.84287d09.png 569 | 570 | function Header() { 571 | // Import result is the URL of your image 572 | return <img src={logo} alt="Logo" />; 573 | } 574 | 575 | export default Header; 576 | ``` 577 | 578 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 579 | 580 | This works in CSS too: 581 | 582 | ```css 583 | .Logo { 584 | background-image: url(./logo.png); 585 | } 586 | ``` 587 | 588 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 589 | 590 | Please be advised that this is also a custom feature of Webpack. 591 | 592 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 593 | An alternative way of handling static assets is described in the next section. 594 | 595 | ## Using the `public` Folder 596 | 597 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 598 | 599 | ### Changing the HTML 600 | 601 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 602 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 603 | 604 | ### Adding Assets Outside of the Module System 605 | 606 | You can also add other assets to the `public` folder. 607 | 608 | Note that we normally encourage you to `import` assets in JavaScript files instead. 609 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-and-fonts). 610 | This mechanism provides a number of benefits: 611 | 612 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 613 | * Missing files cause compilation errors instead of 404 errors for your users. 614 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 615 | 616 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 617 | 618 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 619 | 620 | Inside `index.html`, you can use it like this: 621 | 622 | ```html 623 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 624 | ``` 625 | 626 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 627 | 628 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 629 | 630 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 631 | 632 | ```js 633 | render() { 634 | // Note: this is an escape hatch and should be used sparingly! 635 | // Normally we recommend using `import` for getting asset URLs 636 | // as described in “Adding Images and Fonts” above this section. 637 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 638 | } 639 | ``` 640 | 641 | Keep in mind the downsides of this approach: 642 | 643 | * None of the files in `public` folder get post-processed or minified. 644 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 645 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 646 | 647 | ### When to Use the `public` Folder 648 | 649 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-and-fonts) from JavaScript. 650 | The `public` folder is useful as a workaround for a number of less common cases: 651 | 652 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 653 | * You have thousands of images and need to dynamically reference their paths. 654 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 655 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 656 | 657 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 658 | 659 | ## Using Global Variables 660 | 661 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 662 | 663 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 664 | 665 | ```js 666 | const $ = window.$; 667 | ``` 668 | 669 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 670 | 671 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 672 | 673 | ## Adding Bootstrap 674 | 675 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 676 | 677 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 678 | 679 | ``` 680 | npm install react-bootstrap --save 681 | npm install bootstrap@3 --save 682 | ``` 683 | 684 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 685 | 686 | ```js 687 | import 'bootstrap/dist/css/bootstrap.css'; 688 | import 'bootstrap/dist/css/bootstrap-theme.css'; 689 | // Put any other imports below so that CSS from your 690 | // components takes precedence over default styles. 691 | ``` 692 | 693 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 694 | 695 | ```js 696 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 697 | ``` 698 | 699 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 700 | 701 | ### Using a Custom Theme 702 | 703 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 704 | We suggest the following approach: 705 | 706 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 707 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 708 | * Install your own theme npm package as a dependency of your app. 709 | 710 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 711 | 712 | ## Adding Flow 713 | 714 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 715 | 716 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 717 | 718 | To add Flow to a Create React App project, follow these steps: 719 | 720 | 1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`). 721 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 722 | 3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 723 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 724 | 725 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 726 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 727 | In the future we plan to integrate it into Create React App even more closely. 728 | 729 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 730 | 731 | ## Adding Custom Environment Variables 732 | 733 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 734 | 735 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 736 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 737 | `REACT_APP_`. 738 | 739 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 740 | 741 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 742 | 743 | These environment variables will be defined for you on `process.env`. For example, having an environment 744 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 745 | 746 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 747 | 748 | These environment variables can be useful for displaying information conditionally based on where the project is 749 | deployed or consuming sensitive data that lives outside of version control. 750 | 751 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 752 | in the environment inside a `<form>`: 753 | 754 | ```jsx 755 | render() { 756 | return ( 757 | <div> 758 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 759 | <form> 760 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 761 | </form> 762 | </div> 763 | ); 764 | } 765 | ``` 766 | 767 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 768 | 769 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 770 | 771 | ```html 772 | <div> 773 | <small>You are running this application in <b>development</b> mode.</small> 774 | <form> 775 | <input type="hidden" value="abcdef" /> 776 | </form> 777 | </div> 778 | ``` 779 | 780 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 781 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 782 | a `.env` file. Both of these ways are described in the next few sections. 783 | 784 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 785 | 786 | ```js 787 | if (process.env.NODE_ENV !== 'production') { 788 | analytics.disable(); 789 | } 790 | ``` 791 | 792 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 793 | 794 | ### Referencing Environment Variables in the HTML 795 | 796 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 797 | 798 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 799 | 800 | ```html 801 | <title>%REACT_APP_WEBSITE_NAME% 802 | ``` 803 | 804 | Note that the caveats from the above section apply: 805 | 806 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 807 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 808 | 809 | ### Adding Temporary Environment Variables In Your Shell 810 | 811 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 812 | life of the shell session. 813 | 814 | #### Windows (cmd.exe) 815 | 816 | ```cmd 817 | set REACT_APP_SECRET_CODE=abcdef&&npm start 818 | ``` 819 | 820 | (Note: the lack of whitespace is intentional.) 821 | 822 | #### Linux, macOS (Bash) 823 | 824 | ```bash 825 | REACT_APP_SECRET_CODE=abcdef npm start 826 | ``` 827 | 828 | ### Adding Development Environment Variables In `.env` 829 | 830 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 831 | 832 | To define permanent environment variables, create a file called `.env` in the root of your project: 833 | 834 | ``` 835 | REACT_APP_SECRET_CODE=abcdef 836 | ``` 837 | 838 | These variables will act as the defaults if the machine does not explicitly set them.
839 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 840 | 841 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 842 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 843 | 844 | ## Can I Use Decorators? 845 | 846 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
847 | Create React App doesn’t support decorator syntax at the moment because: 848 | 849 | * It is an experimental proposal and is subject to change. 850 | * The current specification version is not officially supported by Babel. 851 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 852 | 853 | However in many cases you can rewrite decorator-based code without decorators just as fine.
854 | Please refer to these two threads for reference: 855 | 856 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 857 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 858 | 859 | Create React App will add decorator support when the specification advances to a stable stage. 860 | 861 | ## Integrating with an API Backend 862 | 863 | These tutorials will help you to integrate your app with an API backend running on another port, 864 | using `fetch()` to access it. 865 | 866 | ### Node 867 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 868 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 869 | 870 | ### Ruby on Rails 871 | 872 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 873 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 874 | 875 | ## Proxying API Requests in Development 876 | 877 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 878 | 879 | People often serve the front-end React app from the same host and port as their backend implementation.
880 | For example, a production setup might look like this after the app is deployed: 881 | 882 | ``` 883 | / - static server returns index.html with React app 884 | /todos - static server returns index.html with React app 885 | /api/todos - server handles any /api/* requests using the backend implementation 886 | ``` 887 | 888 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 889 | 890 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 891 | 892 | ```js 893 | "proxy": "http://localhost:4000", 894 | ``` 895 | 896 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 897 | 898 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 899 | 900 | ``` 901 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 902 | ``` 903 | 904 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 905 | 906 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
907 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 908 | 909 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 910 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 911 | 912 | ## Using HTTPS in Development 913 | 914 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 915 | 916 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 917 | 918 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 919 | 920 | #### Windows (cmd.exe) 921 | 922 | ```cmd 923 | set HTTPS=true&&npm start 924 | ``` 925 | 926 | (Note: the lack of whitespace is intentional.) 927 | 928 | #### Linux, macOS (Bash) 929 | 930 | ```bash 931 | HTTPS=true npm start 932 | ``` 933 | 934 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 935 | 936 | ## Generating Dynamic `` Tags on the Server 937 | 938 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 939 | 940 | ```html 941 | 942 | 943 | 944 | 945 | 946 | ``` 947 | 948 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 949 | 950 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 951 | 952 | ## Pre-Rendering into Static HTML Files 953 | 954 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 955 | 956 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 957 | 958 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 959 | 960 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 961 | 962 | ## Injecting Data from the Server into the Page 963 | 964 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 965 | 966 | ```js 967 | 968 | 969 | 970 | 973 | ``` 974 | 975 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 976 | 977 | ## Running Tests 978 | 979 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
980 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 981 | 982 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 983 | 984 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 985 | 986 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 987 | 988 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 989 | 990 | ### Filename Conventions 991 | 992 | Jest will look for test files with any of the following popular naming conventions: 993 | 994 | * Files with `.js` suffix in `__tests__` folders. 995 | * Files with `.test.js` suffix. 996 | * Files with `.spec.js` suffix. 997 | 998 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 999 | 1000 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 1001 | 1002 | ### Command Line Interface 1003 | 1004 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 1005 | 1006 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 1007 | 1008 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1009 | 1010 | ### Version Control Integration 1011 | 1012 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests runs fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 1013 | 1014 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 1015 | 1016 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 1017 | 1018 | ### Writing Tests 1019 | 1020 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 1021 | 1022 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1023 | 1024 | ```js 1025 | import sum from './sum'; 1026 | 1027 | it('sums numbers', () => { 1028 | expect(sum(1, 2)).toEqual(3); 1029 | expect(sum(2, 2)).toEqual(4); 1030 | }); 1031 | ``` 1032 | 1033 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1034 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 1035 | 1036 | ### Testing Components 1037 | 1038 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 1039 | 1040 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 1041 | 1042 | ```js 1043 | import React from 'react'; 1044 | import ReactDOM from 'react-dom'; 1045 | import App from './App'; 1046 | 1047 | it('renders without crashing', () => { 1048 | const div = document.createElement('div'); 1049 | ReactDOM.render(, div); 1050 | }); 1051 | ``` 1052 | 1053 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 1054 | 1055 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 1056 | 1057 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). You can write a smoke test with it too: 1058 | 1059 | ```sh 1060 | npm install --save-dev enzyme react-addons-test-utils 1061 | ``` 1062 | 1063 | ```js 1064 | import React from 'react'; 1065 | import { shallow } from 'enzyme'; 1066 | import App from './App'; 1067 | 1068 | it('renders without crashing', () => { 1069 | shallow(); 1070 | }); 1071 | ``` 1072 | 1073 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `