├── Resources ├── a1.png ├── a2.png ├── a3.png └── blueskeinstar-5de7e7.svg ├── client ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── src │ ├── index.js │ ├── reportWebVitals.js │ ├── components │ │ ├── screens │ │ │ ├── ResetPasswordScreen.css │ │ │ ├── RegisterScreen.css │ │ │ ├── ForgotPasswordScreen.css │ │ │ ├── LoginScreen.css │ │ │ ├── PrivateScreen.js │ │ │ ├── ForgotPasswordScreen.js │ │ │ ├── LoginScreen.js │ │ │ ├── ResetPasswordScreen.js │ │ │ └── RegisterScreen.js │ │ └── routing │ │ │ └── PrivateRoute.js │ ├── App.js │ └── index.css ├── .gitignore ├── package.json └── README.md ├── server ├── controllers │ ├── private.js │ └── auth.js ├── utils │ ├── errorResponse.js │ └── sendEmail.js ├── routes │ ├── private.js │ └── auth.js ├── config │ └── db.js ├── package.json ├── middleware │ ├── error.js │ └── auth.js ├── server.js └── models │ └── User.js ├── .gitignore └── README.md /Resources/a1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Honestdev125/mern-authentication/HEAD/Resources/a1.png -------------------------------------------------------------------------------- /Resources/a2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Honestdev125/mern-authentication/HEAD/Resources/a2.png -------------------------------------------------------------------------------- /Resources/a3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Honestdev125/mern-authentication/HEAD/Resources/a3.png -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Honestdev125/mern-authentication/HEAD/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Honestdev125/mern-authentication/HEAD/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Honestdev125/mern-authentication/HEAD/client/public/logo512.png -------------------------------------------------------------------------------- /server/controllers/private.js: -------------------------------------------------------------------------------- 1 | exports.getPrivateData = (req, res, next) => { 2 | res.status(200).json({ 3 | success: true, 4 | data: 'You got access to the private data in this route', 5 | }); 6 | }; 7 | -------------------------------------------------------------------------------- /server/utils/errorResponse.js: -------------------------------------------------------------------------------- 1 | class ErrorResponse extends Error { 2 | constructor(message, statusCode) { 3 | super(message); 4 | this.statusCode = statusCode; 5 | } 6 | } 7 | 8 | module.exports = ErrorResponse; 9 | -------------------------------------------------------------------------------- /server/routes/private.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router(); 3 | const { getPrivateData } = require('../controllers/private'); 4 | const { protect } = require('../middleware/auth'); 5 | 6 | router.route('/').get(protect, getPrivateData); 7 | 8 | module.exports = router; 9 | -------------------------------------------------------------------------------- /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 reportWebVitals from './reportWebVitals'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | reportWebVitals(); 15 | -------------------------------------------------------------------------------- /server/config/db.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const connectDB = async () => { 3 | await mongoose.connect(process.env.MONGO_URI, { 4 | useNewUrlParser: true, 5 | useCreateIndex: true, 6 | useUnifiedTopology: true, 7 | useFindAndModify: true, 8 | }); 9 | console.log('Mongodb connected'); 10 | }; 11 | 12 | module.exports = connectDB; 13 | -------------------------------------------------------------------------------- /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/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /server/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const router = express.Router(); 3 | const { 4 | register, 5 | login, 6 | forgotPassword, 7 | resetPassword, 8 | } = require('../controllers/auth'); 9 | 10 | router.post('/register', register); 11 | router.post('/login', login); 12 | router.post('/forgotpassword', forgotPassword); 13 | router.put('/passwordreset/:resetToken', resetPassword); 14 | 15 | module.exports = router; 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | node_modules/ 6 | /.pnp 7 | .pnp.js 8 | 9 | # testing 10 | /coverage 11 | 12 | # production 13 | /build 14 | 15 | # misc 16 | config.env 17 | .DS_Store 18 | .env.local 19 | .env.development.local 20 | .env.test.local 21 | .env.production.local 22 | 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | -------------------------------------------------------------------------------- /client/src/components/screens/ResetPasswordScreen.css: -------------------------------------------------------------------------------- 1 | .resetpassword-screen { 2 | width: 100%; 3 | height: 100vh; 4 | display: flex; 5 | justify-content: center; 6 | align-items: center; 7 | } 8 | 9 | .resetpassword-screen__form { 10 | width: 380px; 11 | padding: 1.5rem; 12 | box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.2); 13 | background: #fff; 14 | } 15 | 16 | .resetpassword-screen__title { 17 | text-align: center; 18 | margin-bottom: 1rem; 19 | } 20 | -------------------------------------------------------------------------------- /client/src/components/routing/PrivateRoute.js: -------------------------------------------------------------------------------- 1 | import { Redirect, Route } from 'react-router-dom'; 2 | 3 | const PrivateRoute = ({ component: Component, ...rest }) => { 4 | return ( 5 | 8 | localStorage.getItem('authToken') ? ( 9 | 10 | ) : ( 11 | 12 | ) 13 | } 14 | /> 15 | ); 16 | }; 17 | 18 | export default PrivateRoute; 19 | -------------------------------------------------------------------------------- /client/src/components/screens/RegisterScreen.css: -------------------------------------------------------------------------------- 1 | .register-screen { 2 | width: 100%; 3 | height: 100vh; 4 | display: flex; 5 | justify-content: center; 6 | align-items: center; 7 | } 8 | 9 | .register-screen__form { 10 | width: 380px; 11 | padding: 1.5rem; 12 | box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.2); 13 | background: #fff; 14 | } 15 | 16 | .register-screen__title { 17 | text-align: center; 18 | margin-bottom: 1rem; 19 | } 20 | 21 | .register-screen__subtext { 22 | font-size: 0.7rem; 23 | display: block; 24 | margin: 0.5rem 0; 25 | } 26 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "server", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "server.js", 6 | "scripts": { 7 | "start": "node server.js", 8 | "server": "nodemon server.js" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "bcrypt": "^5.0.1", 15 | "cors": "^2.8.5", 16 | "dotenv": "^8.2.0", 17 | "express": "^4.17.1", 18 | "jsonwebtoken": "^8.5.1", 19 | "mongoose": "^5.12.3", 20 | "nodemailer": "^6.5.0", 21 | "nodemon": "^2.0.7" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /client/src/components/screens/ForgotPasswordScreen.css: -------------------------------------------------------------------------------- 1 | .forgotpassword-screen { 2 | width: 100%; 3 | height: 100vh; 4 | display: flex; 5 | justify-content: center; 6 | align-items: center; 7 | } 8 | 9 | .forgotpassword-screen__form { 10 | width: 380px; 11 | padding: 1.5rem; 12 | box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.2); 13 | background: #fff; 14 | } 15 | 16 | .forgotpassword-screen__title { 17 | text-align: center; 18 | margin-bottom: 1rem; 19 | } 20 | 21 | .forgotpassword-screen__subtext { 22 | font-size: 0.7rem; 23 | display: block; 24 | margin: 0.5rem 0; 25 | } 26 | -------------------------------------------------------------------------------- /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 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /client/src/components/screens/LoginScreen.css: -------------------------------------------------------------------------------- 1 | .login-screen { 2 | width: 100%; 3 | height: 100vh; 4 | display: flex; 5 | justify-content: center; 6 | align-items: center; 7 | } 8 | 9 | .login-screen__form { 10 | width: 380px; 11 | padding: 1.5rem; 12 | box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.2); 13 | background: #fff; 14 | } 15 | 16 | .login-screen__title { 17 | text-align: center; 18 | margin-bottom: 1rem; 19 | } 20 | 21 | .login-screen__forgotpassword { 22 | font-size: 0.7rem; 23 | } 24 | 25 | .login-screen__subtext { 26 | font-size: 0.7rem; 27 | display: block; 28 | margin: 0.5rem 0; 29 | } 30 | -------------------------------------------------------------------------------- /server/middleware/error.js: -------------------------------------------------------------------------------- 1 | const ErrorResponse = require('../utils/errorResponse'); 2 | const errorHandler = (err, req, res, next) => { 3 | let error = { ...err }; 4 | error.message = err.message; 5 | if (err.code === 11000) { 6 | const message = 'Dupplicate field value entered'; 7 | error = new ErrorResponse(message, 400); 8 | } 9 | 10 | if (err.name === 'ValidationError') { 11 | const message = Object.values(err.errors).map((val) => val.message); 12 | error = new ErrorResponse(message, 400); 13 | } 14 | 15 | res.status(error.statusCode || 500).json({ 16 | success: false, 17 | error: error.message || 'Server Error', 18 | }); 19 | }; 20 | 21 | module.exports = errorHandler; 22 | -------------------------------------------------------------------------------- /server/utils/sendEmail.js: -------------------------------------------------------------------------------- 1 | const nodemailer = require('nodemailer'); 2 | const sendEmail = (options) => { 3 | const transporter = nodemailer.createTransport({ 4 | service: process.env.EMAIL_SERVICE, 5 | auth: { 6 | user: process.env.EMAIL_USERNAME, 7 | pass: process.env.EMAIL_PASSWORD, 8 | }, 9 | }); 10 | const mailOptions = { 11 | from: process.env.EMAIL_FROM, 12 | to: options.to, 13 | subject: options.subject, 14 | html: options.text, 15 | }; 16 | transporter.sendMail(mailOptions, function (err, info) { 17 | if (err) { 18 | console.log(err); 19 | } else { 20 | console.log(info); 21 | } 22 | }); 23 | }; 24 | 25 | module.exports = sendEmail; 26 | -------------------------------------------------------------------------------- /server/server.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config({ path: './config.env' }); 2 | const express = require('express'); 3 | const connectDB = require('./config/db'); 4 | const cors = require('cors'); 5 | 6 | connectDB(); 7 | const errorHandler = require('./middleware/error'); 8 | 9 | const app = express(); 10 | const PORT = process.env.PORT || 5000; 11 | 12 | app.use(cors()); 13 | app.use(express.json()); 14 | app.use('/api/auth', require('./routes/auth')); 15 | app.use('/api/private', require('./routes/private')); 16 | 17 | app.use(errorHandler); 18 | 19 | const server = app.listen(PORT, () => { 20 | console.log(`Server is running on ${PORT}`); 21 | }); 22 | 23 | process.on('unhandledRejection', (err, promise) => { 24 | console.log(`Logged Error ${err}`); 25 | server.close(() => process.exit(1)); 26 | }); 27 | -------------------------------------------------------------------------------- /server/middleware/auth.js: -------------------------------------------------------------------------------- 1 | const jwt = require('jsonwebtoken'); 2 | const User = require('../models/User'); 3 | const ErrorResponse = require('../utils/errorResponse'); 4 | 5 | exports.protect = async (req, res, next) => { 6 | let token; 7 | if ( 8 | req.headers.authorization && 9 | req.headers.authorization.startsWith('Bearer') 10 | ) { 11 | token = req.headers.authorization.split(' ')[1]; 12 | } 13 | if (!token) { 14 | return next(new ErrorResponse('Not authorized to access this route', 401)); 15 | } 16 | try { 17 | const decoded = jwt.verify(token, process.env.JWT_SECRET); 18 | const user = await User.findById(decoded.id); 19 | if (!user) { 20 | return next(new ErrorResponse('No user found with this id', 404)); 21 | } 22 | req.user = user; 23 | next(); 24 | } catch (error) { 25 | return next(new ErrorResponse('Not authorized to access this route', 401)); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## MERN Authentication 2 | 3 | ## How to Use 4 | 5 | - Clone the repository. 6 | - Go to client directory and run command **npm install**. 7 | - Then run **npm start** to start the development server. 8 | - Go to server directory and create config.env file. 9 | - Setup the environment variables. 10 | - Run command **npm install** to install the dependencies. 11 | - Run command **npm run server** to start the server. 12 | 13 | ## Screenshots 14 | 15 | ![Register Screen](https://github.com/AnumMujahid/mern-authentication/blob/main/Resources/a1.png) 16 | 17 | *Screenshot 1: Register Screen* 18 | 19 |
20 | 21 | ![Login Screen](https://github.com/AnumMujahid/mern-authentication/blob/main/Resources/a2.png) 22 | 23 | *Screenshot 2: Login Screen* 24 | 25 |
26 | 27 | ![Forgot Password Screen](https://github.com/AnumMujahid/mern-authentication/blob/main/Resources/a3.png) 28 | 29 | *Screenshot 3: Forgot Password Screen* 30 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "proxy": "http://127.0.0.1:5000", 5 | "private": true, 6 | "dependencies": { 7 | "@testing-library/jest-dom": "^5.11.10", 8 | "@testing-library/react": "^11.2.6", 9 | "@testing-library/user-event": "^12.8.3", 10 | "axios": "^0.21.1", 11 | "react": "^17.0.2", 12 | "react-dom": "^17.0.2", 13 | "react-router-dom": "^5.2.0", 14 | "react-scripts": "4.0.3", 15 | "web-vitals": "^1.1.1" 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 | "eslintConfig": { 24 | "extends": [ 25 | "react-app", 26 | "react-app/jest" 27 | ] 28 | }, 29 | "browserslist": { 30 | "production": [ 31 | ">0.2%", 32 | "not dead", 33 | "not op_mini all" 34 | ], 35 | "development": [ 36 | "last 1 chrome version", 37 | "last 1 firefox version", 38 | "last 1 safari version" 39 | ] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /client/src/App.js: -------------------------------------------------------------------------------- 1 | import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; 2 | import PrivateRoute from './components/routing/PrivateRoute'; 3 | import PrivateScreen from './components/screens/PrivateScreen'; 4 | import LoginScreen from './components/screens/LoginScreen'; 5 | import RegisterScreen from './components/screens/RegisterScreen'; 6 | import ForgotPasswordScreen from './components/screens/ForgotPasswordScreen'; 7 | import ResetPasswordScreen from './components/screens/ResetPasswordScreen'; 8 | 9 | const App = () => { 10 | return ( 11 | 12 |
13 | 14 | 15 | 16 | 17 | 22 | 27 | 28 |
29 |
30 | ); 31 | }; 32 | 33 | export default App; 34 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | box-sizing: border-box; 5 | } 6 | 7 | body { 8 | font-family: Arial, Helvetica, sans-serif; 9 | line-height: 1.7; 10 | background: #eee; 11 | color: #333; 12 | } 13 | 14 | .form-group, 15 | .form-group label, 16 | .form-group input { 17 | width: 100%; 18 | margin-bottom: 0.5rem; 19 | } 20 | 21 | .form-group label { 22 | font-size: 0.8rem; 23 | } 24 | 25 | .form-group input { 26 | padding: 10px 20px; 27 | border: none; 28 | border-bottom: 3px solid transparent; 29 | background-color: #eee; 30 | outline-width: 0; 31 | font-size: 1rem; 32 | } 33 | 34 | .form-group input:focus { 35 | border-bottom: 3px solid coral; 36 | } 37 | 38 | .btn { 39 | padding: 10px 20px; 40 | cursor: pointer; 41 | width: 100%; 42 | font-size: 1rem; 43 | border: none; 44 | } 45 | 46 | .btn:hover { 47 | opacity: 0.8; 48 | } 49 | 50 | .btn-primary { 51 | background-color: coral; 52 | color: #fff; 53 | } 54 | 55 | .error-message { 56 | width: 100%; 57 | display: inline-block; 58 | padding: 5px; 59 | background: red; 60 | color: #fff; 61 | text-align: center; 62 | margin: 0.5rem 0; 63 | } 64 | 65 | .success-message { 66 | width: 100%; 67 | display: inline-block; 68 | padding: 5px; 69 | background: green; 70 | color: #fff; 71 | text-align: center; 72 | margin: 0.5rem 0; 73 | } 74 | -------------------------------------------------------------------------------- /client/src/components/screens/PrivateScreen.js: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from 'react'; 2 | import axios from 'axios'; 3 | 4 | const PrivateScreen = ({ history }) => { 5 | const [error, setError] = useState(''); 6 | const [privateData, setPrivateData] = useState(''); 7 | 8 | const logoutHandler = () => { 9 | localStorage.removeItem('authToken'); 10 | history.push('/login'); 11 | }; 12 | 13 | useEffect(() => { 14 | if (!localStorage.getItem('authToken')) { 15 | history.push('/login'); 16 | } 17 | const fetchPrivateData = async () => { 18 | const config = { 19 | headers: { 20 | 'Content-Type': 'application/json', 21 | Authorization: `Bearer ${localStorage.getItem('authToken')}`, 22 | }, 23 | }; 24 | try { 25 | const { data } = await axios.get( 26 | 'http://localhost:5000/api/private', 27 | config 28 | ); 29 | setPrivateData(data.data); 30 | } catch (error) { 31 | localStorage.removeItem('authToken'); 32 | setError('You are not authorized please login'); 33 | } 34 | }; 35 | fetchPrivateData(); 36 | }, [history]); 37 | 38 | return error ? ( 39 | {error} 40 | ) : ( 41 | <> 42 |
{privateData}
43 | 44 | 45 | ); 46 | }; 47 | 48 | export default PrivateScreen; 49 | -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /server/models/User.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const bcrypt = require('bcrypt'); 3 | const jwt = require('jsonwebtoken'); 4 | const crypto = require('crypto'); 5 | 6 | const UserSchema = new mongoose.Schema({ 7 | username: { 8 | type: String, 9 | required: [true, 'Please provide a username'], 10 | }, 11 | email: { 12 | type: String, 13 | required: [true, 'Please provide an email'], 14 | unique: true, 15 | match: [ 16 | /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, 17 | 'Please provide a valid email', 18 | ], 19 | }, 20 | password: { 21 | type: String, 22 | required: [true, 'Please provide a password'], 23 | minlength: 6, 24 | select: false, 25 | }, 26 | resetPasswordToken: String, 27 | resetPasswordExpire: Date, 28 | }); 29 | 30 | UserSchema.pre('save', async function (next) { 31 | if (!this.isModified('password')) { 32 | next(); 33 | return; 34 | } 35 | const salt = await bcrypt.genSalt(10); 36 | this.password = await bcrypt.hash(this.password, salt); 37 | next(); 38 | }); 39 | 40 | UserSchema.methods.matchPasswords = async function (password) { 41 | return await bcrypt.compare(password, this.password); 42 | }; 43 | 44 | // require('crypto').randomBytes(35).toString('hex'); 45 | 46 | UserSchema.methods.getSignedToken = function () { 47 | return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { 48 | expiresIn: process.env.JWT_EXPIRE, 49 | }); 50 | }; 51 | 52 | UserSchema.methods.getResetPasswordToken = function () { 53 | const resetToken = crypto.randomBytes(20).toString('hex'); 54 | this.resetPasswordToken = crypto 55 | .createHash('sha256') 56 | .update(resetToken) 57 | .digest('hex'); 58 | this.resetPasswordExpire = Date.now() + 10 * (60 * 1000); 59 | return resetToken; 60 | }; 61 | 62 | const User = mongoose.model('User', UserSchema); 63 | 64 | module.exports = User; 65 | -------------------------------------------------------------------------------- /client/src/components/screens/ForgotPasswordScreen.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from 'react'; 2 | import axios from 'axios'; 3 | import './ForgotPasswordScreen.css'; 4 | 5 | const ForgotPasswordScreen = ({ history }) => { 6 | const [email, setEmail] = useState(''); 7 | const [error, setError] = useState(''); 8 | const [success, setSuccess] = useState(''); 9 | 10 | useEffect(() => { 11 | if (localStorage.getItem('authToken')) { 12 | history.push('/'); 13 | } 14 | }, [history]); 15 | 16 | const forgotPasswordHandler = async (e) => { 17 | e.preventDefault(); 18 | const config = { 19 | headers: { 20 | 'content-type': 'application/json', 21 | }, 22 | }; 23 | 24 | try { 25 | const { data } = await axios.post( 26 | 'http://localhost:5000/api/auth/forgotpassword', 27 | { email }, 28 | config 29 | ); 30 | setSuccess(data.data); 31 | } catch (error) { 32 | setError(error.response.data.error); 33 | setEmail(''); 34 | setTimeout(() => { 35 | setError(''); 36 | }, 5000); 37 | } 38 | }; 39 | return ( 40 |
41 |
45 |

