├── .gitignore ├── README.md ├── config ├── env.js ├── jest │ ├── cssTransform.js │ └── fileTransform.js ├── paths.js ├── polyfills.js ├── webpack.config.dev.js ├── webpack.config.prod.js └── webpackDevServer.config.js ├── index.html ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── scripts ├── build.js ├── start.js └── test.js ├── server ├── app.js ├── index.js ├── models │ └── account.js └── routes │ └── index.js ├── src ├── App.css ├── App.js ├── App.test.js ├── components │ ├── LoginForm.jsx │ └── RegisterForm.jsx ├── index.css ├── index.js ├── logo.svg └── registerServiceWorker.js ├── static └── js │ ├── bundle.js │ └── bundle.js.map └── yarn.lock /.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.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Router 4 + Express + Passport Auth Example 2 | 3 | This app is sort of haphazardly thrown together in order to illustrate React Router 4 + Passport. There is * a lot * to clean up! Tread carefully. It is a combination of `create-react-app` (code in src/ dir is client code) and [User Authentication with Passport and Express 4](https://github.com/mjhea0/passport-local-express4). 4 | 5 | To get this operational, you need to open two tabs and use the following commands - 1 in each tab: 6 | 7 | ``` 8 | npm run start:client 9 | ``` 10 | to start webpack watching and building your client-side code into the build/ directory, and 11 | 12 | ``` 13 | npm run start:server 14 | ``` 15 | to start nodemon watching your code in the server/ directory and serving everything on localhost:3000 16 | 17 | NOTE: the static index.html and code inside of build/ dir are served by express static configuration. 18 | -------------------------------------------------------------------------------- /config/env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | 7 | // Make sure that including paths.js after env.js will read .env variables. 8 | delete require.cache[require.resolve('./paths')]; 9 | 10 | const NODE_ENV = process.env.NODE_ENV; 11 | if (!NODE_ENV) { 12 | throw new Error( 13 | 'The NODE_ENV environment variable is required but was not specified.' 14 | ); 15 | } 16 | 17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 18 | var dotenvFiles = [ 19 | `${paths.dotenv}.${NODE_ENV}.local`, 20 | `${paths.dotenv}.${NODE_ENV}`, 21 | // Don't include `.env.local` for `test` environment 22 | // since normally you expect tests to produce the same 23 | // results for everyone 24 | NODE_ENV !== 'test' && `${paths.dotenv}.local`, 25 | paths.dotenv, 26 | ].filter(Boolean); 27 | 28 | // Load environment variables from .env* files. Suppress warnings using silent 29 | // if this file is missing. dotenv will never modify any environment variables 30 | // that have already been set. 31 | // https://github.com/motdotla/dotenv 32 | dotenvFiles.forEach(dotenvFile => { 33 | if (fs.existsSync(dotenvFile)) { 34 | require('dotenv').config({ 35 | path: dotenvFile, 36 | }); 37 | } 38 | }); 39 | 40 | // We support resolving modules according to `NODE_PATH`. 41 | // This lets you use absolute paths in imports inside large monorepos: 42 | // https://github.com/facebookincubator/create-react-app/issues/253. 43 | // It works similar to `NODE_PATH` in Node itself: 44 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 45 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 46 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. 47 | // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 48 | // We also resolve them to make sure all tools using them work consistently. 49 | const appDirectory = fs.realpathSync(process.cwd()); 50 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 51 | .split(path.delimiter) 52 | .filter(folder => folder && !path.isAbsolute(folder)) 53 | .map(folder => path.resolve(appDirectory, folder)) 54 | .join(path.delimiter); 55 | 56 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be 57 | // injected into the application via DefinePlugin in Webpack configuration. 58 | const REACT_APP = /^REACT_APP_/i; 59 | 60 | function getClientEnvironment(publicUrl) { 61 | const raw = Object.keys(process.env) 62 | .filter(key => REACT_APP.test(key)) 63 | .reduce( 64 | (env, key) => { 65 | env[key] = process.env[key]; 66 | return env; 67 | }, 68 | { 69 | // Useful for determining whether we’re running in production mode. 70 | // Most importantly, it switches React into the correct mode. 71 | NODE_ENV: process.env.NODE_ENV || 'development', 72 | // Useful for resolving the correct path to static assets in `public`. 73 | // For example, . 74 | // This should only be used as an escape hatch. Normally you would put 75 | // images into the `src` and `import` them in code to get their paths. 76 | PUBLIC_URL: publicUrl, 77 | } 78 | ); 79 | // Stringify all values so we can feed into Webpack DefinePlugin 80 | const stringified = { 81 | 'process.env': Object.keys(raw).reduce((env, key) => { 82 | env[key] = JSON.stringify(raw[key]); 83 | return env; 84 | }, {}), 85 | }; 86 | 87 | return { raw, stringified }; 88 | } 89 | 90 | module.exports = getClientEnvironment; 91 | -------------------------------------------------------------------------------- /config/jest/cssTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // This is a custom Jest transformer turning style imports into empty objects. 4 | // http://facebook.github.io/jest/docs/tutorial-webpack.html 5 | 6 | module.exports = { 7 | process() { 8 | return 'module.exports = {};'; 9 | }, 10 | getCacheKey() { 11 | // The output is always the same. 12 | return 'cssTransform'; 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /config/jest/fileTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | 5 | // This is a custom Jest transformer turning file imports into filenames. 6 | // http://facebook.github.io/jest/docs/tutorial-webpack.html 7 | 8 | module.exports = { 9 | process(src, filename) { 10 | return `module.exports = ${JSON.stringify(path.basename(filename))};`; 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /config/paths.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const fs = require('fs'); 5 | const url = require('url'); 6 | 7 | // Make sure any symlinks in the project folder are resolved: 8 | // https://github.com/facebookincubator/create-react-app/issues/637 9 | const appDirectory = fs.realpathSync(process.cwd()); 10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 11 | 12 | const envPublicUrl = process.env.PUBLIC_URL; 13 | 14 | function ensureSlash(path, needsSlash) { 15 | const hasSlash = path.endsWith('/'); 16 | if (hasSlash && !needsSlash) { 17 | return path.substr(path, path.length - 1); 18 | } else if (!hasSlash && needsSlash) { 19 | return `${path}/`; 20 | } else { 21 | return path; 22 | } 23 | } 24 | 25 | const getPublicUrl = appPackageJson => 26 | envPublicUrl || require(appPackageJson).homepage; 27 | 28 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer 29 | // "public path" at which the app is served. 30 | // Webpack needs to know it to put the right 40 | 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-router-passport-express-demo-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "autoprefixer": "7.1.2", 7 | "babel-core": "6.25.0", 8 | "babel-eslint": "7.2.3", 9 | "babel-jest": "20.0.3", 10 | "babel-loader": "7.1.1", 11 | "babel-preset-react-app": "^3.0.2", 12 | "babel-runtime": "6.26.0", 13 | "body-parser": "^1.17.2", 14 | "case-sensitive-paths-webpack-plugin": "2.1.1", 15 | "chalk": "1.1.3", 16 | "connect-flash": "^0.1.1", 17 | "cookie-parser": "^1.4.3", 18 | "css-loader": "0.28.4", 19 | "debug": "^3.0.1", 20 | "dotenv": "4.0.0", 21 | "eslint": "4.4.1", 22 | "eslint-config-react-app": "^2.0.0", 23 | "eslint-loader": "1.9.0", 24 | "eslint-plugin-flowtype": "2.35.0", 25 | "eslint-plugin-import": "2.7.0", 26 | "eslint-plugin-jsx-a11y": "5.1.1", 27 | "eslint-plugin-react": "7.1.0", 28 | "express": "^4.15.4", 29 | "express-session": "^1.15.5", 30 | "extract-text-webpack-plugin": "3.0.0", 31 | "file-loader": "0.11.2", 32 | "fs-extra": "3.0.1", 33 | "html-webpack-plugin": "2.29.0", 34 | "jest": "20.0.4", 35 | "mongoose": "^4.11.10", 36 | "morgan": "^1.8.2", 37 | "object-assign": "4.1.1", 38 | "passport": "^0.4.0", 39 | "passport-local": "^1.0.0", 40 | "passport-local-mongoose": "^4.2.1", 41 | "postcss-flexbugs-fixes": "3.2.0", 42 | "postcss-loader": "2.0.6", 43 | "promise": "8.0.1", 44 | "react": "^15.6.1", 45 | "react-dev-utils": "^4.0.1", 46 | "react-dom": "^15.6.1", 47 | "react-router-dom": "^4.2.2", 48 | "style-loader": "0.18.2", 49 | "sw-precache-webpack-plugin": "0.11.4", 50 | "url-loader": "0.5.9", 51 | "webpack": "3.5.1", 52 | "webpack-dev-server": "2.7.1", 53 | "webpack-manifest-plugin": "1.2.1", 54 | "whatwg-fetch": "2.0.3" 55 | }, 56 | "scripts": { 57 | "start:client": "NODE_ENV=development webpack -w --config config/webpack.config.dev.js", 58 | "start:server": "NODE_ENV=development nodemon --inspect ./server/", 59 | "build": "node scripts/build.js", 60 | "test": "node scripts/test.js --env=jsdom" 61 | }, 62 | "jest": { 63 | "collectCoverageFrom": [ 64 | "src/**/*.{js,jsx}" 65 | ], 66 | "setupFiles": [ 67 | "/config/polyfills.js" 68 | ], 69 | "testMatch": [ 70 | "/src/**/__tests__/**/*.js?(x)", 71 | "/src/**/?(*.)(spec|test).js?(x)" 72 | ], 73 | "testEnvironment": "node", 74 | "testURL": "http://localhost", 75 | "transform": { 76 | "^.+\\.(js|jsx)$": "/node_modules/babel-jest", 77 | "^.+\\.css$": "/config/jest/cssTransform.js", 78 | "^(?!.*\\.(js|jsx|css|json)$)": "/config/jest/fileTransform.js" 79 | }, 80 | "transformIgnorePatterns": [ 81 | "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$" 82 | ], 83 | "moduleNameMapper": { 84 | "^react-native$": "react-native-web" 85 | }, 86 | "moduleFileExtensions": [ 87 | "web.js", 88 | "js", 89 | "json", 90 | "web.jsx", 91 | "jsx", 92 | "node" 93 | ] 94 | }, 95 | "babel": { 96 | "presets": [ 97 | "react-app" 98 | ] 99 | }, 100 | "eslintConfig": { 101 | "extends": "react-app" 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/netpoetica/react-router-passport-express-demo-app/f42c5093c4eac9a8f8162cf61fcfe365ef0821cc/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 22 | React App 23 | 24 | 25 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'production'; 5 | process.env.NODE_ENV = 'production'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | const path = require('path'); 18 | const chalk = require('chalk'); 19 | const fs = require('fs-extra'); 20 | const webpack = require('webpack'); 21 | const config = require('../config/webpack.config.prod'); 22 | const paths = require('../config/paths'); 23 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 24 | const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); 25 | const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); 26 | const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); 27 | const printBuildError = require('react-dev-utils/printBuildError'); 28 | 29 | const measureFileSizesBeforeBuild = 30 | FileSizeReporter.measureFileSizesBeforeBuild; 31 | const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; 32 | const useYarn = fs.existsSync(paths.yarnLockFile); 33 | 34 | // These sizes are pretty large. We'll warn for bundles exceeding them. 35 | const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; 36 | const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; 37 | 38 | // Warn and crash if required files are missing 39 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 40 | process.exit(1); 41 | } 42 | 43 | // First, read the current file sizes in build directory. 44 | // This lets us display how much they changed later. 45 | measureFileSizesBeforeBuild(paths.appBuild) 46 | .then(previousFileSizes => { 47 | // Remove all content but keep the directory so that 48 | // if you're in it, you don't end up in Trash 49 | fs.emptyDirSync(paths.appBuild); 50 | // Merge with the public folder 51 | copyPublicFolder(); 52 | // Start the webpack build 53 | return build(previousFileSizes); 54 | }) 55 | .then( 56 | ({ stats, previousFileSizes, warnings }) => { 57 | if (warnings.length) { 58 | console.log(chalk.yellow('Compiled with warnings.\n')); 59 | console.log(warnings.join('\n\n')); 60 | console.log( 61 | '\nSearch for the ' + 62 | chalk.underline(chalk.yellow('keywords')) + 63 | ' to learn more about each warning.' 64 | ); 65 | console.log( 66 | 'To ignore, add ' + 67 | chalk.cyan('// eslint-disable-next-line') + 68 | ' to the line before.\n' 69 | ); 70 | } else { 71 | console.log(chalk.green('Compiled successfully.\n')); 72 | } 73 | 74 | console.log('File sizes after gzip:\n'); 75 | printFileSizesAfterBuild( 76 | stats, 77 | previousFileSizes, 78 | paths.appBuild, 79 | WARN_AFTER_BUNDLE_GZIP_SIZE, 80 | WARN_AFTER_CHUNK_GZIP_SIZE 81 | ); 82 | console.log(); 83 | 84 | const appPackage = require(paths.appPackageJson); 85 | const publicUrl = paths.publicUrl; 86 | const publicPath = config.output.publicPath; 87 | const buildFolder = path.relative(process.cwd(), paths.appBuild); 88 | printHostingInstructions( 89 | appPackage, 90 | publicUrl, 91 | publicPath, 92 | buildFolder, 93 | useYarn 94 | ); 95 | }, 96 | err => { 97 | console.log(chalk.red('Failed to compile.\n')); 98 | printBuildError(err); 99 | process.exit(1); 100 | } 101 | ); 102 | 103 | // Create the production build and print the deployment instructions. 104 | function build(previousFileSizes) { 105 | console.log('Creating an optimized production build...'); 106 | 107 | let compiler = webpack(config); 108 | return new Promise((resolve, reject) => { 109 | compiler.run((err, stats) => { 110 | if (err) { 111 | return reject(err); 112 | } 113 | const messages = formatWebpackMessages(stats.toJson({}, true)); 114 | if (messages.errors.length) { 115 | // Only keep the first error. Others are often indicative 116 | // of the same problem, but confuse the reader with noise. 117 | if (messages.errors.length > 1) { 118 | messages.errors.length = 1; 119 | } 120 | return reject(new Error(messages.errors.join('\n\n'))); 121 | } 122 | if ( 123 | process.env.CI && 124 | (typeof process.env.CI !== 'string' || 125 | process.env.CI.toLowerCase() !== 'false') && 126 | messages.warnings.length 127 | ) { 128 | console.log( 129 | chalk.yellow( 130 | '\nTreating warnings as errors because process.env.CI = true.\n' + 131 | 'Most CI servers set it automatically.\n' 132 | ) 133 | ); 134 | return reject(new Error(messages.warnings.join('\n\n'))); 135 | } 136 | return resolve({ 137 | stats, 138 | previousFileSizes, 139 | warnings: messages.warnings, 140 | }); 141 | }); 142 | }); 143 | } 144 | 145 | function copyPublicFolder() { 146 | fs.copySync(paths.appPublic, paths.appBuild, { 147 | dereference: true, 148 | filter: file => file !== paths.appHtml, 149 | }); 150 | } 151 | -------------------------------------------------------------------------------- /scripts/start.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'development'; 5 | process.env.NODE_ENV = 'development'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | const fs = require('fs'); 18 | const chalk = require('chalk'); 19 | const webpack = require('webpack'); 20 | const WebpackDevServer = require('webpack-dev-server'); 21 | const clearConsole = require('react-dev-utils/clearConsole'); 22 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 23 | const { 24 | choosePort, 25 | createCompiler, 26 | prepareProxy, 27 | prepareUrls, 28 | } = require('react-dev-utils/WebpackDevServerUtils'); 29 | const openBrowser = require('react-dev-utils/openBrowser'); 30 | const paths = require('../config/paths'); 31 | const config = require('../config/webpack.config.dev'); 32 | const createDevServerConfig = require('../config/webpackDevServer.config'); 33 | 34 | const useYarn = fs.existsSync(paths.yarnLockFile); 35 | const isInteractive = process.stdout.isTTY; 36 | 37 | // Warn and crash if required files are missing 38 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 39 | process.exit(1); 40 | } 41 | 42 | // Tools like Cloud9 rely on this. 43 | const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; 44 | const HOST = process.env.HOST || '0.0.0.0'; 45 | 46 | // We attempt to use the default port but if it is busy, we offer the user to 47 | // run on a different port. `detect()` Promise resolves to the next free port. 48 | choosePort(HOST, DEFAULT_PORT) 49 | .then(port => { 50 | if (port == null) { 51 | // We have not found a port. 52 | return; 53 | } 54 | const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; 55 | const appName = require(paths.appPackageJson).name; 56 | const urls = prepareUrls(protocol, HOST, port); 57 | // Create a webpack compiler that is configured with custom messages. 58 | const compiler = createCompiler(webpack, config, appName, urls, useYarn); 59 | // Load proxy config 60 | const proxySetting = require(paths.appPackageJson).proxy; 61 | const proxyConfig = prepareProxy(proxySetting, paths.appPublic); 62 | // Serve webpack assets generated by the compiler over a web sever. 63 | const serverConfig = createDevServerConfig( 64 | proxyConfig, 65 | urls.lanUrlForConfig 66 | ); 67 | const devServer = new WebpackDevServer(compiler, serverConfig); 68 | // Launch WebpackDevServer. 69 | devServer.listen(port, HOST, err => { 70 | if (err) { 71 | return console.log(err); 72 | } 73 | if (isInteractive) { 74 | clearConsole(); 75 | } 76 | console.log(chalk.cyan('Starting the development server...\n')); 77 | openBrowser(urls.localUrlForBrowser); 78 | }); 79 | 80 | ['SIGINT', 'SIGTERM'].forEach(function(sig) { 81 | process.on(sig, function() { 82 | devServer.close(); 83 | process.exit(); 84 | }); 85 | }); 86 | }) 87 | .catch(err => { 88 | if (err && err.message) { 89 | console.log(err.message); 90 | } 91 | process.exit(1); 92 | }); 93 | -------------------------------------------------------------------------------- /scripts/test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'test'; 5 | process.env.NODE_ENV = 'test'; 6 | process.env.PUBLIC_URL = ''; 7 | 8 | // Makes the script crash on unhandled rejections instead of silently 9 | // ignoring them. In the future, promise rejections that are not handled will 10 | // terminate the Node.js process with a non-zero exit code. 11 | process.on('unhandledRejection', err => { 12 | throw err; 13 | }); 14 | 15 | // Ensure environment variables are read. 16 | require('../config/env'); 17 | 18 | const jest = require('jest'); 19 | const argv = process.argv.slice(2); 20 | 21 | // Watch unless on CI or in coverage mode 22 | if (!process.env.CI && argv.indexOf('--coverage') < 0) { 23 | argv.push('--watch'); 24 | } 25 | 26 | 27 | jest.run(argv); 28 | -------------------------------------------------------------------------------- /server/app.js: -------------------------------------------------------------------------------- 1 | // dependencies 2 | var express = require('express'); 3 | var path = require('path'); 4 | var logger = require('morgan'); 5 | var cookieParser = require('cookie-parser'); 6 | var bodyParser = require('body-parser'); 7 | var mongoose = require('mongoose'); 8 | var passport = require('passport'); 9 | var LocalStrategy = require('passport-local').Strategy; 10 | var flash = require('connect-flash'); 11 | 12 | var routes = require('./routes/index'); 13 | 14 | var app = express(); 15 | 16 | app.use(logger('dev')); 17 | app.use(bodyParser.urlencoded({ extended: true })); 18 | app.use(bodyParser.json()); 19 | app.use(cookieParser()); 20 | app.use(require('express-session')({ 21 | secret: 'keyboard cat', 22 | resave: false, 23 | saveUninitialized: false 24 | })); 25 | app.use(passport.initialize()); 26 | app.use(flash()); 27 | app.use(passport.session()); app.use(express.static(path.join(__dirname, '../build'))); 28 | 29 | 30 | app.use('/', routes); 31 | 32 | // passport config 33 | var Account = require('./models/account'); 34 | passport.use(new LocalStrategy(Account.authenticate())); 35 | passport.serializeUser(Account.serializeUser()); 36 | passport.deserializeUser(Account.deserializeUser()); 37 | 38 | // mongoose 39 | mongoose.connect('mongodb://localhost/passport_local_mongoose_express4'); 40 | 41 | // catch 404 and forward to error handler 42 | app.use(function(req, res, next) { 43 | var err = new Error('Not Found'); 44 | err.status = 404; 45 | next(err); 46 | }); 47 | 48 | // error handlers 49 | 50 | // development error handler 51 | // will print stacktrace 52 | if (app.get('env') === 'development') { 53 | app.use(function(err, req, res, next) { 54 | res.status(err.status || 500); 55 | res.json({ 56 | message: err.message, 57 | error: err 58 | }); 59 | }); 60 | } 61 | 62 | // production error handler 63 | // no stacktraces leaked to user 64 | app.use(function(err, req, res, next) { 65 | res.status(err.status || 500); 66 | res.json({ 67 | message: err.message, 68 | error: {} 69 | }); 70 | }); 71 | 72 | module.exports = app; 73 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | var app = require('./app'); 6 | var debug = require('debug')('passport-local-express4:server'); 7 | var http = require('http'); 8 | 9 | /** 10 | * Get port from environment and store in Express. 11 | */ 12 | 13 | var port = normalizePort(process.env.PORT || '3000'); 14 | app.set('port', port); 15 | 16 | /** 17 | * Create HTTP server. 18 | */ 19 | 20 | var server = http.createServer(app); 21 | 22 | /** 23 | * Listen on provided port, on all network interfaces. 24 | */ 25 | 26 | server.listen(port); 27 | server.on('error', onError); 28 | server.on('listening', onListening); 29 | 30 | /** 31 | * Normalize a port into a number, string, or false. 32 | */ 33 | 34 | function normalizePort(val) { 35 | var port = parseInt(val, 10); 36 | 37 | if (isNaN(port)) { 38 | // named pipe 39 | return val; 40 | } 41 | 42 | if (port >= 0) { 43 | // port number 44 | return port; 45 | } 46 | 47 | return false; 48 | } 49 | 50 | /** 51 | * Event listener for HTTP server "error" event. 52 | */ 53 | 54 | function onError(error) { 55 | if (error.syscall !== 'listen') { 56 | throw error; 57 | } 58 | 59 | var bind = typeof port === 'string' 60 | ? 'Pipe ' + port 61 | : 'Port ' + port 62 | 63 | // handle specific listen errors with friendly messages 64 | switch (error.code) { 65 | case 'EACCES': 66 | console.error(bind + ' requires elevated privileges'); 67 | process.exit(1); 68 | break; 69 | case 'EADDRINUSE': 70 | console.error(bind + ' is already in use'); 71 | process.exit(1); 72 | break; 73 | default: 74 | throw error; 75 | } 76 | } 77 | 78 | /** 79 | * Event listener for HTTP server "listening" event. 80 | */ 81 | 82 | function onListening() { 83 | var addr = server.address(); 84 | var bind = typeof addr === 'string' 85 | ? 'pipe ' + addr 86 | : 'port ' + addr.port; 87 | debug('Listening on ' + bind); 88 | } -------------------------------------------------------------------------------- /server/models/account.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | const passportLocalMongoose = require('passport-local-mongoose'); 4 | 5 | const Account = new Schema({ 6 | username: String, 7 | password: String 8 | }); 9 | 10 | Account.plugin(passportLocalMongoose); 11 | 12 | module.exports = mongoose.model('accounts', Account); 13 | -------------------------------------------------------------------------------- /server/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const passport = require('passport'); 3 | const Account = require('../models/account'); 4 | const router = express.Router(); 5 | 6 | // Use this route to verify the user is authenticated 7 | // and get credentials. AKA if req.user, you have a session 8 | router.get('/user', (req, res, next) => { 9 | if(req.user) { 10 | return res.status(200).json({ 11 | user: req.user, 12 | authenticated: true 13 | }); 14 | } else { 15 | return res.status(401).json({ 16 | error: 'User is not authenticated', 17 | authenticated: false 18 | }); 19 | } 20 | }); 21 | 22 | router.post('/register', (req, res, next) => { 23 | console.log('/register handler', req.body); 24 | Account.register(new Account({ username : req.body.username }), req.body.password, (err, account) => { 25 | if (err) { 26 | return res.status(500).send({ error : err.message }); 27 | } 28 | 29 | passport.authenticate('local')(req, res, () => { 30 | req.session.save((err) => { 31 | if (err) { 32 | return next(err); 33 | } 34 | 35 | res.status(200).send('OK'); 36 | }); 37 | }); 38 | }); 39 | }); 40 | 41 | 42 | router.post('/login', passport.authenticate('local', { failureRedirect: '/?error=LoginError', failureFlash: true }), (req, res, next) => { 43 | console.log('/login handler'); 44 | req.session.save((err) => { 45 | if (err) { 46 | return next(err); 47 | } 48 | 49 | res.status(200).send('OK'); 50 | }); 51 | }); 52 | 53 | /* 54 | Example of not using failureRedirect: 55 | 56 | router.post('/login', function(req, res, next) { 57 | passport.authenticate('local', function(err, user, info) { 58 | console.log('/login handler', req.body); 59 | 60 | if (err) { return next(err); } 61 | if (!user) { return res.status(500).json({ error: 'User not found.' }); } 62 | 63 | req.session.save((err) => { 64 | if (err) { 65 | return next(err); 66 | } 67 | 68 | res.status(200).json({ success: true }); 69 | }); 70 | })(req, res, next); 71 | }); 72 | */ 73 | 74 | router.get('/logout', (req, res, next) => { 75 | req.logout(); 76 | req.session.save((err) => { 77 | if (err) { 78 | return next(err); 79 | } 80 | res.status(200).send('OK'); 81 | }); 82 | }); 83 | 84 | // Use this to test that your API is working 85 | router.get('/ping', (req, res) => { 86 | res.status(200).send("pong!"); 87 | }); 88 | 89 | 90 | /* These routes should be handled on front-end in React, React Router */ 91 | /* 92 | router.get('/', (req, res) => { 93 | res.render('index', { user : req.user }); 94 | }); 95 | 96 | router.get('/register', (req, res) => { 97 | res.render('register', { }); 98 | }); 99 | 100 | router.get('/login', (req, res) => { 101 | res.render('login', { user : req.user, error : req.flash('error')}); 102 | }); 103 | */ 104 | 105 | module.exports = router; 106 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 80px; 8 | } 9 | 10 | .App-header { 11 | background-color: #222; 12 | height: 150px; 13 | padding: 20px; 14 | color: white; 15 | } 16 | 17 | .App-intro { 18 | font-size: large; 19 | } 20 | 21 | @keyframes App-logo-spin { 22 | from { transform: rotate(0deg); } 23 | to { transform: rotate(360deg); } 24 | } 25 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { 3 | BrowserRouter as Router, 4 | Route, 5 | Link, 6 | Redirect, 7 | withRouter 8 | } from 'react-router-dom' 9 | 10 | import LoginForm from './components/LoginForm' 11 | import RegisterForm from './components/RegisterForm' 12 | 13 | const AuthExample = () => ( 14 | 15 |
16 | 17 |
    18 |
  • Public Page
  • 19 |
  • Protected Page
  • 20 |
  • Register a New User
  • 21 |
22 | 23 | 24 | 25 | 26 |
27 |
28 | ) 29 | 30 | const auth = { 31 | isAuthenticated: false, 32 | authenticate(cb) { 33 | // req.user on backend will contain user info if 34 | // this person has credentials that are valid 35 | fetch('/user', { 36 | credentials: 'include' 37 | }) 38 | .then((res) => { 39 | this.isAuthenticated = true 40 | if (typeof cb === 'function') { 41 | cb(res.json().user); 42 | } 43 | }) 44 | .catch((err) => { 45 | console.log('Error fetching authorized user.'); 46 | }); 47 | }, 48 | signout(cb) { 49 | fetch('/logout', { 50 | method: 'POST', 51 | credentials: 'include' 52 | }) 53 | .then((res) => { 54 | this.isAuthenticated = false; 55 | if (typeof cb === 'function') { 56 | // user was logged out 57 | cb(true); 58 | } 59 | }) 60 | .catch((err) => { 61 | console.log('Error logging out user.'); 62 | if (typeof cb === 'function') { 63 | // user was not logged out 64 | cb(false); 65 | } 66 | }); 67 | } 68 | } 69 | 70 | const AuthButton = withRouter(({ history }) => ( 71 | auth.isAuthenticated ? ( 72 |

73 | Welcome! 76 |

77 | ) : ( 78 |

You are not logged in.

79 | ) 80 | )) 81 | 82 | const PrivateRoute = ({ component: Component, ...rest }) => ( 83 | ( 84 | auth.isAuthenticated ? ( 85 | 86 | ) : ( 87 | 91 | ) 92 | )}/> 93 | ) 94 | 95 | const Public = () =>

