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

Commit

Permalink
Create POST /auth/login and user route permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
akhilome committed Sep 30, 2018
1 parent f82ef0a commit aa028dd
Show file tree
Hide file tree
Showing 6 changed files with 202 additions and 2 deletions.
93 changes: 91 additions & 2 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -25,6 +25,7 @@
"body-parser": "^1.18.3",
"dotenv": "^6.0.0",
"express": "^4.16.3",
"jsonwebtoken": "^8.3.0",
"pg": "^7.4.3"
},
"devDependencies": {
Expand Down
34 changes: 34 additions & 0 deletions server/controllers/Auth.js
Expand Up @@ -28,6 +28,40 @@ class AuthController {
return res.status(400).json();
}
}

static async signin(req, res, next) {
const { email, password } = req;

try {
// Check if a user with the provided email exists
const userExists = (await pool.query('SELECT * FROM users WHERE email=$1', [email])).rowCount;
if (!userExists) {
return res.status(400).json({
status: 'error',
message: 'no user with that email exists',
});
}

const userDetails = (await pool.query('SELECT * FROM users WHERE email=$1', [email])).rows[0];
const correctPassword = await bcrpyt.compare(password, userDetails.password);

if (!correctPassword) {
return res.status(400).json({
status: 'error',
message: 'incorrect password',
});
}

// Append important payload to request object
req.userId = userDetails.id;
req.userName = userDetails.name;
req.userEmail = userDetails.email;
req.userStatus = userDetails.is_admin ? 'admin' : 'customer';
return next();
} catch (error) {
return res.status(400).json();
}
}
}

export default AuthController;
59 changes: 59 additions & 0 deletions server/middleware/AuthHandler.js
@@ -0,0 +1,59 @@
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config();

class AuthHandler {
static async generateAuthToken(req, res) {
const {
userId,
userName,
userEmail,
userStatus,
} = req;

const token = jwt.sign({
userId,
userName,
userEmail,
userStatus,
}, process.env.JWT_SECRET);

res.status(200).json({
status: 'success',
message: 'user logged in successfully',
auth_token: token,
});
}

static authenticate(req, res, next) {
const token = req.header('x-auth');

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
req.userName = decoded.userName;
req.userEmail = decoded.userEmail;
req.userStatus = decoded.userStatus;
return next();
} catch (error) {
return res.status(401).json({
status: 'error',
message: 'you must be logged in to use this route',
});
}
}

static authenticateAdmin(req, res, next) {
if (req.userStatus !== 'admin') {
return res.status(401).json({
status: 'error',
message: 'only admins can use this route',
});
}

return next();
}
}

export default AuthHandler;
15 changes: 15 additions & 0 deletions server/middleware/Sanitizer.js
Expand Up @@ -38,6 +38,21 @@ class Sanitize {
req.password = password.trim();
return next();
}

static signin(req, res, next) {
const { email, password } = req.body;

if (!Validator.isEmail(email) || !Validator.isValidPassword(password)) {
return res.status(400).json({
status: 'error',
message: 'email or password not correctly password',
});
}

req.email = email.trim();
req.password = password.trim();
return next();
}
}

export default Sanitize;
2 changes: 2 additions & 0 deletions server/routes/authRouter.js
@@ -1,9 +1,11 @@
import { Router } from 'express';
import AuthController from '../controllers/Auth';
import Sanitize from '../middleware/Sanitizer';
import AuthHandler from '../middleware/AuthHandler';

const router = new Router();

router.post('/signup', Sanitize.signup, AuthController.signup);
router.post('/login', Sanitize.signin, AuthController.signin, AuthHandler.generateAuthToken);

export default router;

0 comments on commit aa028dd

Please sign in to comment.