Forgot Password

46 | {error && {error}} 47 | {success && {success}} 48 |
49 |

50 | Please enter the email address you register your account with. We 51 | will send you reset password confirmation to this email. 52 |

53 | 54 | setEmail(e.target.value)} 61 | required 62 | /> 63 |
64 | 67 |
68 |
69 | ); 70 | }; 71 | 72 | export default ForgotPasswordScreen; 73 | -------------------------------------------------------------------------------- /client/src/components/screens/LoginScreen.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from 'react'; 2 | import { Link } from 'react-router-dom'; 3 | import axios from 'axios'; 4 | import './LoginScreen.css'; 5 | 6 | const LoginScreen = ({ history }) => { 7 | const [email, setEmail] = useState(''); 8 | const [password, setPassword] = useState(''); 9 | const [error, setError] = useState(''); 10 | 11 | useEffect(() => { 12 | if (localStorage.getItem('authToken')) { 13 | history.push('/'); 14 | } 15 | }, [history]); 16 | 17 | const loginHandler = async (e) => { 18 | e.preventDefault(); 19 | const config = { 20 | headers: { 21 | 'content-type': 'application/json', 22 | }, 23 | }; 24 | 25 | try { 26 | const { data } = await axios.post( 27 | 'http://localhost:5000/api/auth/login', 28 | { email, password }, 29 | config 30 | ); 31 | localStorage.setItem('authToken', data.token); 32 | history.push('/'); 33 | } catch (error) { 34 | setError(error.response.data.error); 35 | setTimeout(() => { 36 | setError(''); 37 | }, 5000); 38 | } 39 | }; 40 | return ( 41 |
42 |
43 |

Login

44 | {error && {error}} 45 |
46 | 47 | setEmail(e.target.value)} 55 | required 56 | /> 57 |
58 |
59 | 69 | setPassword(e.target.value)} 77 | required 78 | /> 79 |
80 | 83 | 84 | Don't have an account? 85 | 86 | Register 87 | 88 | 89 |
90 |
91 | ); 92 | }; 93 | 94 | export default LoginScreen; 95 | -------------------------------------------------------------------------------- /client/src/components/screens/ResetPasswordScreen.js: -------------------------------------------------------------------------------- 1 | import { useState } from 'react'; 2 | import { Link } from 'react-router-dom'; 3 | import axios from 'axios'; 4 | 5 | import './ResetPasswordScreen.css'; 6 | 7 | const ResetPasswordScreen = ({ match }) => { 8 | const [password, setPassword] = useState(''); 9 | const [confirmPassword, setConfirmPassword] = useState(''); 10 | const [error, setError] = useState(''); 11 | const [success, setSuccess] = useState(''); 12 | 13 | const resetPasswordHandler = async (e) => { 14 | e.preventDefault(); 15 | 16 | const config = { 17 | header: { 18 | 'Content-Type': 'application/json', 19 | }, 20 | }; 21 | 22 | if (password !== confirmPassword) { 23 | setPassword(''); 24 | setConfirmPassword(''); 25 | setTimeout(() => { 26 | setError(''); 27 | }, 5000); 28 | return setError("Passwords don't match"); 29 | } 30 | 31 | try { 32 | const { data } = await axios.put( 33 | `http://localhost:5000/api/auth/passwordreset/${match.params.resetToken}`, 34 | { 35 | password, 36 | }, 37 | config 38 | ); 39 | 40 | console.log(data); 41 | setSuccess(data.data); 42 | } catch (error) { 43 | setError(error.response.data.error); 44 | setTimeout(() => { 45 | setError(''); 46 | }, 5000); 47 | } 48 | }; 49 | 50 | return ( 51 |
52 |
56 |

Forgot Password

57 | {error && {error} } 58 | {success && ( 59 | 60 | {success} Login 61 | 62 | )} 63 |
64 | 65 | setPassword(e.target.value)} 73 | /> 74 |
75 |
76 | 77 | setConfirmPassword(e.target.value)} 85 | /> 86 |
87 | 90 |
91 |
92 | ); 93 | }; 94 | 95 | export default ResetPasswordScreen; 96 | -------------------------------------------------------------------------------- /server/controllers/auth.js: -------------------------------------------------------------------------------- 1 | const User = require('../models/User'); 2 | const ErrorResponse = require('../utils/errorResponse'); 3 | const sendEmail = require('../utils/sendEmail'); 4 | const crypto = require('crypto'); 5 | 6 | exports.register = async (req, res, next) => { 7 | const { username, email, password } = req.body; 8 | try { 9 | const user = await User.create({ 10 | username, 11 | email, 12 | password, 13 | }); 14 | sendToken(user, 201, res); 15 | } catch (error) { 16 | next(error); 17 | } 18 | }; 19 | 20 | exports.login = async (req, res, next) => { 21 | const { email, password } = req.body; 22 | if (!email || !password) { 23 | return next(new ErrorResponse('Please provide an email and password', 400)); 24 | } 25 | try { 26 | const user = await User.findOne({ email }).select('+password'); 27 | if (!user) { 28 | return next(new ErrorResponse('Invalid Credentials', 401)); 29 | } 30 | const isMatch = await user.matchPasswords(password); 31 | if (!isMatch) { 32 | return next(new ErrorResponse('Invalid Credentials', 401)); 33 | } 34 | sendToken(user, 200, res); 35 | } catch (error) { 36 | next(error); 37 | } 38 | }; 39 | 40 | exports.forgotPassword = async (req, res, next) => { 41 | const { email } = req.body; 42 | try { 43 | const user = await User.findOne({ email }); 44 | if (!user) { 45 | next(new ErrorResponse('Email cannot be sent', 404)); 46 | } 47 | const resetToken = user.getResetPasswordToken(); 48 | await user.save(); 49 | const resetUrl = `http://localhost:3000/passwordreset/${resetToken}`; 50 | const message = `

You have requested a password reset

Please go to this link to reset your password

${resetUrl}`; 51 | try { 52 | await sendEmail({ 53 | to: user.email, 54 | subject: 'Password Reset Request', 55 | text: message, 56 | }); 57 | res.status(200).json({ success: true, data: 'Email Sent' }); 58 | } catch (error) { 59 | user.resetPasswordToken = undefined; 60 | user.resetPasswordExpire = undefined; 61 | await user.save(); 62 | next(new ErrorResponse('Email cannot be sent', 404)); 63 | } 64 | } catch (error) { 65 | next(error); 66 | } 67 | }; 68 | 69 | exports.resetPassword = async (req, res, next) => { 70 | const resetPasswordToken = crypto 71 | .createHash('sha256') 72 | .update(req.params.resetToken) 73 | .digest('hex'); 74 | try { 75 | const user = await User.findOne({ 76 | resetPasswordToken, 77 | resetPasswordExpire: { $gt: Date.now() }, 78 | }); 79 | if (!user) { 80 | return next(new ErrorResponse('Invalid reset token', 400)); 81 | } 82 | user.password = req.body.password; 83 | user.resetPasswordToken = undefined; 84 | user.resetPasswordExpire = undefined; 85 | await user.save(); 86 | res.status(201).json({ 87 | success: true, 88 | data: 'Password reset success', 89 | }); 90 | } catch (error) { 91 | next(error); 92 | } 93 | }; 94 | 95 | const sendToken = (user, statusCode, res) => { 96 | const token = user.getSignedToken(); 97 | res.status(statusCode).json({ success: true, token }); 98 | }; 99 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | 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. 37 | 38 | 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. 39 | 40 | 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. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /client/src/components/screens/RegisterScreen.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from 'react'; 2 | import { Link } from 'react-router-dom'; 3 | import axios from 'axios'; 4 | import './RegisterScreen.css'; 5 | 6 | const RegisterScreen = ({ history }) => { 7 | const [username, setUsername] = useState(''); 8 | const [email, setEmail] = useState(''); 9 | const [password, setPassword] = useState(''); 10 | const [confirmPassword, setConfirmPassword] = useState(''); 11 | const [error, setError] = useState(''); 12 | 13 | useEffect(() => { 14 | if (localStorage.getItem('authToken')) { 15 | history.push('/'); 16 | } 17 | }, [history]); 18 | 19 | const registerHandler = async (e) => { 20 | e.preventDefault(); 21 | const config = { 22 | headers: { 23 | 'content-type': 'application/json', 24 | }, 25 | }; 26 | if (password !== confirmPassword) { 27 | setPassword(''); 28 | setConfirmPassword(''); 29 | setTimeout(() => { 30 | setError(''); 31 | }, 5000); 32 | return setError('Passwords do not match'); 33 | } 34 | try { 35 | const { data } = await axios.post( 36 | 'http://localhost:5000/api/auth/register', 37 | { username, email, password }, 38 | config 39 | ); 40 | localStorage.setItem('authToken', data.token); 41 | history.push('/'); 42 | } catch (error) { 43 | setError(error.response.data.error); 44 | setTimeout(() => { 45 | setError(''); 46 | }, 5000); 47 | } 48 | }; 49 | return ( 50 |
51 |
52 |

Register

53 | {error && {error}} 54 |
55 | 56 | setUsername(e.target.value)} 63 | required 64 | /> 65 |
66 |
67 | 68 | setEmail(e.target.value)} 75 | required 76 | /> 77 |
78 |
79 | 80 | setPassword(e.target.value)} 87 | required 88 | /> 89 |
90 |
91 | 92 | setConfirmPassword(e.target.value)} 99 | required 100 | /> 101 |
102 | 105 | 106 | Already have an account?Login 107 | 108 |
109 |
110 | ); 111 | }; 112 | 113 | export default RegisterScreen; 114 | -------------------------------------------------------------------------------- /Resources/blueskeinstar-5de7e7.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | Star–Shaped Skein, by Adam Stanislav 22 | 23 | 24 | 25 | --------------------------------------------------------------------------------