Public

96 | const Protected = () =>

Protected

97 | 98 | class Login extends React.Component { 99 | state = { 100 | redirectToReferrer: false 101 | } 102 | 103 | login = (data) => { 104 | console.log('Logging in ' + data.username); 105 | fetch('/login', { 106 | method: 'POST', 107 | body: JSON.stringify(data), 108 | credentials: 'include', 109 | headers: { 110 | 'Content-Type': 'application/json' 111 | }, 112 | }) 113 | .then((response) => { 114 | if (response.status === 200) { 115 | auth.authenticate(() => { 116 | this.setState({ redirectToReferrer: true }) 117 | }); 118 | } 119 | }) 120 | .catch((err) => { 121 | console.log('Error logging in.', err); 122 | }); 123 | } 124 | 125 | render() { 126 | const { from } = this.props.location.state || { from: { pathname: '/' } } 127 | const { redirectToReferrer } = this.state 128 | 129 | if (redirectToReferrer) { 130 | return ( 131 | 132 | ) 133 | } 134 | 135 | return ( 136 |
137 |

You must log in to view the page at {from.pathname}

138 | 139 |
140 | ) 141 | } 142 | } 143 | 144 | 145 | class Register extends React.Component { 146 | state = { 147 | redirectToReferrer: false 148 | } 149 | 150 | register = (data) => { 151 | fetch('/register', { 152 | method: 'POST', 153 | body: JSON.stringify(data), 154 | headers: { 155 | 'Content-Type': 'application/json' 156 | }, 157 | credentials: 'include' 158 | }) 159 | .then((response) => { 160 | if (response.status === 200) { 161 | console.log('Succesfully registered user!'); 162 | } 163 | }) 164 | .catch((err) => { 165 | console.log('Error registering user.', err); 166 | }); 167 | } 168 | 169 | render() { 170 | return ( 171 |
172 |

Register a New User

173 | 174 |
175 | ) 176 | } 177 | } 178 | 179 | export default AuthExample 180 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | }); 9 | -------------------------------------------------------------------------------- /src/components/LoginForm.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | class LoginForm extends React.Component { 4 | // refs 5 | form: null; 6 | usernameElem: null; 7 | passwordElem: null; 8 | 9 | render() { 10 | const { onLogin } = this.props; 11 | return ( 12 |
13 |
this.form = elem} 15 | onSubmit={(e) => { 16 | e.preventDefault(); 17 | return onLogin({ 18 | username: this.usernameElem.value, 19 | password: this.passwordElem.value 20 | }); 21 | }} 22 | > 23 | this.usernameElem = input} type='text' name="username" placeholder='Enter Username' /> 24 | this.passwordElem = input} type='password' name="password" placeholder='Password' /> 25 | 31 |
32 |
33 | ) 34 | } 35 | } 36 | 37 | export default LoginForm -------------------------------------------------------------------------------- /src/components/RegisterForm.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | class LoginForm extends React.Component { 4 | // refs 5 | form: null; 6 | usernameElem: null; 7 | passwordElem: null; 8 | 9 | render() { 10 | const { onRegister } = this.props; 11 | return ( 12 |
13 |
this.form = elem} 15 | onSubmit={(e) => { 16 | e.preventDefault(); 17 | return onRegister({ 18 | username: this.usernameElem.value, 19 | password: this.passwordElem.value 20 | }); 21 | }} 22 | > 23 | this.usernameElem = input} type='text' name="username" placeholder='Enter Username' /> 24 | this.passwordElem = input} type='password' name="password" placeholder='Password' /> 25 | 31 |
32 |
33 | ) 34 | } 35 | } 36 | 37 | export default LoginForm -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import registerServiceWorker from './registerServiceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | registerServiceWorker(); 9 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/registerServiceWorker.js: -------------------------------------------------------------------------------- 1 | // In production, we register a service worker to serve assets from local cache. 2 | 3 | // This lets the app load faster on subsequent visits in production, and gives 4 | // it offline capabilities. However, it also means that developers (and users) 5 | // will only see deployed updates on the "N+1" visit to a page, since previously 6 | // cached resources are updated in the background. 7 | 8 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. 9 | // This link also includes instructions on opting out of this behavior. 10 | 11 | const isLocalhost = Boolean( 12 | window.location.hostname === 'localhost' || 13 | // [::1] is the IPv6 localhost address. 14 | window.location.hostname === '[::1]' || 15 | // 127.0.0.1/8 is considered localhost for IPv4. 16 | window.location.hostname.match( 17 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 18 | ) 19 | ); 20 | 21 | export default function register() { 22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 23 | // The URL constructor is available in all browsers that support SW. 24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location); 25 | if (publicUrl.origin !== window.location.origin) { 26 | // Our service worker won't work if PUBLIC_URL is on a different origin 27 | // from what our page is served on. This might happen if a CDN is used to 28 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 29 | return; 30 | } 31 | 32 | window.addEventListener('load', () => { 33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 34 | 35 | if (!isLocalhost) { 36 | // Is not local host. Just register service worker 37 | registerValidSW(swUrl); 38 | } else { 39 | // This is running on localhost. Lets check if a service worker still exists or not. 40 | checkValidServiceWorker(swUrl); 41 | } 42 | }); 43 | } 44 | } 45 | 46 | function registerValidSW(swUrl) { 47 | navigator.serviceWorker 48 | .register(swUrl) 49 | .then(registration => { 50 | registration.onupdatefound = () => { 51 | const installingWorker = registration.installing; 52 | installingWorker.onstatechange = () => { 53 | if (installingWorker.state === 'installed') { 54 | if (navigator.serviceWorker.controller) { 55 | // At this point, the old content will have been purged and 56 | // the fresh content will have been added to the cache. 57 | // It's the perfect time to display a "New content is 58 | // available; please refresh." message in your web app. 59 | console.log('New content is available; please refresh.'); 60 | } else { 61 | // At this point, everything has been precached. 62 | // It's the perfect time to display a 63 | // "Content is cached for offline use." message. 64 | console.log('Content is cached for offline use.'); 65 | } 66 | } 67 | }; 68 | }; 69 | }) 70 | .catch(error => { 71 | console.error('Error during service worker registration:', error); 72 | }); 73 | } 74 | 75 | function checkValidServiceWorker(swUrl) { 76 | // Check if the service worker can be found. If it can't reload the page. 77 | fetch(swUrl) 78 | .then(response => { 79 | // Ensure service worker exists, and that we really are getting a JS file. 80 | if ( 81 | response.status === 404 || 82 | response.headers.get('content-type').indexOf('javascript') === -1 83 | ) { 84 | // No service worker found. Probably a different app. Reload the page. 85 | navigator.serviceWorker.ready.then(registration => { 86 | registration.unregister().then(() => { 87 | window.location.reload(); 88 | }); 89 | }); 90 | } else { 91 | // Service worker found. Proceed as normal. 92 | registerValidSW(swUrl); 93 | } 94 | }) 95 | .catch(() => { 96 | console.log( 97 | 'No internet connection found. App is running in offline mode.' 98 | ); 99 | }); 100 | } 101 | 102 | export function unregister() { 103 | if ('serviceWorker' in navigator) { 104 | navigator.serviceWorker.ready.then(registration => { 105 | registration.unregister(); 106 | }); 107 | } 108 | } 109 | --------------------------------------------------------------------------------