Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google Auth added to strategy #269

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ SMTP_PORT=587
SMTP_USERNAME=email-server-username
SMTP_PASSWORD=email-server-password
EMAIL_FROM=support@yourapp.com

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_CALLBACK_URL=
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"express": "^4.17.1",
"express-mongo-sanitize": "^2.0.0",
"express-rate-limit": "^5.0.0",
"google-auth-library": "^8.7.0",
"helmet": "^4.1.0",
"http-status": "^1.4.0",
"joi": "^17.3.0",
Expand All @@ -66,6 +67,7 @@
"morgan": "^1.9.1",
"nodemailer": "^6.3.1",
"passport": "^0.4.0",
"passport-google-oauth20": "^2.0.0",
"passport-jwt": "^4.0.0",
"pm2": "^5.1.0",
"swagger-jsdoc": "^6.0.8",
Expand Down
34 changes: 34 additions & 0 deletions src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const httpStatus = require('http-status');
const { OAuth2Client } = require('google-auth-library');
const catchAsync = require('../utils/catchAsync');
const { authService, userService, tokenService, emailService } = require('../services');

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);

const register = catchAsync(async (req, res) => {
const user = await userService.createUser(req.body);
const tokens = await tokenService.generateAuthTokens(user);
Expand Down Expand Up @@ -46,7 +49,36 @@ const verifyEmail = catchAsync(async (req, res) => {
await authService.verifyEmail(req.query.token);
res.status(httpStatus.NO_CONTENT).send();
});
const googleAuth = async (req, res) => {
const tokens = await tokenService.generateAuthTokens(req.user);
res.status(httpStatus.OK).send(tokens);
};

const googleTokenAuth = async (req, res) => {
const { idToken } = req.body;

const ticket = await client.verifyIdToken({
idToken,
audience: process.env.GOOGLE_CLIENT_ID,
});

const payload = ticket.getPayload();
const googleId = payload.sub;
const { email } = payload;

let user = await userService.getUserByGoogleId(googleId);

if (!user) {
user = await userService.createUser({
name: payload.name,
email,
googleId,
});
}

const tokens = await tokenService.generateAuthTokens(user);
res.status(httpStatus.OK).send(tokens);
};
module.exports = {
register,
login,
Expand All @@ -56,4 +88,6 @@ module.exports = {
resetPassword,
sendVerificationEmail,
verifyEmail,
googleAuth,
googleTokenAuth,
};
18 changes: 10 additions & 8 deletions src/middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@ const verifyCallback = (req, resolve, reject, requiredRights) => async (err, use
if (requiredRights.length) {
const userRights = roleRights.get(user.role);
const hasRequiredRights = requiredRights.every((requiredRight) => userRights.includes(requiredRight));
if (!hasRequiredRights && req.params.userId !== user.id) {
if (!hasRequiredRights && req.params.userId !== user.id && req.body.userId !== user.id) {
return reject(new ApiError(httpStatus.FORBIDDEN, 'Forbidden'));
}
}

resolve();
};

const auth = (...requiredRights) => async (req, res, next) => {
return new Promise((resolve, reject) => {
passport.authenticate('jwt', { session: false }, verifyCallback(req, resolve, reject, requiredRights))(req, res, next);
})
.then(() => next())
.catch((err) => next(err));
};
const auth =
(...requiredRights) =>
async (req, res, next) => {
return new Promise((resolve, reject) => {
passport.authenticate('jwt', { session: false }, verifyCallback(req, resolve, reject, requiredRights))(req, res, next);
})
.then(() => next())
.catch((err) => next(err));
};

module.exports = auth;
2 changes: 2 additions & 0 deletions src/routes/v1/auth.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const express = require('express');
const validate = require('../../middlewares/validate');
const authValidation = require('../../validations/auth.validation');
const authController = require('../../controllers/auth.controller');

const auth = require('../../middlewares/auth');

const router = express.Router();
Expand All @@ -14,6 +15,7 @@ router.post('/forgot-password', validate(authValidation.forgotPassword), authCon
router.post('/reset-password', validate(authValidation.resetPassword), authController.resetPassword);
router.post('/send-verification-email', auth(), authController.sendVerificationEmail);
router.post('/verify-email', validate(authValidation.verifyEmail), authController.verifyEmail);
router.post('/google/token', authController.googleTokenAuth);

module.exports = router;

Expand Down