├── .gitignore ├── LICENSE ├── README.md ├── client ├── .gitignore ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── components │ ├── AuthService.js │ ├── Navbar │ │ ├── Navbar.js │ │ └── index.js │ └── withAuth.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── pages │ ├── Login.js │ ├── Profile.js │ └── Signup.js │ ├── registerServiceWorker.js │ └── utils │ └── API.js ├── config ├── auth.js └── isAuthenticated.js ├── models ├── User.js └── index.js ├── package.json └── server.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # Mac 64 | .DS_Store 65 | 66 | # Webstorm 67 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Travis Thompson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create React Express App 2 | 3 | ## About This Boilerplate 4 | 5 | This setup allows for a Node/Express/React/JWT app which can be easily deployed to Heroku. 6 | 7 | The front-end React app will auto-reload as it's updated via webpack dev server, and the backend Express app will auto-reload independently with nodemon. 8 | 9 | An article on how the server is setup with JWT can be found [here](https://hptechblogs.com/using-json-web-token-for-authentication/). This has been modified to use a mongo database instead of hardcoded array of users. 10 | 11 | The front end has been setup to use JWT as a way of authenticating users and routes. To understand it's structure better please refer to the following article [here](https://hptechblogs.com/using-json-web-token-react/) 12 | 13 | Please feel free to modify this code in anyway you see fit for your project. It is a boilerplate setup that tries to make sure you can get something up and running without having to worry about setting up user authentication from scratch. 14 | I highly suggest you read the articles before jumping in so you can have an better understanding of how everything works in the code. 15 | 16 | Server-side article and using JWT: https://hptechblogs.com/using-json-web-token-for-authentication/ 17 | 18 | Front End article on using the JWT on a react application: https://hptechblogs.com/using-json-web-token-react/ 19 | 20 | ## Starting the app locally 21 | 22 | Add a .env at the top level of this project. 23 | 24 | Then inside of the .env add a SERVER_SECRET set to any value you'd like 25 | 26 | ``` 27 | SERVER_SECRET = 123456 28 | ``` 29 | 30 | First off make sure you have a local version of MongoDB running on your machine. This project will make a local database for you called `appDB`. 31 | 32 | ``` 33 | mongod 34 | ``` 35 | 36 | Start by installing front and backend dependencies. While in the root directory, run the following command: 37 | 38 | ``` 39 | npm install 40 | ``` 41 | 42 | After all installations complete, run the following command in your terminal: 43 | 44 | ``` 45 | npm start 46 | ``` 47 | 48 | That's it, your app should be running on . The Express server should intercept any AJAX requests from the client. 49 | 50 | ## Deployment (Heroku) 51 | 52 | ### Create a Git Repo 53 | 54 | Once you're ready to deploy, start by making sure your project is a git repository. If so, proceed to the next section, otherwise run the following commands in your terminal: 55 | 56 | ``` 57 | git init 58 | git add . 59 | git commit -m "Initial commit" 60 | ``` 61 | 62 | ### Deploying 63 | 64 | 1. Go onto your heroku account and link your repository through the UI 65 | 2. Go to resources and find mLab as a Add-on 66 | 3. Provision a Mongo Database 67 | 4. Go back and click "Deploy" 68 | -------------------------------------------------------------------------------- /client/.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 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # React JWT Authentication System 2 | 3 | First install all the dependencies 4 | ```sh 5 | npm install 6 | ``` 7 | 8 | To start the app type 9 | ```sh 10 | npm start 11 | ``` 12 | 13 | 14 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-react-express-jwt-client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "proxy": "http://localhost:3001/", 6 | "dependencies": { 7 | "axios": "^0.18.0", 8 | "jwt-decode": "^2.2.0", 9 | "react": "^16.8.6", 10 | "react-dom": "^16.8.6", 11 | "react-router-dom": "^5.0.0", 12 | "react-scripts": "^3.0.0" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": "react-app" 22 | }, 23 | "browserslist": { 24 | "production": [ 25 | ">0.2%", 26 | "not dead", 27 | "not op_mini all" 28 | ], 29 | "development": [ 30 | "last 1 chrome version", 31 | "last 1 firefox version", 32 | "last 1 safari version" 33 | ] 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Travo100/create-react-express-jwt/5c593cd34bcfa1aaf234fc2fdff6c9de5e6916f1/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | 23 | React App 24 | 25 | 26 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /client/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 | -------------------------------------------------------------------------------- /client/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 | -------------------------------------------------------------------------------- /client/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | import AuthService from './components/AuthService'; 5 | import withAuth from './components/withAuth'; 6 | const Auth = new AuthService(); 7 | 8 | class App extends Component { 9 | 10 | 11 | handleLogout = () => { 12 | Auth.logout(); 13 | this.props.history.replace('/signup'); 14 | }; 15 | 16 | goToEditProfile = () => { 17 | this.props.history.replace('/profile'); 18 | }; 19 | 20 | render() { 21 | console.log(process.env.REACT_APP_SECRET_CODE); 22 | return ( 23 |
24 |
25 | logo 26 |

