0
votes

i am using passport with google strategy for authentication

my folder structure:

  • views
    • home.html
    • enter.html (this has just one google+ button)
  • app.js
  • routes
    • auth.js (for google login)

i want the client to be directed to enter.html and not be able to use home.html if req.user is not set ( req.user is set when user is authenticated using google )

once authentication is done user should be redirected to home.html

app.use(express.static()) makes both of them available which is not what i want

the google login page comes by auth/google

and i also need to know what i should keep as the callback uri

in app.js

  1. i have done mongodb configuration

  2. i have done passport configuration

what to do next?

in auth.js

const router = require('express').Router();
const passport = require('passport');
router.route('/google')
    .get(passport.authenticate('google', { scope: ["profile"] }));
router.route('/google/redirect')
    .get(passport.authenticate('google'), (req, res, next) => {
        // res.redirect what
    });
module.exports = router;
1

1 Answers

1
votes

To serve the home.html page you could redirect to a protected home route. Here an example of how I would go about implementing this.

auth.js

router.route('/google/redirect')
    .get(passport.authenticate('google', { failureRedirect: '/' }), (req, res, next) => {
        // Set to redirect to your home route / html page
        res.redirect('/home')
    });
    

To prevent users from going to home without authorization, you should also add a route guard to your /home route.

routes.js

const { checkAuth } = require('./guards'); // Protected routes 
router.get('/home', checkAuth, async (req, res) => {
  res.render('home')
});

guards.js

module.exports = {
  checkAuth(req, res, next) {
    if (req.isAuthenticated()) {
      return next()
    } else {
      res.redirect('/')
    }
  },
}