Skip to content
This repository has been archived by the owner on Jul 18, 2022. It is now read-only.

Commit

Permalink
Feat📌: Created user registeration & login routes🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
omzi committed Oct 15, 2020
1 parent 9858ef2 commit bbfa212
Show file tree
Hide file tree
Showing 6 changed files with 234 additions and 0 deletions.
58 changes: 58 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const ErrorResponse = require('../utils/errorResponse');
const asyncHandler = require('../middleware/async');
const User = require('../models/User');

/**
* @desc Register user
* @route POST /api/v1/auth/register
* @access Public
*/
exports.register = asyncHandler(async (req, res, next) => {
const { name, email, password, role } = req.body;

// Create user
const user = await User.create({ name, email, password, role });

sendTokenCookieResponse(user, 200, res)
})

/**
* @desc Log user in
* @route POST /api/v1/auth/login
* @access Public
*/
exports.login = asyncHandler(async (req, res, next) => {
const { email, password } = req.body;

if (!email || !password) {
return next(new ErrorResponse('Please enter an email address & a password'))
}

const user = await User.findOne({ email }).select('+password');

if (!user) return next(new ErrorResponse('Invalid credentials'), 401);

// Check if password matches
const isMatch = await user.comparePassword(password);

if (!isMatch) return next(new ErrorResponse('Invalid credentials'), 401);

sendTokenCookieResponse(user, 200, res)
})

const sendTokenCookieResponse = (user, statusCode, res) => {
// Create token
const token = user.getSignedToken();

const options = {
expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000),
httpOnly: true
}

if (process.env.NODE_ENV === 'production') options.secure = true

res
.status(statusCode)
.cookie('token', token, options)
.json({ success: true, token });
}
56 changes: 56 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const UserSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name']
},
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
match: [
/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/i,
'Please enter a valid email'
]
},
role: {
type: String,
enum: ['user'],
default: 'user'
},
password: {
type: String,
required: [true, 'Please add a password'],
minlength: 6,
select: false
},
resetPasswordToken: String,
resetPasswordExpiration: Date,
createdAt: {
type: Date,
default: Date.now()
}
})

// Encrypt password using bcrypt
UserSchema.pre('save', async function(next) {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
})

// Sign JSON web token & return
UserSchema.methods.getSignedToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE
})
}

// Match user entered password to hashed password
UserSchema.methods.comparePassword = async function(enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password)
}

module.exports = mongoose.model('User', UserSchema);
105 changes: 105 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@
},
"homepage": "https://github.com/omzi/madam-sauce#readme",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-fileupload": "^1.2.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.9",
"slugify": "^1.4.5"
},
Expand Down
7 changes: 7 additions & 0 deletions routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const router = require('express').Router();
const { register, login } = require('../controllers/auth');

router.post('/register', register);
router.post('/login', login);

module.exports = router;
5 changes: 5 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ const dotenv = require('dotenv');
const morgan = require('morgan');
const colors = require('colors');
const fileUpload = require('express-fileupload');
const cookieParser = require('cookie-parser');
const errorHandler = require('./middleware/error');
const db = require('./config/db');

// Load route files
const foods = require('./routes/foods');
const auth = require('./routes/auth');

// Load env variables
dotenv.config({ path: './config/.env' })
Expand All @@ -18,6 +20,7 @@ db()

const app = express();
app.use(express.json());
app.use(cookieParser());

// Dev logging middleware
if (process.env.NODE_ENV === 'development') app.use(morgan('dev'))
Expand All @@ -27,6 +30,8 @@ app.use(express.static(path.join(__dirname, 'public')));

// Mount routers
app.use('/api/v1/foods', foods);
app.use('/api/v1/auth', auth);

app.use(errorHandler);

const PORT = process.env.PORT || 5050
Expand Down

0 comments on commit bbfa212

Please sign in to comment.