├── .gitignore ├── README.md ├── client ├── .gitignore ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── actions │ │ ├── authActions.js │ │ └── types.js │ ├── components │ │ ├── auth │ │ │ ├── Login.js │ │ │ └── Register.js │ │ ├── dashboard │ │ │ └── Dashboard.js │ │ ├── layout │ │ │ ├── Landing.js │ │ │ └── Navbar.js │ │ └── private-route │ │ │ └── PrivateRoute.js │ ├── index.css │ ├── index.js │ ├── reducers │ │ ├── authReducer.js │ │ ├── errorReducer.js │ │ └── index.js │ ├── serviceWorker.js │ ├── store.js │ └── utils │ │ └── setAuthToken.js └── yarn.lock ├── config ├── keys.js └── passport.js ├── models └── User.js ├── package.json ├── routes └── api │ └── users.js ├── server.js └── validation ├── login.js └── register.js /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | package-lock.json 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mern-auth 2 | 3 | ![Final App](https://i.postimg.cc/tybZb8dL/final-MERNAuth.gif) 4 | Minimal full-stack MERN app with authentication using passport and JWTs. 5 | 6 | This project uses the following technologies: 7 | 8 | - [React](https://reactjs.org) and [React Router](https://reacttraining.com/react-router/) for frontend 9 | - [Express](http://expressjs.com/) and [Node](https://nodejs.org/en/) for the backend 10 | - [MongoDB](https://www.mongodb.com/) for the database 11 | - [Redux](https://redux.js.org/basics/usagewithreact) for state management between React components 12 | 13 | ## Medium Series 14 | 15 | - [Build a Login/Auth App with the MERN Stack — Part 1 (Backend)](https://blog.bitsrc.io/build-a-login-auth-app-with-mern-stack-part-1-c405048e3669) 16 | - [Build a Login/Auth App with the MERN Stack — Part 2 (Frontend & Redux Setup)](https://blog.bitsrc.io/build-a-login-auth-app-with-mern-stack-part-2-frontend-6eac4e38ee82) 17 | - [Build a Login/Auth App with the MERN Stack — Part 3 (Linking Redux with React Components)](https://blog.bitsrc.io/build-a-login-auth-app-with-the-mern-stack-part-3-react-components-88190f8db718) 18 | 19 | ## Configuration 20 | 21 | Make sure to add your own `MONGOURI` from your [mLab](http://mlab.com) database in `config/keys.js`. 22 | 23 | ```javascript 24 | module.exports = { 25 | mongoURI: "YOUR_MONGO_URI_HERE", 26 | secretOrKey: "secret" 27 | }; 28 | ``` 29 | 30 | ## Quick Start 31 | 32 | ```javascript 33 | // Install dependencies for server & client 34 | npm install && npm run client-install 35 | 36 | // Run client & server with concurrently 37 | npm run dev 38 | 39 | // Server runs on http://localhost:5000 and client on http://localhost:3000 40 | ``` 41 | 42 | For deploying to Heroku, please refer to [this](https://www.youtube.com/watch?v=71wSzpLyW9k) helpful video by TraversyMedia. 43 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | 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. 35 | 36 | 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. 37 | 38 | 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. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "axios": "^0.18.0", 7 | "classnames": "^2.2.6", 8 | "jwt-decode": "^2.2.0", 9 | "react": "^16.6.3", 10 | "react-dom": "^16.6.3", 11 | "react-redux": "^5.1.1", 12 | "react-router-dom": "^4.3.1", 13 | "react-scripts": "2.1.1", 14 | "redux": "^4.0.1", 15 | "redux-thunk": "^2.3.0" 16 | }, 17 | "scripts": { 18 | "start": "react-scripts start", 19 | "build": "react-scripts build", 20 | "test": "react-scripts test", 21 | "eject": "react-scripts eject" 22 | }, 23 | "proxy": "http://localhost:5000", 24 | "eslintConfig": { 25 | "extends": "react-app" 26 | }, 27 | "browserslist": [ 28 | ">0.2%", 29 | "not dead", 30 | "not ie <= 11", 31 | "not op_mini all" 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rishipr/mern-auth/4a339402faeac8685609c32362aa4ea09a07e118/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | MERN Auth App 13 | 14 | 15 | 18 |
19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /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": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /client/src/App.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rishipr/mern-auth/4a339402faeac8685609c32362aa4ea09a07e118/client/src/App.css -------------------------------------------------------------------------------- /client/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; 3 | import jwt_decode from "jwt-decode"; 4 | import setAuthToken from "./utils/setAuthToken"; 5 | 6 | import { setCurrentUser, logoutUser } from "./actions/authActions"; 7 | import { Provider } from "react-redux"; 8 | import store from "./store"; 9 | 10 | import Navbar from "./components/layout/Navbar"; 11 | import Landing from "./components/layout/Landing"; 12 | import Register from "./components/auth/Register"; 13 | import Login from "./components/auth/Login"; 14 | import PrivateRoute from "./components/private-route/PrivateRoute"; 15 | import Dashboard from "./components/dashboard/Dashboard"; 16 | 17 | import "./App.css"; 18 | 19 | // Check for token to keep user logged in 20 | if (localStorage.jwtToken) { 21 | // Set auth token header auth 22 | const token = localStorage.jwtToken; 23 | setAuthToken(token); 24 | // Decode token and get user info and exp 25 | const decoded = jwt_decode(token); 26 | // Set user and isAuthenticated 27 | store.dispatch(setCurrentUser(decoded)); 28 | // Check for expired token 29 | const currentTime = Date.now() / 1000; // to get in milliseconds 30 | if (decoded.exp < currentTime) { 31 | // Logout user 32 | store.dispatch(logoutUser()); 33 | 34 | // Redirect to login 35 | window.location.href = "./login"; 36 | } 37 | } 38 | class App extends Component { 39 | render() { 40 | return ( 41 | 42 | 43 |
44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 |
52 |
53 |
54 | ); 55 | } 56 | } 57 | export default App; 58 | -------------------------------------------------------------------------------- /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 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /client/src/actions/authActions.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | import setAuthToken from "../utils/setAuthToken"; 3 | import jwt_decode from "jwt-decode"; 4 | 5 | import { GET_ERRORS, SET_CURRENT_USER, USER_LOADING } from "./types"; 6 | 7 | // Register User 8 | export const registerUser = (userData, history) => dispatch => { 9 | axios 10 | .post("/api/users/register", userData) 11 | .then(res => history.push("/login")) 12 | .catch(err => 13 | dispatch({ 14 | type: GET_ERRORS, 15 | payload: err.response.data 16 | }) 17 | ); 18 | }; 19 | 20 | // Login - get user token 21 | export const loginUser = userData => dispatch => { 22 | axios 23 | .post("/api/users/login", userData) 24 | .then(res => { 25 | // Save to localStorage 26 | 27 | // Set token to localStorage 28 | const { token } = res.data; 29 | localStorage.setItem("jwtToken", token); 30 | // Set token to Auth header 31 | setAuthToken(token); 32 | // Decode token to get user data 33 | const decoded = jwt_decode(token); 34 | // Set current user 35 | dispatch(setCurrentUser(decoded)); 36 | }) 37 | .catch(err => 38 | dispatch({ 39 | type: GET_ERRORS, 40 | payload: err.response.data 41 | }) 42 | ); 43 | }; 44 | 45 | // Set logged in user 46 | export const setCurrentUser = decoded => { 47 | return { 48 | type: SET_CURRENT_USER, 49 | payload: decoded 50 | }; 51 | }; 52 | 53 | // User loading 54 | export const setUserLoading = () => { 55 | return { 56 | type: USER_LOADING 57 | }; 58 | }; 59 | 60 | // Log user out 61 | export const logoutUser = () => dispatch => { 62 | // Remove token from local storage 63 | localStorage.removeItem("jwtToken"); 64 | // Remove auth header for future requests 65 | setAuthToken(false); 66 | // Set current user to empty object {} which will set isAuthenticated to false 67 | dispatch(setCurrentUser({})); 68 | }; 69 | -------------------------------------------------------------------------------- /client/src/actions/types.js: -------------------------------------------------------------------------------- 1 | export const GET_ERRORS = "GET_ERRORS"; 2 | export const USER_LOADING = "USER_LOADING"; 3 | export const SET_CURRENT_USER = "SET_CURRENT_USER"; 4 | -------------------------------------------------------------------------------- /client/src/components/auth/Login.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Link } from "react-router-dom"; 3 | import PropTypes from "prop-types"; 4 | import { connect } from "react-redux"; 5 | import { loginUser } from "../../actions/authActions"; 6 | import classnames from "classnames"; 7 | 8 | class Login extends Component { 9 | constructor() { 10 | super(); 11 | this.state = { 12 | email: "", 13 | password: "", 14 | errors: {} 15 | }; 16 | } 17 | 18 | componentDidMount() { 19 | // If logged in and user navigates to Login page, should redirect them to dashboard 20 | if (this.props.auth.isAuthenticated) { 21 | this.props.history.push("/dashboard"); 22 | } 23 | } 24 | 25 | componentWillReceiveProps(nextProps) { 26 | if (nextProps.auth.isAuthenticated) { 27 | this.props.history.push("/dashboard"); 28 | } 29 | 30 | if (nextProps.errors) { 31 | this.setState({ 32 | errors: nextProps.errors 33 | }); 34 | } 35 | } 36 | 37 | onChange = e => { 38 | this.setState({ [e.target.id]: e.target.value }); 39 | }; 40 | 41 | onSubmit = e => { 42 | e.preventDefault(); 43 | 44 | const userData = { 45 | email: this.state.email, 46 | password: this.state.password 47 | }; 48 | 49 | this.props.loginUser(userData); 50 | }; 51 | 52 | render() { 53 | const { errors } = this.state; 54 | 55 | return ( 56 |
57 |
58 |
59 | 60 | keyboard_backspace Back to 61 | home 62 | 63 |
64 |

