Let's say I have myWebsite.com and myWebsite.com/login
I have a route for the index page and a route for the login page.
I am working on another feature now, which will take an id such as myWebsite.com/t9wfhash
If there is such id, I will query the DB with it for something.
I tried something like
/* GET index page. */
router.get('/:urlId', function (req, res) {
if ( req.params.urlId !== 'undefined' ) {
console.log(req.params.urlId);
var urlId = req.params.urlId;
}
if (req.isAuthenticated()) {
res.redirect('/dashboard');
}
res.render('index', { title: urlId });
});
However, the login page doesn't work anymore when taking an id from the index page (:urlId) -- if I go to my login page it just console logs "login", of course.
So how can I make it so if someone goes to one of my routes (IE login page), then it's not considered like an ID.
Any ideas appreciated.
As long as you register the login route before the urlId route, a request for /login will trigger your login route instead of the urlId route:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.get('/login', function(req, res){
res.send('this is the login page');
});
app.get('/:urlId', function(req, res){
res.send( req.params.urlId );
});
app.listen(3005);
// http://localhost:3005/login will return "this is the login page"
// http://localhost:3005/22 will return 22
Related
I want to create a login page, such that when the user successfully logs in the app goes to the URL localhost:3000/:username. So for instance when a person with username johnlogs in the app should go to localhost:3000/john. I read this page on express routing https://expressjs.com/en/guide/routing.html but it does not seem to explain this. It only explains how to get the username from the URL but not the other way around (how to route to a different URL depending on the username). Any hints would be appreciated.
You can use redirection after the user login successfully.
var express = require('express');
var app = express();
// login page
app.get('/login', function (req, res) {
res.send(`This is login page`);
});
// login verification
app.post('/login', function (req, res) {
// verify user
const user = getUserByEmailAndPassword(req.body.email, req.body.password);
// set session
// ...
// redirect
res.redirect(`/${user.username}`);
});
// private user page
app.get('/:username', function (req, res) {
const username = req.params.username;
res.send(`Hello ${username}`);
});
I'm using PassportJS for handle the access to my application, suppose that the user has logged in, and suppose that these urls:
Login
Register
Welcome
need to redirect the user on dashboard url, only if the user has logged in, how can I do?
This is my authentication middleware:
module.exports = {
ensureAuthenticated: function(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.render('index/forbidden');
}
};
Example:
User go to login
No session
Stay on the page
(already works)
User go to login
Already logged in
Redirect to dashboard
You can create another middleware to redirect if logged in and add it to the routes that don't need login. You are basically doing the opposite.
module.exports = {
ensureAuthenticated: function(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.render('index/forbidden');
},
ensureNOTAuthenticated: function(req, res, next){
if(req.isAuthenticated()){
return res.redirect('/dashboard')
}
return next();
}
};
For routes that need auth:
app.get('/dashboard', ensureAuthenticated, (req,res)=>{...});
For routes that dob't need auth:
app.get('/login', ensureNOTAuthenticated, (req,res)=>{...});
I am stucked with one problem. As you can guess from title , problem is that i am making redirect loop . Simple situation but as a beginner i couldn't solve it . I will provide my code for you to see the problem.
So this is my express routers `
const passport = require('passport');
module.exports = (app) => {
app.get('/auth/eventbrite',
passport.authenticate('eventbrite', {}));
app.get('/auth/eventbrite/callback',
passport.authenticate('eventbrite', { failureRedirect: '/' }),
(req, res) => {
if (!req.user) {
throw new Error('user null');
}
res.redirect('/dashboard');
});
app.get('/api/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
});
app.get('/api/current_user', (req, res) => {
res.send(req.user);
});
app.get('/dashboard', (req, res) => {
console.log(req.user, 'user');
if (!req.user) {
res.redirect('/');
} else {
res.redirect('/dashboard');
}
});
};
You can notice that i redirect user to /dashboard both in passport authentication and for get requests . My goal is to prevent user to come to dashboard if he/she is not authenticated .
If the user is logged in and is redirected to the dashboard, the dashboard redirects him again to the dashboard. This creates an endless loop. Instead, if the user is logged in, the dashboard route should respond. Most probably you want to send him the dashboard html page.
I'm confused by this. Why can I see this at the url http://localhost:1337/admin/hello/holly but not at the url http://localhost:1337/admin/users/holly? It's sending text right? the res.send (sending 'hello' to the page). But surely the adminRouter.get should be pulling the 2nd url (with the word 'users' in the path) ? It's basically doing the opposite of what I 'm expecting it to do.
Here's the code snippet.
// route with parameters (http://localhost:1337/admin/users/:name)
adminRouter.get('/users/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
** edit: Here's the whole code with the other routes:
// load the express package and create our app
var express = require('express');
var app = express();
// send our index.html file to the user for the home page
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// get an instance of the router
var adminRouter = express.Router();
// route middleware that will happen on every request
adminRouter.use(function(req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
// route middleware to validate :name
adminRouter.param('name', function(req, res, next, name) {
// do validation on name here
// blah blah validation
// log something so we know its working
console.log('doing name validations on ' + name);
// once validation is done save the new item in the req
req.name = name;
// go to the next thing
next();
});
// route with parameters (http://localhost:1337/admin/users/:name)
adminRouter.get('/users/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
// create routes for the admin section
// admin main page. the dashboard
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
// users page
adminRouter.get('/users', function(req, res) {
res.send('I show all the users!');
});
// posts page
adminRouter.get('/posts', function(req, res) {
res.send('I show all the posts!');
});
// apply the routes to our application
app.use('/admin', adminRouter);
// start the server
app.listen(1337);
console.log('1337 is the magic port!');
So the answer to this one was to just manually restart my server and the problem corrected itself.
Why it had gotten itself in a twist and was doing the reverse of what it should have been doing who knows, but on restarting the server it worked correctly.
Currently using node.js, express & passport.js to create a custom website/application.
Having followed several guides, I have a functioning login/logout system with authentication. However, should a user revisit and their session is still active, it doesn't redirect them to the 'dashboard'.
Current root route:
/* GET login page. */
router.get('/',function(req, res) {
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
});
I am making use of the isAuthenticated function, as below:
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
How do I get it to automatically redirect users with an existing session? Any pointers most welcome!
Ok, I figured it out. In the / route, I queried whether req.user was set.
/* GET login page. */
router.get('/',function(req, res) {
if(req.user){
res.redirect("/dashboard");
}else{
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
}
});
You can attach a middleware with "/" endpoint something like this.
router.get('/', sessionValidate, function(req, res, next) {
res.render('login');
});
Where sessionValidate looks something like this :
function sessionValidate(req,res,next){
console.log(req.user,"i am here");
users.findById(req.user,function(err, user) {
if(user!=null){
req.session.user = user;
res.locals.user=user;
res.redirect("/home")
}
else {
next();
}
});
}