Aarav
Aarav

Reputation: 111

How to get user page in passport

I am making very simple user login system. Every users have their own page (username.html) . Once users login in a system they should get own pages. Here I used passportjs and my code is

var express = require('express');
var router = express.Router();


var isAuthenticated = function (req, res, next) {
            // request and response objects
    if (req.isAuthenticated())
        return next();
    // not authenticated then redirect to the login page
    res.redirect('/');
}

router.post('/login',
        passport.authenticate('login', {failureRedirect: '/'}),
         function(req, res) {
    // If this function gets called, authentication was successful.

         res.redirect(req.user.username);
         });

/*  GET user Page  */

    router.get('/user.username', isAuthenticated, function(req, res){

        res.render('user.username', { user: req.user });

I stuck in getting user page. Do you have any suggestion how I can get '/user.username' page in router.get?. Thank you very much for your help.

Upvotes: 0

Views: 281

Answers (1)

suraj
suraj

Reputation: 141

There is a problem in the way you are trying to pass parameters to the express get route. The query parameters to be received must be specified after a :. For e.g.

app.get('/api/:version', function(req, res) {
    res.send(req.params.version);
  });

This code snippet will recognize routes like /api/1 , /api/2 etc. Here version is the parameter to be received. The parameter's value can be accessed by using req.param.

So here, we need to redirect the user to his page after successful login.This can be done by creating a route as "/:username" which will accept username as a parameter and renders the user's page.

Now for e.g. if the user logs in as 'aarav' then he will be redirected to \aarav which will be handled by the get route, thus rendering the appropriate page whose value is given by req.params.username.

Here goes the modified code :

var express = require('express');
var router = express.Router();


var isAuthenticated = function (req, res, next) {
            // request and response objects
    if (req.isAuthenticated())
        return next();
    // not authenticated then redirect to the login page
    res.redirect('/');
}

router.post('/login',
        passport.authenticate('login', {failureRedirect: '/'}),
         function(req, res) {
    // If this function gets called, authentication was successful.

         res.redirect('/'+req.user.username);
         });

/*  GET user Page  */

    router.get('/:username', isAuthenticated, function(req, res){

        res.render(req.params.username, { user: req.user });

Hope it helps :)

Upvotes: 3

Related Questions