65 | Login below 66 |

67 |

68 | Don't have an account? Register 69 |

70 |
71 |
72 |
73 | 83 | 84 | 85 | {errors.email} 86 | {errors.emailnotfound} 87 | 88 |
89 |
90 | 100 | 101 | 102 | {errors.password} 103 | {errors.passwordincorrect} 104 | 105 |
106 |
107 | 119 |
120 |
121 |
122 |
123 |
124 | ); 125 | } 126 | } 127 | 128 | Login.propTypes = { 129 | loginUser: PropTypes.func.isRequired, 130 | auth: PropTypes.object.isRequired, 131 | errors: PropTypes.object.isRequired 132 | }; 133 | 134 | const mapStateToProps = state => ({ 135 | auth: state.auth, 136 | errors: state.errors 137 | }); 138 | 139 | export default connect( 140 | mapStateToProps, 141 | { loginUser } 142 | )(Login); 143 | -------------------------------------------------------------------------------- /client/src/components/auth/Register.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Link, withRouter } from "react-router-dom"; 3 | import PropTypes from "prop-types"; 4 | import { connect } from "react-redux"; 5 | import { registerUser } from "../../actions/authActions"; 6 | import classnames from "classnames"; 7 | 8 | class Register extends Component { 9 | constructor() { 10 | super(); 11 | this.state = { 12 | name: "", 13 | email: "", 14 | password: "", 15 | password2: "", 16 | errors: {} 17 | }; 18 | } 19 | 20 | componentDidMount() { 21 | // If logged in and user navigates to Register page, should redirect them to dashboard 22 | if (this.props.auth.isAuthenticated) { 23 | this.props.history.push("/dashboard"); 24 | } 25 | } 26 | 27 | componentWillReceiveProps(nextProps) { 28 | if (nextProps.errors) { 29 | this.setState({ 30 | errors: nextProps.errors 31 | }); 32 | } 33 | } 34 | 35 | onChange = e => { 36 | this.setState({ [e.target.id]: e.target.value }); 37 | }; 38 | 39 | onSubmit = e => { 40 | e.preventDefault(); 41 | 42 | const newUser = { 43 | name: this.state.name, 44 | email: this.state.email, 45 | password: this.state.password, 46 | password2: this.state.password2 47 | }; 48 | 49 | this.props.registerUser(newUser, this.props.history); 50 | }; 51 | 52 | render() { 53 | const { errors } = this.state; 54 | 55 | return ( 56 |
57 |
58 |
59 | 60 | keyboard_backspace Back to 61 | home 62 | 63 |
64 |

65 | Register below 66 |

67 |

68 | Already have an account? Log in 69 |

70 |
71 |
72 |
73 | 83 | 84 | {errors.name} 85 |
86 |
87 | 97 | 98 | {errors.email} 99 |
100 |
101 | 111 | 112 | {errors.password} 113 |
114 |
115 | 125 | 126 | {errors.password2} 127 |
128 |
129 | 141 |
142 |
143 |
144 |
145 |
146 | ); 147 | } 148 | } 149 | 150 | Register.propTypes = { 151 | registerUser: PropTypes.func.isRequired, 152 | auth: PropTypes.object.isRequired, 153 | errors: PropTypes.object.isRequired 154 | }; 155 | 156 | const mapStateToProps = state => ({ 157 | auth: state.auth, 158 | errors: state.errors 159 | }); 160 | 161 | export default connect( 162 | mapStateToProps, 163 | { registerUser } 164 | )(withRouter(Register)); 165 | -------------------------------------------------------------------------------- /client/src/components/dashboard/Dashboard.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import PropTypes from "prop-types"; 3 | import { connect } from "react-redux"; 4 | import { logoutUser } from "../../actions/authActions"; 5 | 6 | class Dashboard extends Component { 7 | onLogoutClick = e => { 8 | e.preventDefault(); 9 | this.props.logoutUser(); 10 | }; 11 | 12 | render() { 13 | const { user } = this.props.auth; 14 | 15 | return ( 16 |
17 |
18 |
19 |

20 | Hey there, {user.name.split(" ")[0]} 21 |

22 | You are logged into a full-stack{" "} 23 | MERN app 👏 24 |

25 |

26 | 38 |
39 |
40 |
41 | ); 42 | } 43 | } 44 | 45 | Dashboard.propTypes = { 46 | logoutUser: PropTypes.func.isRequired, 47 | auth: PropTypes.object.isRequired 48 | }; 49 | 50 | const mapStateToProps = state => ({ 51 | auth: state.auth 52 | }); 53 | 54 | export default connect( 55 | mapStateToProps, 56 | { logoutUser } 57 | )(Dashboard); 58 | -------------------------------------------------------------------------------- /client/src/components/layout/Landing.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Link } from "react-router-dom"; 3 | 4 | class Landing extends Component { 5 | render() { 6 | return ( 7 |
8 |
9 |
10 |

11 | Build a login/auth app with the{" "} 12 | MERN stack from 13 | scratch 14 |

15 |

16 | Create a (minimal) full-stack app with user authentication via 17 | passport and JWTs 18 |

19 |
20 |
21 | 30 | Register 31 | 32 |
33 |
34 | 43 | Log In 44 | 45 |
46 |
47 |
48 |
49 | ); 50 | } 51 | } 52 | 53 | export default Landing; 54 | -------------------------------------------------------------------------------- /client/src/components/layout/Navbar.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Link } from "react-router-dom"; 3 | 4 | class Navbar extends Component { 5 | render() { 6 | return ( 7 |
8 | 22 |
23 | ); 24 | } 25 | } 26 | 27 | export default Navbar; 28 | -------------------------------------------------------------------------------- /client/src/components/private-route/PrivateRoute.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Route, Redirect } from "react-router-dom"; 3 | import { connect } from "react-redux"; 4 | import PropTypes from "prop-types"; 5 | 6 | const PrivateRoute = ({ component: Component, auth, ...rest }) => ( 7 | 10 | auth.isAuthenticated === true ? ( 11 | 12 | ) : ( 13 | 14 | ) 15 | } 16 | /> 17 | ); 18 | 19 | PrivateRoute.propTypes = { 20 | auth: PropTypes.object.isRequired 21 | }; 22 | 23 | const mapStateToProps = state => ({ 24 | auth: state.auth 25 | }); 26 | 27 | export default connect(mapStateToProps)(PrivateRoute); 28 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /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 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: http://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /client/src/reducers/authReducer.js: -------------------------------------------------------------------------------- 1 | import { SET_CURRENT_USER, USER_LOADING } from "../actions/types"; 2 | 3 | const isEmpty = require("is-empty"); 4 | 5 | const initialState = { 6 | isAuthenticated: false, 7 | user: {}, 8 | loading: false 9 | }; 10 | 11 | export default function(state = initialState, action) { 12 | switch (action.type) { 13 | case SET_CURRENT_USER: 14 | return { 15 | ...state, 16 | isAuthenticated: !isEmpty(action.payload), 17 | user: action.payload 18 | }; 19 | case USER_LOADING: 20 | return { 21 | ...state, 22 | loading: true 23 | }; 24 | default: 25 | return state; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /client/src/reducers/errorReducer.js: -------------------------------------------------------------------------------- 1 | import { GET_ERRORS } from "../actions/types"; 2 | 3 | const initialState = {}; 4 | 5 | export default function(state = initialState, action) { 6 | switch (action.type) { 7 | case GET_ERRORS: 8 | return action.payload; 9 | default: 10 | return state; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /client/src/reducers/index.js: -------------------------------------------------------------------------------- 1 | import { combineReducers } from "redux"; 2 | import authReducer from "./authReducer"; 3 | import errorReducer from "./errorReducer"; 4 | 5 | export default combineReducers({ 6 | auth: authReducer, 7 | errors: errorReducer 8 | }); 9 | -------------------------------------------------------------------------------- /client/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read http://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /client/src/store.js: -------------------------------------------------------------------------------- 1 | import { createStore, applyMiddleware, compose } from "redux"; 2 | import thunk from "redux-thunk"; 3 | import rootReducer from "./reducers"; 4 | 5 | const initialState = {}; 6 | 7 | const middleware = [thunk]; 8 | 9 | const store = createStore( 10 | rootReducer, 11 | initialState, 12 | compose( 13 | applyMiddleware(...middleware), 14 | (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ && 15 | window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__()) || 16 | compose 17 | ) 18 | ); 19 | 20 | export default store; 21 | -------------------------------------------------------------------------------- /client/src/utils/setAuthToken.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | const setAuthToken = token => { 4 | if (token) { 5 | // Apply authorization token to every request if logged in 6 | axios.defaults.headers.common["Authorization"] = token; 7 | } else { 8 | // Delete auth header 9 | delete axios.defaults.headers.common["Authorization"]; 10 | } 11 | }; 12 | 13 | export default setAuthToken; 14 | -------------------------------------------------------------------------------- /config/keys.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | mongoURI: "YOUR_MONGO_URI_HERE", 3 | secretOrKey: "secret" 4 | }; 5 | -------------------------------------------------------------------------------- /config/passport.js: -------------------------------------------------------------------------------- 1 | const JwtStrategy = require("passport-jwt").Strategy; 2 | const ExtractJwt = require("passport-jwt").ExtractJwt; 3 | const mongoose = require("mongoose"); 4 | const User = mongoose.model("users"); 5 | const keys = require("../config/keys"); 6 | 7 | const opts = {}; 8 | opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); 9 | opts.secretOrKey = keys.secretOrKey; 10 | 11 | module.exports = passport => { 12 | passport.use( 13 | new JwtStrategy(opts, (jwt_payload, done) => { 14 | User.findById(jwt_payload.id) 15 | .then(user => { 16 | if (user) { 17 | return done(null, user); 18 | } 19 | return done(null, false); 20 | }) 21 | .catch(err => console.log(err)); 22 | }) 23 | ); 24 | }; 25 | -------------------------------------------------------------------------------- /models/User.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | const Schema = mongoose.Schema; 3 | 4 | // Create Schema 5 | const UserSchema = new Schema({ 6 | name: { 7 | type: String, 8 | required: true 9 | }, 10 | email: { 11 | type: String, 12 | required: true 13 | }, 14 | password: { 15 | type: String, 16 | required: true 17 | }, 18 | date: { 19 | type: Date, 20 | default: Date.now 21 | } 22 | }); 23 | 24 | module.exports = User = mongoose.model("users", UserSchema); 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mern-auth", 3 | "version": "1.0.0", 4 | "description": "Mern Auth Example", 5 | "main": "server.js", 6 | "scripts": { 7 | "client-install": "npm install --prefix client", 8 | "start": "node server.js", 9 | "server": "nodemon server.js", 10 | "client": "npm start --prefix client", 11 | "dev": "concurrently \"npm run server\" \"npm run client\"" 12 | }, 13 | "author": "", 14 | "license": "MIT", 15 | "dependencies": { 16 | "bcryptjs": "^2.4.3", 17 | "body-parser": "^1.18.3", 18 | "concurrently": "^4.0.1", 19 | "express": "^4.16.4", 20 | "is-empty": "^1.2.0", 21 | "jsonwebtoken": "^8.3.0", 22 | "mongoose": "^5.3.11", 23 | "passport": "^0.4.0", 24 | "passport-jwt": "^4.0.0", 25 | "validator": "^10.9.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /routes/api/users.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | const bcrypt = require("bcryptjs"); 4 | const jwt = require("jsonwebtoken"); 5 | const keys = require("../../config/keys"); 6 | const passport = require("passport"); 7 | 8 | // Load input validation 9 | const validateRegisterInput = require("../../validation/register"); 10 | const validateLoginInput = require("../../validation/login"); 11 | 12 | // Load User model 13 | const User = require("../../models/User"); 14 | 15 | // @route POST api/users/register 16 | // @desc Register user 17 | // @access Public 18 | router.post("/register", (req, res) => { 19 | // Form validation 20 | 21 | const { errors, isValid } = validateRegisterInput(req.body); 22 | 23 | // Check validation 24 | if (!isValid) { 25 | return res.status(400).json(errors); 26 | } 27 | 28 | User.findOne({ email: req.body.email }).then(user => { 29 | if (user) { 30 | return res.status(400).json({ email: "Email already exists" }); 31 | } else { 32 | const newUser = new User({ 33 | name: req.body.name, 34 | email: req.body.email, 35 | password: req.body.password 36 | }); 37 | 38 | // Hash password before saving in database 39 | bcrypt.genSalt(10, (err, salt) => { 40 | bcrypt.hash(newUser.password, salt, (err, hash) => { 41 | if (err) throw err; 42 | newUser.password = hash; 43 | newUser 44 | .save() 45 | .then(user => res.json(user)) 46 | .catch(err => console.log(err)); 47 | }); 48 | }); 49 | } 50 | }); 51 | }); 52 | 53 | // @route POST api/users/login 54 | // @desc Login user and return JWT token 55 | // @access Public 56 | router.post("/login", (req, res) => { 57 | // Form validation 58 | 59 | const { errors, isValid } = validateLoginInput(req.body); 60 | 61 | // Check validation 62 | if (!isValid) { 63 | return res.status(400).json(errors); 64 | } 65 | 66 | const email = req.body.email; 67 | const password = req.body.password; 68 | 69 | // Find user by email 70 | User.findOne({ email }).then(user => { 71 | // Check if user exists 72 | if (!user) { 73 | return res.status(404).json({ emailnotfound: "Email not found" }); 74 | } 75 | 76 | // Check password 77 | bcrypt.compare(password, user.password).then(isMatch => { 78 | if (isMatch) { 79 | // User matched 80 | // Create JWT Payload 81 | const payload = { 82 | id: user.id, 83 | name: user.name 84 | }; 85 | 86 | // Sign token 87 | jwt.sign( 88 | payload, 89 | keys.secretOrKey, 90 | { 91 | expiresIn: 31556926 // 1 year in seconds 92 | }, 93 | (err, token) => { 94 | res.json({ 95 | success: true, 96 | token: "Bearer " + token 97 | }); 98 | } 99 | ); 100 | } else { 101 | return res 102 | .status(400) 103 | .json({ passwordincorrect: "Password incorrect" }); 104 | } 105 | }); 106 | }); 107 | }); 108 | 109 | module.exports = router; 110 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const mongoose = require("mongoose"); 3 | const bodyParser = require("body-parser"); 4 | const passport = require("passport"); 5 | 6 | const users = require("./routes/api/users"); 7 | 8 | const app = express(); 9 | 10 | // Bodyparser middleware 11 | app.use( 12 | bodyParser.urlencoded({ 13 | extended: false 14 | }) 15 | ); 16 | app.use(bodyParser.json()); 17 | 18 | // DB Config 19 | const db = require("./config/keys").mongoURI; 20 | 21 | // Connect to MongoDB 22 | mongoose 23 | .connect( 24 | db, 25 | { useNewUrlParser: true } 26 | ) 27 | .then(() => console.log("MongoDB successfully connected")) 28 | .catch(err => console.log(err)); 29 | 30 | // Passport middleware 31 | app.use(passport.initialize()); 32 | 33 | // Passport config 34 | require("./config/passport")(passport); 35 | 36 | // Routes 37 | app.use("/api/users", users); 38 | 39 | const port = process.env.PORT || 5000; 40 | 41 | app.listen(port, () => console.log(`Server up and running on port ${port} !`)); 42 | -------------------------------------------------------------------------------- /validation/login.js: -------------------------------------------------------------------------------- 1 | const Validator = require("validator"); 2 | const isEmpty = require("is-empty"); 3 | 4 | module.exports = function validateLoginInput(data) { 5 | let errors = {}; 6 | 7 | // Convert empty fields to an empty string so we can use validator functions 8 | data.email = !isEmpty(data.email) ? data.email : ""; 9 | data.password = !isEmpty(data.password) ? data.password : ""; 10 | 11 | // Email checks 12 | if (Validator.isEmpty(data.email)) { 13 | errors.email = "Email field is required"; 14 | } else if (!Validator.isEmail(data.email)) { 15 | errors.email = "Email is invalid"; 16 | } 17 | // Password checks 18 | if (Validator.isEmpty(data.password)) { 19 | errors.password = "Password field is required"; 20 | } 21 | 22 | return { 23 | errors, 24 | isValid: isEmpty(errors) 25 | }; 26 | }; 27 | -------------------------------------------------------------------------------- /validation/register.js: -------------------------------------------------------------------------------- 1 | const Validator = require("validator"); 2 | const isEmpty = require("is-empty"); 3 | 4 | module.exports = function validateRegisterInput(data) { 5 | let errors = {}; 6 | 7 | // Convert empty fields to an empty string so we can use validator functions 8 | data.name = !isEmpty(data.name) ? data.name : ""; 9 | data.email = !isEmpty(data.email) ? data.email : ""; 10 | data.password = !isEmpty(data.password) ? data.password : ""; 11 | data.password2 = !isEmpty(data.password2) ? data.password2 : ""; 12 | 13 | // Name checks 14 | if (Validator.isEmpty(data.name)) { 15 | errors.name = "Name field is required"; 16 | } 17 | 18 | // Email checks 19 | if (Validator.isEmpty(data.email)) { 20 | errors.email = "Email field is required"; 21 | } else if (!Validator.isEmail(data.email)) { 22 | errors.email = "Email is invalid"; 23 | } 24 | 25 | // Password checks 26 | if (Validator.isEmpty(data.password)) { 27 | errors.password = "Password field is required"; 28 | } 29 | 30 | if (Validator.isEmpty(data.password2)) { 31 | errors.password2 = "Confirm password field is required"; 32 | } 33 | 34 | if (!Validator.isLength(data.password, { min: 6, max: 30 })) { 35 | errors.password = "Password must be at least 6 characters"; 36 | } 37 | 38 | if (!Validator.equals(data.password, data.password2)) { 39 | errors.password2 = "Passwords must match"; 40 | } 41 | 42 | return { 43 | errors, 44 | isValid: isEmpty(errors) 45 | }; 46 | }; 47 | --------------------------------------------------------------------------------