Skip to content

Commit

Permalink
Merge branch 'release/v0.0.2'
Browse files Browse the repository at this point in the history
  • Loading branch information
thomas367 committed Mar 15, 2020
2 parents 83a7158 + a5cc2ac commit 0dcb322
Show file tree
Hide file tree
Showing 9 changed files with 159 additions and 19 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/node_modules

package-lock.json
default.json
.env
10 changes: 5 additions & 5 deletions config/dbConnection.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const dotenv = require('dotenv').config();

const connectDB = async () => {
try {
await mongoose.connect(db, {
await mongoose.connect(process.env.mongoURI, {
useUnifiedTopology: true,
useNewUrlParser: true
useNewUrlParser: true,
useCreateIndex: true
});

console.log('Mongo connected...')
} catch (err) {
console.log(err.message);
Expand Down
88 changes: 88 additions & 0 deletions controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv').config();

const User = require('../models/User');

exports.register = async (req, res) => {
const {name, email, password } = req.body;

try {
let user = await User.findOne({ email });

if (user) {
return res.status(400).json({ errors: [{ message: 'User already exists' }] });
}

const avatar = gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mm'
});

user = new User({ name, email, avatar, password });

const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);

await user.save();

const payload = {
user: {
id: user.id
}
}

jwt.sign(
payload,
process.env.jwtSecret,
{expiresIn: 36000},
(err, token) => {
if (err) throw err;
res.json({ token });
});


} catch(err) {
console.log(err.message);
res.status(500).send('Server error');
}
};

exports.login = async (req, res) => {
const {email, password } = req.body;

try {
let user = await User.findOne({ email });

if (!user) {
return res.status(400).json({ errors: [{ message: 'Invalid Credentials' }] });
}

const isMatched = await bcrypt.compare(password, user.password);

if (!isMatched) {
return res.status(400).json({ errors: [{ message: 'Invalid Credentials' }] });
}

const payload = {
user: {
id: user.id
}
}

jwt.sign(
payload,
process.env.jwtSecret,
{expiresIn: 36000},
(err, token) => {
if (err) throw err;
res.json({ token });
});

} catch(err) {
console.log(err.message);
res.status(500).send('Server error');
}
};
18 changes: 18 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv').config();

module.exports = (req, res, next) => {
const token = req.header('x-auth-token');

if (!token) {
return res.status(401).json({ message: 'No token, authorization denied' });
}

try {
const decoded = jwt.verify(token, process.env.jwtSecret);
req.user = decoded.user;
next();
} catch(err) {
res.status(401).json({ message: 'Token is not valid' });
}
}
29 changes: 29 additions & 0 deletions middleware/validations/authValidation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const { check, validationResult } = require('express-validator');

exports.login = [
check('email', 'Please include a valid email').isEmail(),
check('password', 'Password id required').exists(),

function(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
return next();
}
];

exports.register = [
check('name', 'Name is required').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check('password', 'Please enter a password with 6 or more characters').isLength({ min: 6 }),

function(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
return next();
}
];

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@
},
"homepage": "https://github.com/thomas367/nodeDemo#readme",
"dependencies": {
"config": "^3.3.0",
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.4.0",
"gravatar": "^1.8.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.4"
},
"devDependencies": {
Expand Down
9 changes: 0 additions & 9 deletions routes/api/users.js

This file was deleted.

9 changes: 9 additions & 0 deletions routes/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express');
const router = express.Router();
const authCtrl = require('../controllers/authController');
const validation = require('../middleware/validations/authValidation');

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

module.exports = router;
7 changes: 4 additions & 3 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
const express = require('express');
const connectDB = require('./config/dbConnection');
const routes = require('./routes/routes');

const app = express();

connectDB();

app.get('/', (req, res) => res.send('API running'));
app.use(express.json({ extended: false }));

//Access user route
app.use('/api/users', require('./routes/api/users'));
app.get('/', (req, res) => res.send('API running'));
app.use('/', routes);

const PORT = process.env.PORT || 5000;

Expand Down

0 comments on commit 0dcb322

Please sign in to comment.