├── .gitignore ├── client ├── assets │ └── images │ │ └── unicornbike.jpg ├── main.js ├── auth │ ├── PrivateRoute.js │ ├── api-auth.js │ ├── auth-helper.js │ └── Signin.js ├── theme.js ├── App.js ├── MainRouter.js ├── core │ ├── Home.js │ └── Menu.js └── user │ ├── api-user.js │ ├── DeleteUser.js │ ├── Users.js │ ├── Profile.js │ ├── Signup.js │ └── EditProfile.js ├── nodemon.json ├── .babelrc ├── server ├── routes │ ├── auth.routes.js │ └── user.routes.js ├── server.js ├── devBundle.js ├── helpers │ └── dbErrorHandler.js ├── controllers │ ├── auth.controller.js │ └── user.controller.js ├── models │ └── user.model.js └── express.js ├── config └── config.js ├── .github └── stale.yml ├── webpack.config.client.production.js ├── webpack.config.server.js ├── template.js ├── LICENSE.md ├── webpack.config.client.js ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | /dist/ 3 | /data/ 4 | npm-debug.log 5 | -------------------------------------------------------------------------------- /client/assets/images/unicornbike.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shamahoque/mern-skeleton/HEAD/client/assets/images/unicornbike.jpg -------------------------------------------------------------------------------- /client/main.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { hydrate } from 'react-dom' 3 | import App from './App' 4 | 5 | hydrate(, document.getElementById('root')) 6 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "verbose": false, 3 | "watch": [ 4 | "./server" 5 | ], 6 | "exec": "webpack --mode=development --config webpack.config.server.js && node ./dist/server.generated.js" 7 | } 8 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", 4 | { 5 | "targets": { 6 | "node": "current" 7 | } 8 | } 9 | ], 10 | "@babel/preset-react" 11 | ], 12 | "plugins": [ 13 | "react-hot-loader/babel" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /server/routes/auth.routes.js: -------------------------------------------------------------------------------- 1 | import express from 'express' 2 | import authCtrl from '../controllers/auth.controller' 3 | 4 | const router = express.Router() 5 | 6 | router.route('/auth/signin') 7 | .post(authCtrl.signin) 8 | router.route('/auth/signout') 9 | .get(authCtrl.signout) 10 | 11 | export default router 12 | -------------------------------------------------------------------------------- /config/config.js: -------------------------------------------------------------------------------- 1 | const config = { 2 | env: process.env.NODE_ENV || 'development', 3 | port: process.env.PORT || 3000, 4 | jwtSecret: process.env.JWT_SECRET || "YOUR_secret_key", 5 | mongoUri: process.env.MONGODB_URI || 6 | process.env.MONGO_HOST || 7 | 'mongodb://' + (process.env.IP || 'localhost') + ':' + 8 | (process.env.MONGO_PORT || '27017') + 9 | '/mernproject' 10 | } 11 | 12 | export default config 13 | -------------------------------------------------------------------------------- /client/auth/PrivateRoute.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Route, Redirect } from 'react-router-dom' 3 | import auth from './auth-helper' 4 | 5 | const PrivateRoute = ({ component: Component, ...rest }) => ( 6 | ( 7 | auth.isAuthenticated() ? ( 8 | 9 | ) : ( 10 | 14 | ) 15 | )}/> 16 | ) 17 | 18 | export default PrivateRoute 19 | -------------------------------------------------------------------------------- /server/server.js: -------------------------------------------------------------------------------- 1 | import config from './../config/config' 2 | import app from './express' 3 | import mongoose from 'mongoose' 4 | 5 | // Connection URL 6 | mongoose.Promise = global.Promise 7 | mongoose.connect(config.mongoUri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }) 8 | mongoose.connection.on('error', () => { 9 | throw new Error(`unable to connect to database: ${config.mongoUri}`) 10 | }) 11 | 12 | app.listen(config.port, (err) => { 13 | if (err) { 14 | console.log(err) 15 | } 16 | console.info('Server started on port %s.', config.port) 17 | }) 18 | -------------------------------------------------------------------------------- /server/routes/user.routes.js: -------------------------------------------------------------------------------- 1 | import express from 'express' 2 | import userCtrl from '../controllers/user.controller' 3 | import authCtrl from '../controllers/auth.controller' 4 | 5 | const router = express.Router() 6 | 7 | router.route('/api/users') 8 | .get(userCtrl.list) 9 | .post(userCtrl.create) 10 | 11 | router.route('/api/users/:userId') 12 | .get(authCtrl.requireSignin, userCtrl.read) 13 | .put(authCtrl.requireSignin, authCtrl.hasAuthorization, userCtrl.update) 14 | .delete(authCtrl.requireSignin, authCtrl.hasAuthorization, userCtrl.remove) 15 | 16 | router.param('userId', userCtrl.userByID) 17 | 18 | export default router 19 | -------------------------------------------------------------------------------- /server/devBundle.js: -------------------------------------------------------------------------------- 1 | import config from './../config/config' 2 | import webpack from 'webpack' 3 | import webpackMiddleware from 'webpack-dev-middleware' 4 | import webpackHotMiddleware from 'webpack-hot-middleware' 5 | import webpackConfig from './../webpack.config.client.js' 6 | 7 | const compile = (app) => { 8 | if(config.env === "development"){ 9 | const compiler = webpack(webpackConfig) 10 | const middleware = webpackMiddleware(compiler, { 11 | publicPath: webpackConfig.output.publicPath 12 | }) 13 | app.use(middleware) 14 | app.use(webpackHotMiddleware(compiler)) 15 | } 16 | } 17 | 18 | export default { 19 | compile 20 | } 21 | -------------------------------------------------------------------------------- /client/theme.js: -------------------------------------------------------------------------------- 1 | import { createMuiTheme } from '@material-ui/core/styles' 2 | import { pink } from '@material-ui/core/colors' 3 | 4 | const theme = createMuiTheme({ 5 | typography: { 6 | useNextVariants: true, 7 | }, 8 | palette: { 9 | primary: { 10 | light: '#5c67a3', 11 | main: '#3f4771', 12 | dark: '#2e355b', 13 | contrastText: '#fff', 14 | }, 15 | secondary: { 16 | light: '#ff79b0', 17 | main: '#ff4081', 18 | dark: '#c60055', 19 | contrastText: '#000', 20 | }, 21 | openTitle: '#3f4771', 22 | protectedTitle: pink['400'], 23 | type: 'light' 24 | } 25 | }) 26 | 27 | export default theme -------------------------------------------------------------------------------- /client/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import MainRouter from './MainRouter' 3 | import {BrowserRouter} from 'react-router-dom' 4 | import { ThemeProvider } from '@material-ui/styles' 5 | import theme from './theme' 6 | import { hot } from 'react-hot-loader' 7 | 8 | const App = () => { 9 | React.useEffect(() => { 10 | const jssStyles = document.querySelector('#jss-server-side') 11 | if (jssStyles) { 12 | jssStyles.parentNode.removeChild(jssStyles) 13 | } 14 | }, []) 15 | return ( 16 | 17 | 18 | 19 | 20 | 21 | )} 22 | 23 | export default hot(module)(App) 24 | -------------------------------------------------------------------------------- /client/auth/api-auth.js: -------------------------------------------------------------------------------- 1 | const signin = async (user) => { 2 | try { 3 | let response = await fetch('/auth/signin/', { 4 | method: 'POST', 5 | headers: { 6 | 'Accept': 'application/json', 7 | 'Content-Type': 'application/json' 8 | }, 9 | credentials: 'include', 10 | body: JSON.stringify(user) 11 | }) 12 | return await response.json() 13 | } catch(err) { 14 | console.log(err) 15 | } 16 | } 17 | 18 | const signout = async () => { 19 | try { 20 | let response = await fetch('/auth/signout/', { method: 'GET' }) 21 | return await response.json() 22 | } catch(err) { 23 | console.log(err) 24 | } 25 | } 26 | 27 | export { 28 | signin, 29 | signout 30 | } -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | # Label to use when marking an issue as stale 10 | staleLabel: inactive 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: > 13 | This issue has been automatically marked as stale because it has not had 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false 18 | -------------------------------------------------------------------------------- /client/auth/auth-helper.js: -------------------------------------------------------------------------------- 1 | import { signout } from './api-auth.js' 2 | 3 | const auth = { 4 | isAuthenticated() { 5 | if (typeof window == "undefined") 6 | return false 7 | 8 | if (sessionStorage.getItem('jwt')) 9 | return JSON.parse(sessionStorage.getItem('jwt')) 10 | else 11 | return false 12 | }, 13 | authenticate(jwt, cb) { 14 | if (typeof window !== "undefined") 15 | sessionStorage.setItem('jwt', JSON.stringify(jwt)) 16 | cb() 17 | }, 18 | clearJWT(cb) { 19 | if (typeof window !== "undefined") 20 | sessionStorage.removeItem('jwt') 21 | cb() 22 | //optional 23 | signout().then((data) => { 24 | document.cookie = "t=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;" 25 | }) 26 | } 27 | } 28 | 29 | export default auth 30 | -------------------------------------------------------------------------------- /webpack.config.client.production.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const CURRENT_WORKING_DIR = process.cwd() 3 | 4 | const config = { 5 | mode: "production", 6 | entry: [ 7 | path.join(CURRENT_WORKING_DIR, 'client/main.js') 8 | ], 9 | output: { 10 | path: path.join(CURRENT_WORKING_DIR , '/dist'), 11 | filename: 'bundle.js', 12 | publicPath: "/dist/" 13 | }, 14 | module: { 15 | rules: [ 16 | { 17 | test: /\.jsx?$/, 18 | exclude: /node_modules/, 19 | use: [ 20 | 'babel-loader' 21 | ] 22 | }, 23 | { 24 | test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/, 25 | use: 'file-loader' 26 | } 27 | ] 28 | } 29 | } 30 | 31 | module.exports = config 32 | -------------------------------------------------------------------------------- /client/MainRouter.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import {Route, Switch} from 'react-router-dom' 3 | import Home from './core/Home' 4 | import Users from './user/Users' 5 | import Signup from './user/Signup' 6 | import Signin from './auth/Signin' 7 | import EditProfile from './user/EditProfile' 8 | import Profile from './user/Profile' 9 | import PrivateRoute from './auth/PrivateRoute' 10 | import Menu from './core/Menu' 11 | 12 | const MainRouter = () => { 13 | return (
14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
) 24 | } 25 | 26 | export default MainRouter 27 | -------------------------------------------------------------------------------- /webpack.config.server.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const nodeExternals = require('webpack-node-externals') 3 | const CURRENT_WORKING_DIR = process.cwd() 4 | 5 | const config = { 6 | name: "server", 7 | entry: [ path.join(CURRENT_WORKING_DIR , './server/server.js') ], 8 | target: "node", 9 | output: { 10 | path: path.join(CURRENT_WORKING_DIR , '/dist/'), 11 | filename: "server.generated.js", 12 | publicPath: '/dist/', 13 | libraryTarget: "commonjs2" 14 | }, 15 | externals: [nodeExternals()], 16 | module: { 17 | rules: [ 18 | { 19 | test: /\.js$/, 20 | exclude: /node_modules/, 21 | use: [ 'babel-loader' ] 22 | }, 23 | { 24 | test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/, 25 | use: 'file-loader' 26 | } 27 | ] 28 | } 29 | } 30 | 31 | module.exports = config 32 | -------------------------------------------------------------------------------- /template.js: -------------------------------------------------------------------------------- 1 | export default ({markup, css}) => { 2 | return ` 3 | 4 | 5 | 6 | 10 | MERN Skeleton 11 | 12 | 13 | 19 | 20 | 21 |
${markup}
22 | 23 | 24 | 25 | ` 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Shama Hoque 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 | -------------------------------------------------------------------------------- /server/helpers/dbErrorHandler.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | /** 4 | * Get unique error field name 5 | */ 6 | const getUniqueErrorMessage = (err) => { 7 | let output 8 | try { 9 | let fieldName = err.message.substring(err.message.lastIndexOf('.$') + 2, err.message.lastIndexOf('_1')) 10 | output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists' 11 | } catch (ex) { 12 | output = 'Unique field already exists' 13 | } 14 | 15 | return output 16 | } 17 | 18 | /** 19 | * Get the error message from error object 20 | */ 21 | const getErrorMessage = (err) => { 22 | let message = '' 23 | 24 | if (err.code) { 25 | switch (err.code) { 26 | case 11000: 27 | case 11001: 28 | message = getUniqueErrorMessage(err) 29 | break 30 | default: 31 | message = 'Something went wrong' 32 | } 33 | } else { 34 | for (let errName in err.errors) { 35 | if (err.errors[errName].message) message = err.errors[errName].message 36 | } 37 | } 38 | 39 | return message 40 | } 41 | 42 | export default {getErrorMessage} 43 | -------------------------------------------------------------------------------- /webpack.config.client.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const webpack = require('webpack') 3 | const CURRENT_WORKING_DIR = process.cwd() 4 | 5 | const config = { 6 | name: "browser", 7 | mode: "development", 8 | devtool: 'eval-source-map', 9 | entry: [ 10 | 'webpack-hot-middleware/client?reload=true', 11 | path.join(CURRENT_WORKING_DIR, 'client/main.js') 12 | ], 13 | output: { 14 | path: path.join(CURRENT_WORKING_DIR , '/dist'), 15 | filename: 'bundle.js', 16 | publicPath: '/dist/' 17 | }, 18 | module: { 19 | rules: [ 20 | { 21 | test: /\.jsx?$/, 22 | exclude: /node_modules/, 23 | use: [ 24 | 'babel-loader' 25 | ] 26 | }, 27 | { 28 | test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/, 29 | use: 'file-loader' 30 | } 31 | ] 32 | }, 33 | plugins: [ 34 | new webpack.HotModuleReplacementPlugin(), 35 | new webpack.NoEmitOnErrorsPlugin() 36 | ], 37 | resolve: { 38 | alias: { 39 | 'react-dom': '@hot-loader/react-dom' 40 | } 41 | } 42 | } 43 | 44 | module.exports = config 45 | -------------------------------------------------------------------------------- /server/controllers/auth.controller.js: -------------------------------------------------------------------------------- 1 | import User from '../models/user.model' 2 | import jwt from 'jsonwebtoken' 3 | import expressJwt from 'express-jwt' 4 | import config from './../../config/config' 5 | 6 | const signin = async (req, res) => { 7 | try { 8 | let user = await User.findOne({ 9 | "email": req.body.email 10 | }) 11 | if (!user) 12 | return res.status('401').json({ 13 | error: "User not found" 14 | }) 15 | 16 | if (!user.authenticate(req.body.password)) { 17 | return res.status('401').send({ 18 | error: "Email and password don't match." 19 | }) 20 | } 21 | 22 | const token = jwt.sign({ 23 | _id: user._id 24 | }, config.jwtSecret) 25 | 26 | res.cookie("t", token, { 27 | expire: new Date() + 9999 28 | }) 29 | 30 | return res.json({ 31 | token, 32 | user: { 33 | _id: user._id, 34 | name: user.name, 35 | email: user.email 36 | } 37 | }) 38 | 39 | } catch (err) { 40 | 41 | return res.status('401').json({ 42 | error: "Could not sign in" 43 | }) 44 | 45 | } 46 | } 47 | 48 | const signout = (req, res) => { 49 | res.clearCookie("t") 50 | return res.status('200').json({ 51 | message: "signed out" 52 | }) 53 | } 54 | 55 | const requireSignin = expressJwt({ 56 | secret: config.jwtSecret, 57 | userProperty: 'auth' 58 | }) 59 | 60 | const hasAuthorization = (req, res, next) => { 61 | const authorized = req.profile && req.auth && req.profile._id == req.auth._id 62 | if (!(authorized)) { 63 | return res.status('403').json({ 64 | error: "User is not authorized" 65 | }) 66 | } 67 | next() 68 | } 69 | 70 | export default { 71 | signin, 72 | signout, 73 | requireSignin, 74 | hasAuthorization 75 | } 76 | -------------------------------------------------------------------------------- /client/core/Home.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { makeStyles } from '@material-ui/core/styles' 3 | import Card from '@material-ui/core/Card' 4 | import CardContent from '@material-ui/core/CardContent' 5 | import CardMedia from '@material-ui/core/CardMedia' 6 | import Typography from '@material-ui/core/Typography' 7 | import unicornbikeImg from './../assets/images/unicornbike.jpg' 8 | 9 | const useStyles = makeStyles(theme => ({ 10 | card: { 11 | maxWidth: 600, 12 | margin: 'auto', 13 | marginTop: theme.spacing(5), 14 | marginBottom: theme.spacing(5) 15 | }, 16 | title: { 17 | padding:`${theme.spacing(3)}px ${theme.spacing(2.5)}px ${theme.spacing(2)}px`, 18 | color: theme.palette.openTitle 19 | }, 20 | media: { 21 | minHeight: 400 22 | }, 23 | credit: { 24 | padding: 10, 25 | textAlign: 'right', 26 | backgroundColor: '#ededed', 27 | borderBottom: '1px solid #d0d0d0', 28 | '& a':{ 29 | color: '#3f4771' 30 | } 31 | } 32 | })) 33 | 34 | export default function Home(){ 35 | const classes = useStyles() 36 | return ( 37 | 38 | 39 | Home Page 40 | 41 | 42 | Photo by Boudewijn Huysmans on Unsplash 43 | 44 | 45 | Welcome to the MERN Skeleton home page. 46 | 47 | 48 | 49 | ) 50 | } 51 | 52 | -------------------------------------------------------------------------------- /server/models/user.model.js: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose' 2 | import crypto from 'crypto' 3 | const UserSchema = new mongoose.Schema({ 4 | name: { 5 | type: String, 6 | trim: true, 7 | required: 'Name is required' 8 | }, 9 | email: { 10 | type: String, 11 | trim: true, 12 | unique: 'Email already exists', 13 | match: [/.+\@.+\..+/, 'Please fill a valid email address'], 14 | required: 'Email is required' 15 | }, 16 | hashed_password: { 17 | type: String, 18 | required: "Password is required" 19 | }, 20 | salt: String, 21 | updated: Date, 22 | created: { 23 | type: Date, 24 | default: Date.now 25 | } 26 | }) 27 | 28 | UserSchema 29 | .virtual('password') 30 | .set(function(password) { 31 | this._password = password 32 | this.salt = this.makeSalt() 33 | this.hashed_password = this.encryptPassword(password) 34 | }) 35 | .get(function() { 36 | return this._password 37 | }) 38 | 39 | UserSchema.path('hashed_password').validate(function(v) { 40 | if (this._password && this._password.length < 6) { 41 | this.invalidate('password', 'Password must be at least 6 characters.') 42 | } 43 | if (this.isNew && !this._password) { 44 | this.invalidate('password', 'Password is required') 45 | } 46 | }, null) 47 | 48 | UserSchema.methods = { 49 | authenticate: function(plainText) { 50 | return this.encryptPassword(plainText) === this.hashed_password 51 | }, 52 | encryptPassword: function(password) { 53 | if (!password) return '' 54 | try { 55 | return crypto 56 | .createHmac('sha1', this.salt) 57 | .update(password) 58 | .digest('hex') 59 | } catch (err) { 60 | return '' 61 | } 62 | }, 63 | makeSalt: function() { 64 | return Math.round((new Date().valueOf() * Math.random())) + '' 65 | } 66 | } 67 | 68 | export default mongoose.model('User', UserSchema) 69 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mern-skeleton", 3 | "version": "2.0.0", 4 | "description": "A MERN stack skeleton web application", 5 | "author": "Shama Hoque", 6 | "license": "MIT", 7 | "keywords": [ 8 | "react", 9 | "express", 10 | "mongodb", 11 | "node", 12 | "mern" 13 | ], 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/shamahoque/mern-skeleton.git" 17 | }, 18 | "homepage": "https://github.com/shamahoque/mern-skeleton", 19 | "main": "./dist/server.generated.js", 20 | "scripts": { 21 | "development": "nodemon", 22 | "build": "webpack --config webpack.config.client.production.js && webpack --mode=production --config webpack.config.server.js", 23 | "start": "NODE_ENV=production node ./dist/server.generated.js" 24 | }, 25 | "engines": { 26 | "node": "13.12.0", 27 | "npm": "6.14.4" 28 | }, 29 | "devDependencies": { 30 | "@babel/core": "7.9.0", 31 | "@babel/preset-env": "7.9.0", 32 | "@babel/preset-react": "7.9.4", 33 | "babel-loader": "8.1.0", 34 | "file-loader": "6.0.0", 35 | "nodemon": "2.0.2", 36 | "webpack": "4.42.1", 37 | "webpack-cli": "3.3.11", 38 | "webpack-dev-middleware": "3.7.2", 39 | "webpack-hot-middleware": "2.25.0", 40 | "webpack-node-externals": "1.7.2" 41 | }, 42 | "dependencies": { 43 | "@hot-loader/react-dom": "16.13.0", 44 | "@material-ui/core": "4.9.8", 45 | "@material-ui/icons": "4.9.1", 46 | "body-parser": "1.19.0", 47 | "compression": "1.7.4", 48 | "cookie-parser": "1.4.5", 49 | "cors": "2.8.5", 50 | "express": "4.17.1", 51 | "express-jwt": "5.3.1", 52 | "helmet": "3.22.0", 53 | "jsonwebtoken": "8.5.1", 54 | "lodash": "4.17.15", 55 | "mongoose": "5.9.7", 56 | "react": "16.13.1", 57 | "react-dom": "16.13.1", 58 | "react-hot-loader": "4.12.20", 59 | "react-router": "5.1.2", 60 | "react-router-dom": "5.1.2" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /client/core/Menu.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import AppBar from '@material-ui/core/AppBar' 3 | import Toolbar from '@material-ui/core/Toolbar' 4 | import Typography from '@material-ui/core/Typography' 5 | import IconButton from '@material-ui/core/IconButton' 6 | import HomeIcon from '@material-ui/icons/Home' 7 | import Button from '@material-ui/core/Button' 8 | import auth from './../auth/auth-helper' 9 | import {Link, withRouter} from 'react-router-dom' 10 | 11 | const isActive = (history, path) => { 12 | if (history.location.pathname == path) 13 | return {color: '#ff4081'} 14 | else 15 | return {color: '#ffffff'} 16 | } 17 | const Menu = withRouter(({history}) => ( 18 | 19 | 20 | 21 | MERN Skeleton 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | { 32 | !auth.isAuthenticated() && ( 33 | 34 | 36 | 37 | 38 | 40 | 41 | ) 42 | } 43 | { 44 | auth.isAuthenticated() && ( 45 | 46 | 47 | 48 | 51 | ) 52 | } 53 | 54 | 55 | )) 56 | 57 | export default Menu 58 | -------------------------------------------------------------------------------- /client/user/api-user.js: -------------------------------------------------------------------------------- 1 | const create = async (user) => { 2 | try { 3 | let response = await fetch('/api/users/', { 4 | method: 'POST', 5 | headers: { 6 | 'Accept': 'application/json', 7 | 'Content-Type': 'application/json' 8 | }, 9 | body: JSON.stringify(user) 10 | }) 11 | return await response.json() 12 | } catch(err) { 13 | console.log(err) 14 | } 15 | } 16 | 17 | const list = async (signal) => { 18 | try { 19 | let response = await fetch('/api/users/', { 20 | method: 'GET', 21 | signal: signal, 22 | }) 23 | return await response.json() 24 | } catch(err) { 25 | console.log(err) 26 | } 27 | } 28 | 29 | const read = async (params, credentials, signal) => { 30 | try { 31 | let response = await fetch('/api/users/' + params.userId, { 32 | method: 'GET', 33 | signal: signal, 34 | headers: { 35 | 'Accept': 'application/json', 36 | 'Content-Type': 'application/json', 37 | 'Authorization': 'Bearer ' + credentials.t 38 | } 39 | }) 40 | return await response.json() 41 | } catch(err) { 42 | console.log(err) 43 | } 44 | } 45 | 46 | const update = async (params, credentials, user) => { 47 | try { 48 | let response = await fetch('/api/users/' + params.userId, { 49 | method: 'PUT', 50 | headers: { 51 | 'Accept': 'application/json', 52 | 'Content-Type': 'application/json', 53 | 'Authorization': 'Bearer ' + credentials.t 54 | }, 55 | body: JSON.stringify(user) 56 | }) 57 | return await response.json() 58 | } catch(err) { 59 | console.log(err) 60 | } 61 | } 62 | 63 | const remove = async (params, credentials) => { 64 | try { 65 | let response = await fetch('/api/users/' + params.userId, { 66 | method: 'DELETE', 67 | headers: { 68 | 'Accept': 'application/json', 69 | 'Content-Type': 'application/json', 70 | 'Authorization': 'Bearer ' + credentials.t 71 | } 72 | }) 73 | return await response.json() 74 | } catch(err) { 75 | console.log(err) 76 | } 77 | } 78 | 79 | export { 80 | create, 81 | list, 82 | read, 83 | update, 84 | remove 85 | } -------------------------------------------------------------------------------- /client/user/DeleteUser.js: -------------------------------------------------------------------------------- 1 | import React, {useState} from 'react' 2 | import PropTypes from 'prop-types' 3 | import IconButton from '@material-ui/core/IconButton' 4 | import Button from '@material-ui/core/Button' 5 | import DeleteIcon from '@material-ui/icons/Delete' 6 | import Dialog from '@material-ui/core/Dialog' 7 | import DialogActions from '@material-ui/core/DialogActions' 8 | import DialogContent from '@material-ui/core/DialogContent' 9 | import DialogContentText from '@material-ui/core/DialogContentText' 10 | import DialogTitle from '@material-ui/core/DialogTitle' 11 | import auth from './../auth/auth-helper' 12 | import {remove} from './api-user.js' 13 | import {Redirect} from 'react-router-dom' 14 | 15 | export default function DeleteUser(props) { 16 | const [open, setOpen] = useState(false) 17 | const [redirect, setRedirect] = useState(false) 18 | 19 | const jwt = auth.isAuthenticated() 20 | const clickButton = () => { 21 | setOpen(true) 22 | } 23 | const deleteAccount = () => { 24 | remove({ 25 | userId: props.userId 26 | }, {t: jwt.token}).then((data) => { 27 | if (data && data.error) { 28 | console.log(data.error) 29 | } else { 30 | auth.clearJWT(() => console.log('deleted')) 31 | setRedirect(true) 32 | } 33 | }) 34 | } 35 | const handleRequestClose = () => { 36 | setOpen(false) 37 | } 38 | 39 | if (redirect) { 40 | return 41 | } 42 | return ( 43 | 44 | 45 | 46 | 47 | 48 | {"Delete Account"} 49 | 50 | 51 | Confirm to delete your account. 52 | 53 | 54 | 55 | 58 | 61 | 62 | 63 | ) 64 | 65 | } 66 | DeleteUser.propTypes = { 67 | userId: PropTypes.string.isRequired 68 | } 69 | 70 | -------------------------------------------------------------------------------- /server/controllers/user.controller.js: -------------------------------------------------------------------------------- 1 | import User from '../models/user.model' 2 | import extend from 'lodash/extend' 3 | import errorHandler from './../helpers/dbErrorHandler' 4 | 5 | const create = async (req, res) => { 6 | const user = new User(req.body) 7 | try { 8 | await user.save() 9 | return res.status(200).json({ 10 | message: "Successfully signed up!" 11 | }) 12 | } catch (err) { 13 | return res.status(400).json({ 14 | error: errorHandler.getErrorMessage(err) 15 | }) 16 | } 17 | } 18 | 19 | /** 20 | * Load user and append to req. 21 | */ 22 | const userByID = async (req, res, next, id) => { 23 | try { 24 | let user = await User.findById(id) 25 | if (!user) 26 | return res.status('400').json({ 27 | error: "User not found" 28 | }) 29 | req.profile = user 30 | next() 31 | } catch (err) { 32 | return res.status('400').json({ 33 | error: "Could not retrieve user" 34 | }) 35 | } 36 | } 37 | 38 | const read = (req, res) => { 39 | req.profile.hashed_password = undefined 40 | req.profile.salt = undefined 41 | return res.json(req.profile) 42 | } 43 | 44 | const list = async (req, res) => { 45 | try { 46 | let users = await User.find().select('name email updated created') 47 | res.json(users) 48 | } catch (err) { 49 | return res.status(400).json({ 50 | error: errorHandler.getErrorMessage(err) 51 | }) 52 | } 53 | } 54 | 55 | const update = async (req, res) => { 56 | try { 57 | let user = req.profile 58 | user = extend(user, req.body) 59 | user.updated = Date.now() 60 | await user.save() 61 | user.hashed_password = undefined 62 | user.salt = undefined 63 | res.json(user) 64 | } catch (err) { 65 | return res.status(400).json({ 66 | error: errorHandler.getErrorMessage(err) 67 | }) 68 | } 69 | } 70 | 71 | const remove = async (req, res) => { 72 | try { 73 | let user = req.profile 74 | let deletedUser = await user.remove() 75 | deletedUser.hashed_password = undefined 76 | deletedUser.salt = undefined 77 | res.json(deletedUser) 78 | } catch (err) { 79 | return res.status(400).json({ 80 | error: errorHandler.getErrorMessage(err) 81 | }) 82 | } 83 | } 84 | 85 | export default { 86 | create, 87 | userByID, 88 | read, 89 | list, 90 | remove, 91 | update 92 | } 93 | -------------------------------------------------------------------------------- /server/express.js: -------------------------------------------------------------------------------- 1 | import express from 'express' 2 | import path from 'path' 3 | import bodyParser from 'body-parser' 4 | import cookieParser from 'cookie-parser' 5 | import compress from 'compression' 6 | import cors from 'cors' 7 | import helmet from 'helmet' 8 | import Template from './../template' 9 | import userRoutes from './routes/user.routes' 10 | import authRoutes from './routes/auth.routes' 11 | 12 | // modules for server side rendering 13 | import React from 'react' 14 | import ReactDOMServer from 'react-dom/server' 15 | import MainRouter from './../client/MainRouter' 16 | import { StaticRouter } from 'react-router-dom' 17 | 18 | import { ServerStyleSheets, ThemeProvider } from '@material-ui/styles' 19 | import theme from './../client/theme' 20 | //end 21 | 22 | //comment out before building for production 23 | import devBundle from './devBundle' 24 | 25 | const CURRENT_WORKING_DIR = process.cwd() 26 | const app = express() 27 | 28 | //comment out before building for production 29 | devBundle.compile(app) 30 | 31 | // parse body params and attache them to req.body 32 | app.use(bodyParser.json()) 33 | app.use(bodyParser.urlencoded({ extended: true })) 34 | app.use(cookieParser()) 35 | app.use(compress()) 36 | // secure apps by setting various HTTP headers 37 | app.use(helmet()) 38 | // enable CORS - Cross Origin Resource Sharing 39 | app.use(cors()) 40 | 41 | app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist'))) 42 | 43 | // mount routes 44 | app.use('/', userRoutes) 45 | app.use('/', authRoutes) 46 | 47 | app.get('*', (req, res) => { 48 | const sheets = new ServerStyleSheets() 49 | const context = {} 50 | const markup = ReactDOMServer.renderToString( 51 | sheets.collect( 52 | 53 | 54 | 55 | 56 | 57 | ) 58 | ) 59 | if (context.url) { 60 | return res.redirect(303, context.url) 61 | } 62 | const css = sheets.toString() 63 | res.status(200).send(Template({ 64 | markup: markup, 65 | css: css 66 | })) 67 | }) 68 | 69 | // Catch unauthorised errors 70 | app.use((err, req, res, next) => { 71 | if (err.name === 'UnauthorizedError') { 72 | res.status(401).json({"error" : err.name + ": " + err.message}) 73 | }else if (err) { 74 | res.status(400).json({"error" : err.name + ": " + err.message}) 75 | console.log(err) 76 | } 77 | }) 78 | 79 | export default app 80 | -------------------------------------------------------------------------------- /client/user/Users.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react' 2 | import { makeStyles } from '@material-ui/core/styles' 3 | import Paper from '@material-ui/core/Paper' 4 | import List from '@material-ui/core/List' 5 | import ListItem from '@material-ui/core/ListItem' 6 | import ListItemAvatar from '@material-ui/core/ListItemAvatar' 7 | import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction' 8 | import ListItemText from '@material-ui/core/ListItemText' 9 | import Avatar from '@material-ui/core/Avatar' 10 | import IconButton from '@material-ui/core/IconButton' 11 | import Typography from '@material-ui/core/Typography' 12 | import ArrowForward from '@material-ui/icons/ArrowForward' 13 | import Person from '@material-ui/icons/Person' 14 | import {Link} from 'react-router-dom' 15 | import {list} from './api-user.js' 16 | 17 | const useStyles = makeStyles(theme => ({ 18 | root: theme.mixins.gutters({ 19 | padding: theme.spacing(1), 20 | margin: theme.spacing(5) 21 | }), 22 | title: { 23 | margin: `${theme.spacing(4)}px 0 ${theme.spacing(2)}px`, 24 | color: theme.palette.openTitle 25 | } 26 | })) 27 | 28 | export default function Users() { 29 | const classes = useStyles() 30 | const [users, setUsers] = useState([]) 31 | 32 | useEffect(() => { 33 | const abortController = new AbortController() 34 | const signal = abortController.signal 35 | 36 | list(signal).then((data) => { 37 | if (data && data.error) { 38 | console.log(data.error) 39 | } else { 40 | setUsers(data) 41 | } 42 | }) 43 | 44 | return function cleanup(){ 45 | abortController.abort() 46 | } 47 | }, []) 48 | 49 | 50 | return ( 51 | 52 | 53 | All Users 54 | 55 | 56 | {users.map((item, i) => { 57 | return 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | }) 73 | } 74 | 75 | 76 | ) 77 | } 78 | -------------------------------------------------------------------------------- /client/user/Profile.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react' 2 | import { makeStyles } from '@material-ui/core/styles' 3 | import Paper from '@material-ui/core/Paper' 4 | import List from '@material-ui/core/List' 5 | import ListItem from '@material-ui/core/ListItem' 6 | import ListItemAvatar from '@material-ui/core/ListItemAvatar' 7 | import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction' 8 | import ListItemText from '@material-ui/core/ListItemText' 9 | import Avatar from '@material-ui/core/Avatar' 10 | import IconButton from '@material-ui/core/IconButton' 11 | import Typography from '@material-ui/core/Typography' 12 | import Edit from '@material-ui/icons/Edit' 13 | import Person from '@material-ui/icons/Person' 14 | import Divider from '@material-ui/core/Divider' 15 | import DeleteUser from './DeleteUser' 16 | import auth from './../auth/auth-helper' 17 | import {read} from './api-user.js' 18 | import {Redirect, Link} from 'react-router-dom' 19 | 20 | const useStyles = makeStyles(theme => ({ 21 | root: theme.mixins.gutters({ 22 | maxWidth: 600, 23 | margin: 'auto', 24 | padding: theme.spacing(3), 25 | marginTop: theme.spacing(5) 26 | }), 27 | title: { 28 | marginTop: theme.spacing(3), 29 | color: theme.palette.protectedTitle 30 | } 31 | })) 32 | 33 | export default function Profile({ match }) { 34 | const classes = useStyles() 35 | const [user, setUser] = useState({}) 36 | const [redirectToSignin, setRedirectToSignin] = useState(false) 37 | const jwt = auth.isAuthenticated() 38 | 39 | useEffect(() => { 40 | const abortController = new AbortController() 41 | const signal = abortController.signal 42 | 43 | read({ 44 | userId: match.params.userId 45 | }, {t: jwt.token}, signal).then((data) => { 46 | if (data && data.error) { 47 | setRedirectToSignin(true) 48 | } else { 49 | setUser(data) 50 | } 51 | }) 52 | 53 | return function cleanup(){ 54 | abortController.abort() 55 | } 56 | 57 | }, [match.params.userId]) 58 | 59 | if (redirectToSignin) { 60 | return 61 | } 62 | return ( 63 | 64 | 65 | Profile 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | { 75 | auth.isAuthenticated().user && auth.isAuthenticated().user._id == user._id && 76 | ( 77 | 78 | 79 | 80 | 81 | 82 | 83 | ) 84 | } 85 | 86 | 87 | 88 | 90 | 91 | 92 | 93 | ) 94 | } -------------------------------------------------------------------------------- /client/auth/Signin.js: -------------------------------------------------------------------------------- 1 | import React, {useState} from 'react' 2 | import Card from '@material-ui/core/Card' 3 | import CardActions from '@material-ui/core/CardActions' 4 | import CardContent from '@material-ui/core/CardContent' 5 | import Button from '@material-ui/core/Button' 6 | import TextField from '@material-ui/core/TextField' 7 | import Typography from '@material-ui/core/Typography' 8 | import Icon from '@material-ui/core/Icon' 9 | import { makeStyles } from '@material-ui/core/styles' 10 | import auth from './../auth/auth-helper' 11 | import {Redirect} from 'react-router-dom' 12 | import {signin} from './api-auth.js' 13 | 14 | const useStyles = makeStyles(theme => ({ 15 | card: { 16 | maxWidth: 600, 17 | margin: 'auto', 18 | textAlign: 'center', 19 | marginTop: theme.spacing(5), 20 | paddingBottom: theme.spacing(2) 21 | }, 22 | error: { 23 | verticalAlign: 'middle' 24 | }, 25 | title: { 26 | marginTop: theme.spacing(2), 27 | color: theme.palette.openTitle 28 | }, 29 | textField: { 30 | marginLeft: theme.spacing(1), 31 | marginRight: theme.spacing(1), 32 | width: 300 33 | }, 34 | submit: { 35 | margin: 'auto', 36 | marginBottom: theme.spacing(2) 37 | } 38 | })) 39 | 40 | export default function Signin(props) { 41 | const classes = useStyles() 42 | const [values, setValues] = useState({ 43 | email: '', 44 | password: '', 45 | error: '', 46 | redirectToReferrer: false 47 | }) 48 | 49 | const clickSubmit = () => { 50 | const user = { 51 | email: values.email || undefined, 52 | password: values.password || undefined 53 | } 54 | 55 | signin(user).then((data) => { 56 | if (data.error) { 57 | setValues({ ...values, error: data.error}) 58 | } else { 59 | auth.authenticate(data, () => { 60 | setValues({ ...values, error: '',redirectToReferrer: true}) 61 | }) 62 | } 63 | }) 64 | } 65 | 66 | const handleChange = name => event => { 67 | setValues({ ...values, [name]: event.target.value }) 68 | } 69 | 70 | const {from} = props.location.state || { 71 | from: { 72 | pathname: '/' 73 | } 74 | } 75 | const {redirectToReferrer} = values 76 | if (redirectToReferrer) { 77 | return () 78 | } 79 | 80 | return ( 81 | 82 | 83 | 84 | Sign In 85 | 86 |
87 | 88 |
{ 89 | values.error && ( 90 | error 91 | {values.error} 92 | ) 93 | } 94 |
95 | 96 | 97 | 98 |
99 | ) 100 | } 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MERN Skeleton 2.0 2 | - *Looking for the first edition code? [Check here](https://github.com/shamahoque/mern-skeleton/tree/master)* 3 | 4 | A skeleton application with basic user CRUD and auth features - developed using React, Node, Express and MongoDB. 5 | 6 | ![MERN Skeleton](https://mernbook.s3.amazonaws.com/git+/skeleton2.png "MERN Skeleton") 7 | 8 | ### [Live Demo](http://skeleton2.mernbook.com/ "MERN Skeleton") 9 | 10 | #### What you need to run this code 11 | 1. Node (13.12.0) 12 | 2. NPM (6.14.4) or Yarn (1.22.4) 13 | 3. MongoDB (4.2.0) 14 | 15 | #### How to run this code 16 | 1. Make sure MongoDB is running on your system 17 | 2. Clone this repository 18 | 3. Open command line in the cloned folder, 19 | - To install dependencies, run ``` npm install ``` or ``` yarn ``` 20 | - To run the application for development, run ``` npm run development ``` or ``` yarn development ``` 21 | 4. Open [localhost:3000](http://localhost:3000/) in the browser 22 | ---- 23 | ### More applications built by extending this skeleton 24 | 25 | * [MERN Social](https://github.com/shamahoque/mern-social/tree/second-edition) 26 | * [MERN Classroom](https://github.com/shamahoque/mern-classroom) 27 | * [MERN Marketplace](https://github.com/shamahoque/mern-marketplace/tree/second-edition) 28 | * [MERN Expense Tracker](https://github.com/shamahoque/mern-expense-tracker) 29 | * [MERN Mediastream](https://github.com/shamahoque/mern-mediastream/tree/second-edition) 30 | * [MERN VR Game](https://github.com/shamahoque/mern-vrgame/tree/second-edition) 31 | 32 | Learn more at [mernbook.com](http://www.mernbook.com/) 33 | 34 | ---- 35 | ## Get the book 36 | #### [Full-Stack React Projects - Second Edition](https://www.packtpub.com/web-development/full-stack-react-projects-second-edition) 37 | *Learn MERN stack development by building modern web apps using MongoDB, Express, React, and Node.js* 38 | 39 | Full-Stack React Projects 40 | 41 | React combined with industry-tested, server-side technologies, such as Node, Express, and MongoDB, enables you to develop and deploy robust real-world full-stack web apps. This updated second edition focuses on the latest versions and conventions of the technologies in this stack, along with their new features such as Hooks in React and async/await in JavaScript. The book also explores advanced topics such as implementing real-time bidding, a web-based classroom app, and data visualization in an expense tracking app. 42 | 43 | Full-Stack React Projects will take you through the process of preparing the development environment for MERN stack-based web development, creating a basic skeleton app, and extending it to build six different web apps. You'll build apps for social media, classrooms, media streaming, online marketplaces with real-time bidding, and web-based games with virtual reality features. Throughout the book, you'll learn how MERN stack web development works, extend its capabilities for complex features, and gain actionable insights into creating MERN-based apps, along with exploring industry best practices to meet the ever-increasing demands of the real world. 44 | 45 | Things you'll learn in this book: 46 | 47 | - Extend a MERN-based application to build a variety of applications 48 | - Add real-time communication capabilities with Socket.IO 49 | - Implement data visualization features for React applications using Victory 50 | - Develop media streaming applications using MongoDB GridFS 51 | - Improve SEO for your MERN apps by implementing server-side rendering with data 52 | - Implement user authentication and authorization using JSON web tokens 53 | - Set up and use React 360 to develop user interfaces with VR capabilities 54 | - Make your MERN stack applications reliable and scalable with industry best practices 55 | 56 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1839215410) today! 57 | 58 | --- 59 | -------------------------------------------------------------------------------- /client/user/Signup.js: -------------------------------------------------------------------------------- 1 | import React, {useState} from 'react' 2 | import Card from '@material-ui/core/Card' 3 | import CardActions from '@material-ui/core/CardActions' 4 | import CardContent from '@material-ui/core/CardContent' 5 | import Button from '@material-ui/core/Button' 6 | import TextField from '@material-ui/core/TextField' 7 | import Typography from '@material-ui/core/Typography' 8 | import Icon from '@material-ui/core/Icon' 9 | import { makeStyles } from '@material-ui/core/styles' 10 | import {create} from './api-user.js' 11 | import Dialog from '@material-ui/core/Dialog' 12 | import DialogActions from '@material-ui/core/DialogActions' 13 | import DialogContent from '@material-ui/core/DialogContent' 14 | import DialogContentText from '@material-ui/core/DialogContentText' 15 | import DialogTitle from '@material-ui/core/DialogTitle' 16 | import {Link} from 'react-router-dom' 17 | 18 | const useStyles = makeStyles(theme => ({ 19 | card: { 20 | maxWidth: 600, 21 | margin: 'auto', 22 | textAlign: 'center', 23 | marginTop: theme.spacing(5), 24 | paddingBottom: theme.spacing(2) 25 | }, 26 | error: { 27 | verticalAlign: 'middle' 28 | }, 29 | title: { 30 | marginTop: theme.spacing(2), 31 | color: theme.palette.openTitle 32 | }, 33 | textField: { 34 | marginLeft: theme.spacing(1), 35 | marginRight: theme.spacing(1), 36 | width: 300 37 | }, 38 | submit: { 39 | margin: 'auto', 40 | marginBottom: theme.spacing(2) 41 | } 42 | })) 43 | 44 | export default function Signup() { 45 | const classes = useStyles() 46 | const [values, setValues] = useState({ 47 | name: '', 48 | password: '', 49 | email: '', 50 | open: false, 51 | error: '' 52 | }) 53 | 54 | const handleChange = name => event => { 55 | setValues({ ...values, [name]: event.target.value }) 56 | } 57 | 58 | const clickSubmit = () => { 59 | const user = { 60 | name: values.name || undefined, 61 | email: values.email || undefined, 62 | password: values.password || undefined 63 | } 64 | create(user).then((data) => { 65 | if (data.error) { 66 | setValues({ ...values, error: data.error}) 67 | } else { 68 | setValues({ ...values, error: '', open: true}) 69 | } 70 | }) 71 | } 72 | 73 | return (
74 | 75 | 76 | 77 | Sign Up 78 | 79 |
80 |
81 | 82 |
{ 83 | values.error && ( 84 | error 85 | {values.error}) 86 | } 87 |
88 | 89 | 90 | 91 |
92 | 93 | New Account 94 | 95 | 96 | New account successfully created. 97 | 98 | 99 | 100 | 101 | 104 | 105 | 106 | 107 |
108 | ) 109 | } -------------------------------------------------------------------------------- /client/user/EditProfile.js: -------------------------------------------------------------------------------- 1 | import React, {useState, useEffect} from 'react' 2 | import Card from '@material-ui/core/Card' 3 | import CardActions from '@material-ui/core/CardActions' 4 | import CardContent from '@material-ui/core/CardContent' 5 | import Button from '@material-ui/core/Button' 6 | import TextField from '@material-ui/core/TextField' 7 | import Typography from '@material-ui/core/Typography' 8 | import Icon from '@material-ui/core/Icon' 9 | import { makeStyles } from '@material-ui/core/styles' 10 | import auth from './../auth/auth-helper' 11 | import {read, update} from './api-user.js' 12 | import {Redirect} from 'react-router-dom' 13 | 14 | const useStyles = makeStyles(theme => ({ 15 | card: { 16 | maxWidth: 600, 17 | margin: 'auto', 18 | textAlign: 'center', 19 | marginTop: theme.spacing(5), 20 | paddingBottom: theme.spacing(2) 21 | }, 22 | title: { 23 | margin: theme.spacing(2), 24 | color: theme.palette.protectedTitle 25 | }, 26 | error: { 27 | verticalAlign: 'middle' 28 | }, 29 | textField: { 30 | marginLeft: theme.spacing(1), 31 | marginRight: theme.spacing(1), 32 | width: 300 33 | }, 34 | submit: { 35 | margin: 'auto', 36 | marginBottom: theme.spacing(2) 37 | } 38 | })) 39 | 40 | export default function EditProfile({ match }) { 41 | const classes = useStyles() 42 | const [values, setValues] = useState({ 43 | name: '', 44 | password: '', 45 | email: '', 46 | open: false, 47 | error: '', 48 | redirectToProfile: false 49 | }) 50 | const jwt = auth.isAuthenticated() 51 | 52 | useEffect(() => { 53 | const abortController = new AbortController() 54 | const signal = abortController.signal 55 | 56 | read({ 57 | userId: match.params.userId 58 | }, {t: jwt.token}, signal).then((data) => { 59 | if (data && data.error) { 60 | setValues({...values, error: data.error}) 61 | } else { 62 | setValues({...values, name: data.name, email: data.email}) 63 | } 64 | }) 65 | return function cleanup(){ 66 | abortController.abort() 67 | } 68 | 69 | }, [match.params.userId]) 70 | 71 | const clickSubmit = () => { 72 | const user = { 73 | name: values.name || undefined, 74 | email: values.email || undefined, 75 | password: values.password || undefined 76 | } 77 | update({ 78 | userId: match.params.userId 79 | }, { 80 | t: jwt.token 81 | }, user).then((data) => { 82 | if (data && data.error) { 83 | setValues({...values, error: data.error}) 84 | } else { 85 | setValues({...values, userId: data._id, redirectToProfile: true}) 86 | } 87 | }) 88 | } 89 | const handleChange = name => event => { 90 | setValues({...values, [name]: event.target.value}) 91 | } 92 | 93 | if (values.redirectToProfile) { 94 | return () 95 | } 96 | return ( 97 | 98 | 99 | 100 | Edit Profile 101 | 102 |
103 |
104 | 105 |
{ 106 | values.error && ( 107 | error 108 | {values.error} 109 | ) 110 | } 111 |
112 | 113 | 114 | 115 |
116 | ) 117 | } 118 | 119 | --------------------------------------------------------------------------------