Welcome {this.props.user.email}

27 |
28 |

29 | 30 | 31 |

32 |
33 | ); 34 | } 35 | } 36 | 37 | export default withAuth(App); 38 | -------------------------------------------------------------------------------- /client/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 | -------------------------------------------------------------------------------- /client/src/components/AuthService.js: -------------------------------------------------------------------------------- 1 | import decode from 'jwt-decode'; 2 | import axios from 'axios'; 3 | export default class AuthService { 4 | 5 | login = (email, password) => { 6 | // Get a token 7 | return axios.post('api/login', {email: email, password: password}) 8 | .then(res => { 9 | // set the token once the user logs in 10 | this.setToken(res.data.token); 11 | // return the rest of the response 12 | return res; 13 | }); 14 | }; 15 | 16 | getProfile = () => { 17 | return decode(this.getToken()); 18 | }; 19 | 20 | loggedIn() { 21 | // Checks if there is a saved token and it's still valid 22 | const token = this.getToken(); 23 | return !!token && !this.isTokenExpired(token) // handwaiving here 24 | } 25 | 26 | isTokenExpired(token) { 27 | try { 28 | const decoded = decode(token); 29 | if (decoded.exp < Date.now() / 1000) { 30 | return true; 31 | } 32 | else 33 | return false; 34 | } 35 | catch (err) { 36 | return false; 37 | } 38 | } 39 | 40 | setToken(idToken) { 41 | // Saves user token to localStorage 42 | axios.defaults.headers.common['Authorization'] = `Bearer ${idToken}`; 43 | localStorage.setItem('id_token', idToken); 44 | } 45 | 46 | getToken() { 47 | // Retrieves the user token from localStorage 48 | return localStorage.getItem('id_token'); 49 | } 50 | 51 | logout() { 52 | // Clear user token and profile data from localStorage 53 | axios.defaults.headers.common['Authorization'] = null; 54 | localStorage.removeItem('id_token'); 55 | // this will reload the page and reset the state of the application 56 | window.location.reload('/'); 57 | } 58 | 59 | 60 | 61 | } -------------------------------------------------------------------------------- /client/src/components/Navbar/Navbar.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Link } from 'react-router-dom'; 3 | import AuthService from '../AuthService'; 4 | 5 | class Navbar extends Component { 6 | constructor() { 7 | super(); 8 | this.Auth = new AuthService(); 9 | } 10 | 11 | showNavigation = () => { 12 | if (this.Auth.loggedIn()) { 13 | return ( 14 | 23 | ); 24 | } else { 25 | return ( 26 | 34 | ); 35 | } 36 | }; 37 | 38 | render() { 39 | return ( 40 | 53 | ) 54 | } 55 | } 56 | 57 | export default Navbar; -------------------------------------------------------------------------------- /client/src/components/Navbar/index.js: -------------------------------------------------------------------------------- 1 | export { default } from "./Navbar"; -------------------------------------------------------------------------------- /client/src/components/withAuth.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import AuthService from './AuthService'; 3 | 4 | export default function withAuth(AuthComponent) { 5 | const Auth = new AuthService(); 6 | return class AuthWrapped extends Component { 7 | constructor() { 8 | super(); 9 | this.state = { 10 | user: null 11 | }; 12 | } 13 | componentWillMount() { 14 | if (!Auth.loggedIn()) { 15 | this.props.history.replace('/signup'); 16 | } 17 | else { 18 | try { 19 | const profile = Auth.getProfile(); 20 | this.setState({ 21 | user: profile 22 | }); 23 | } 24 | catch(err){ 25 | Auth.logout(); 26 | this.props.history.replace('/signup'); 27 | } 28 | } 29 | } 30 | 31 | render() { 32 | if (this.state.user) { 33 | return ( 34 | 35 | ); 36 | } 37 | else { 38 | return null; 39 | } 40 | } 41 | }; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /client/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | 6 | import registerServiceWorker from './registerServiceWorker'; 7 | import { Route, BrowserRouter as Router } from 'react-router-dom'; 8 | import axios from "axios"; 9 | 10 | // Our Components 11 | import Login from './pages/Login'; 12 | import Profile from './pages/Profile'; 13 | import Signup from './pages/Signup'; 14 | import Navbar from './components/Navbar'; 15 | 16 | // Here is if we have an id_token in localStorage 17 | if(localStorage.getItem("id_token")) { 18 | // then we will attach it to the headers of each request from react application via axios 19 | axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('id_token')}`; 20 | } 21 | 22 | ReactDOM.render( 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 | , document.getElementById('root') 33 | ); 34 | registerServiceWorker(); 35 | -------------------------------------------------------------------------------- /client/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /client/src/pages/Login.js: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | import AuthService from './../components/AuthService'; 3 | import {Link} from 'react-router-dom'; 4 | 5 | class Login extends Component { 6 | constructor() { 7 | super(); 8 | this.Auth = new AuthService(); 9 | } 10 | 11 | componentWillMount() { 12 | if (this.Auth.loggedIn()) { 13 | this.props.history.replace('/'); 14 | } 15 | } 16 | 17 | handleFormSubmit = event => { 18 | event.preventDefault(); 19 | 20 | this.Auth.login(this.state.email, this.state.password) 21 | .then(res => { 22 | // once user is logged in 23 | // take them to their profile page 24 | this.props.history.replace(`/profile`); 25 | }) 26 | .catch(err => { 27 | alert(err.response.data.message) 28 | }); 29 | }; 30 | 31 | handleChange = event => { 32 | const {name, value} = event.target; 33 | this.setState({ 34 | [name]: value 35 | }); 36 | }; 37 | 38 | render() { 39 | return ( 40 |
41 |

Login

42 |
43 |
44 | 45 | 51 |
52 |
53 | 54 | 60 |
61 | 62 |
63 |

Go to Signup

64 |
65 | 66 | ); 67 | } 68 | } 69 | 70 | export default Login; -------------------------------------------------------------------------------- /client/src/pages/Profile.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import withAuth from './../components/withAuth'; 3 | import API from './../utils/API'; 4 | import { Link } from 'react-router-dom'; 5 | 6 | class Profile extends Component { 7 | 8 | state = { 9 | username: "", 10 | email: "" 11 | }; 12 | 13 | componentDidMount() { 14 | API.getUser(this.props.user.id).then(res => { 15 | this.setState({ 16 | username: res.data.username, 17 | email: res.data.email 18 | }) 19 | }); 20 | } 21 | 22 | render() { 23 | return ( 24 |
25 |

On the profile page!

26 |

Username: {this.state.username}

27 |

Email: {this.state.email}

28 | Go home 29 |
30 | ) 31 | } 32 | } 33 | 34 | export default withAuth(Profile); -------------------------------------------------------------------------------- /client/src/pages/Signup.js: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | import {Link} from 'react-router-dom'; 3 | import AuthService from './../components/AuthService'; 4 | import API from './../utils/API'; 5 | 6 | class Signup extends Component { 7 | constructor() { 8 | super(); 9 | this.Auth = new AuthService(); 10 | } 11 | 12 | componentWillMount() { 13 | if (this.Auth.loggedIn()) { 14 | this.props.history.replace('/'); 15 | } 16 | } 17 | 18 | handleFormSubmit = event => { 19 | event.preventDefault(); 20 | API.signUpUser(this.state.username, this.state.email, this.state.password) 21 | .then(res => { 22 | // once the user has signed up 23 | // send them to the login page 24 | this.props.history.replace('/login'); 25 | }) 26 | .catch(err => alert(err)); 27 | }; 28 | 29 | handleChange = event => { 30 | const {name, value} = event.target; 31 | this.setState({ 32 | [name]: value 33 | }); 34 | }; 35 | 36 | render() { 37 | return ( 38 |
39 | 40 |

Signup

41 |
42 |
43 | 44 | 50 |
51 |
52 | 53 | 59 |
60 |
61 | 62 | 68 |
69 | 70 |
71 |

Go to Login

72 |
73 | ); 74 | } 75 | } 76 | 77 | export default Signup; -------------------------------------------------------------------------------- /client/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 | -------------------------------------------------------------------------------- /client/src/utils/API.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | export default { 3 | // Gets a single user by id 4 | getUser: (id) => { 5 | return axios.get(`/api/user/${id}`); 6 | }, 7 | // sign up a user to our service 8 | signUpUser: (username, email, password) => { 9 | return axios.post('api/signup', {username: username, email: email, password: password}); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /config/auth.js: -------------------------------------------------------------------------------- 1 | const db = require('../models'); 2 | const jwt = require('jsonwebtoken'); 3 | 4 | module.exports = { 5 | logUserIn: function (email, password) { 6 | return new Promise((resolve, reject) => { 7 | db.User.findOne({ 8 | email: email 9 | }).then(user => { 10 | user.verifyPassword(password, (err, isMatch) => { 11 | if (isMatch && !err) { 12 | let token = jwt.sign({ id: user._id, email: user.email }, process.env.SERVER_SECRET, { expiresIn: 129600 }); // Sigining the token 13 | resolve({ success: true, message: "Token Issued!", token: token, user: user }); 14 | } else { 15 | reject({ success: false, message: "Authentication failed. Wrong password." }); 16 | } 17 | }); 18 | }).catch(err => reject({ success: false, message: "User not found", error: err })); 19 | }) 20 | } 21 | } -------------------------------------------------------------------------------- /config/isAuthenticated.js: -------------------------------------------------------------------------------- 1 | const exjwt = require('express-jwt'); 2 | 3 | // Init the express-jwt middleware 4 | const isAuthenticated = exjwt({ 5 | secret: process.env.SERVER_SECRET 6 | }); 7 | 8 | module.exports = isAuthenticated; -------------------------------------------------------------------------------- /models/User.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const Schema = mongoose.Schema; 3 | const bcrypt = require('bcrypt-nodejs'); 4 | 5 | const UserSchema = new Schema({ 6 | username: { 7 | type: String, 8 | required: true, 9 | trim: true 10 | }, 11 | email: { 12 | type: String, 13 | required: true, 14 | unique: true, 15 | trim: true, 16 | lowercase: true, 17 | index: { 18 | unique: true 19 | } 20 | }, 21 | password: { 22 | type: String, 23 | required: true 24 | }, 25 | createdAt: { 26 | type: Date, 27 | default: Date.now 28 | } 29 | }); 30 | 31 | // Execute before each user.save() call 32 | UserSchema.pre('save', function(callback) { 33 | let user = this; 34 | 35 | // Break out if the password hasn't changed 36 | if (!user.isModified('password')) return callback(); 37 | 38 | // Password changed so we need to hash it 39 | bcrypt.genSalt(5, function(err, salt) { 40 | if (err) return callback(err); 41 | 42 | bcrypt.hash(user.password, salt, null, function(err, hash) { 43 | if (err) return callback(err); 44 | user.password = hash; 45 | callback(); 46 | }); 47 | }); 48 | }); 49 | 50 | UserSchema.methods.verifyPassword = function(password, cb) { 51 | bcrypt.compare(password, this.password, function(err, isMatch) { 52 | if (err) return cb(err); 53 | cb(null, isMatch); 54 | }); 55 | }; 56 | 57 | const User = mongoose.model('User', UserSchema); 58 | 59 | module.exports = User; -------------------------------------------------------------------------------- /models/index.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | User: require('./User') 3 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-react-express-jwt-server", 3 | "version": "1.0.0", 4 | "description": "Mern Demo", 5 | "main": "server.js", 6 | "scripts": { 7 | "start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev", 8 | "start:prod": "node server.js", 9 | "start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"", 10 | "client": "cd client && npm run start", 11 | "install": "cd client && npm install", 12 | "build": "cd client && npm run build", 13 | "heroku-postbuild": "npm run build" 14 | }, 15 | "author": "", 16 | "license": "ISC", 17 | "devDependencies": { 18 | "concurrently": "^3.6.1", 19 | "nodemon": "^1.18.3" 20 | }, 21 | "dependencies": { 22 | "bcrypt-nodejs": "0.0.3", 23 | "dotenv": "^7.0.0", 24 | "express": "^4.16.4", 25 | "express-jwt": "^5.3.1", 26 | "if-env": "^1.0.4", 27 | "jsonwebtoken": "^8.5.1", 28 | "mongoose": "^5.5.3", 29 | "morgan": "^1.9.1" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config() 2 | const express = require('express'); 3 | const app = express(); 4 | const path = require('path'); 5 | const mongoose = require('mongoose'); 6 | const morgan = require('morgan'); // used to see requests 7 | const db = require('./models'); 8 | const PORT = process.env.PORT || 3001; 9 | 10 | const isAuthenticated = require("./config/isAuthenticated"); 11 | const auth = require("./config/auth"); 12 | 13 | // Setting CORS so that any website can 14 | // Access our API 15 | app.use((req, res, next) => { 16 | res.setHeader('Access-Control-Allow-Origin', '*'); 17 | res.setHeader('Access-Control-Allow-Headers', 'Content-type,Authorization'); 18 | next(); 19 | }); 20 | 21 | //log all requests to the console 22 | app.use(morgan('dev')); 23 | 24 | // Setting up express to use json and set it to req.body 25 | app.use(express.json()); 26 | app.use(express.urlencoded({ extended: true })); 27 | 28 | mongoose 29 | .connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/appDB', {useNewUrlParser: true, useCreateIndex: true}) 30 | .then(() => console.log("MongoDB Connected!")) 31 | .catch(err => console.error(err)); 32 | 33 | 34 | // LOGIN ROUTE 35 | app.post('/api/login', (req, res) => { 36 | auth 37 | .logUserIn(req.body.email, req.body.password) 38 | .then(dbUser => res.json(dbUser)) 39 | .catch(err => res.status(400).json(err)); 40 | }); 41 | 42 | // SIGNUP ROUTE 43 | app.post('/api/signup', (req, res) => { 44 | db.User.create(req.body) 45 | .then(data => res.json(data)) 46 | .catch(err => res.status(400).json(err)); 47 | }); 48 | 49 | // Any route with isAuthenticated is protected and you need a valid token 50 | // to access 51 | app.get('/api/user/:id', isAuthenticated, (req, res) => { 52 | db.User.findById(req.params.id).then(data => { 53 | if(data) { 54 | res.json(data); 55 | } else { 56 | res.status(404).send({success: false, message: 'No user found'}); 57 | } 58 | }).catch(err => res.status(400).send(err)); 59 | }); 60 | 61 | // Serve up static assets (usually on heroku) 62 | if (process.env.NODE_ENV === "production") { 63 | app.use(express.static("client/build")); 64 | } 65 | 66 | app.get('/', isAuthenticated /* Using the express jwt MW here */, (req, res) => { 67 | res.send('You are authenticated'); //Sending some response when authenticated 68 | }); 69 | 70 | // Error handling 71 | app.use(function (err, req, res, next) { 72 | if (err.name === 'UnauthorizedError') { // Send the error rather than to show it on the console 73 | res.status(401).send(err); 74 | } 75 | else { 76 | next(err); 77 | } 78 | }); 79 | 80 | // Send every request to the React app 81 | // Define any API routes before this runs 82 | app.get("*", function(req, res) { 83 | res.sendFile(path.join(__dirname, "./client/build/index.html")); 84 | }); 85 | 86 | app.listen(PORT, function() { 87 | console.log(`🌎 ==> Server now on port ${PORT}!`); 88 | }); 89 | --------------------------------------------------------------------------------