I'm new to node js and i tried creating a simple login page. but when i run my code it takes me to the login page alright. the problem is when i enter a user name and password, it doesn't display the information it supposed to display.
var express = require('express');
var sessions = require('express-session');
var session;
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
secret: '2937#&&#',
resave: false,
saveUninitialized: true
}))
app.get('/login', function(req, resp){
session = req.session;
if(session.uniqueID){
resp.redirect('/redirects');
}
resp.sendFile('./files/login.html', {root: __dirname});
});
app.post('/login', function(req, resp){
// resp.end(JSON.stringify(req.body));
session = req.session;
if(session.uniqueID) {
resp.redirect('/redirects');
}
if(req.body.username == 'admin' && req.body.password == 'admin'){
session.uniqueID = req.body.username;
}
resp.redirect('/redirects');
});
app.get('/logout', function(req, resp){
req.session.destroy();
resp.redirect('/login');
});
app.get('/admin', function(req, resp){
session = req.session;
if(session.uniqueID != 'admin'){
resp.end('Unauthorised acess')
}
resp.end('You are good');
})
app.get('/redirects', function(req, resp){
session = req.session;
if(session.uniqueID =='admin') {
console.log(session.uniqueID)
resp.redirect('/admin');
} else {
resp.send(req.session.uniqueID + 'not found KILL SESSION');
}
})
app.listen(1337, function() {
console.log('Listening at port 1337');
});
Nothing happens because you can't redirect on an AJAX call. Your POST probably works, but then your redirect directive has no effect.
Try sending a "success" response if the username and password are good (a simple res.send('OK'); would do) and then on the client side redirect the user to /redirects (window.location.replace('https://yoursite.com/redirects')); if a success code is returned.
This will be handled by your GET route for /redirects and you should see what you want.
Related
I can't get the logout function to work correctly and remove the session from the mongodb.
I'm able to store the session. logout was initially req.session.destroy(); but that kept returning an error. (destroy undefined)
I'm pretty new to nodejs/javascript, I'm trying to learn my apologies in advance for any ignorance!
Any help would be appreciated!!
app.js
const express = require('express'), url = require('url');
const path = require('path');
const dotenv = require('dotenv');
const connectToDatabase = require('./src/db/mongoose');
const helmet = require('helmet');
const router = require('./src/routes/routes');
const openApiDocumentation = require('./src/swagger/openApiDocumentation');
const swaggerUi = require('swagger-ui-express');
const cors = require('cors');
const bodyParser = require("body-parser");
var app = express();
const session = require('express-session');
const MongoStore = require('connect-mongo');
const port = process.env.PORT || 3000;
dotenv.config();
connectToDatabase(); //This removed to simplify the connection
app.use(express.json());
app.use(express.static('src/css'));
app.use(express.static('src/js'));
app.use(express.static('scripts'));
app.use(express.static('controllers'));
app.use(express.static(__dirname + '/views'));
app.use(express.static("views"));
app.use('/', express.static(path.join(__dirname, 'views'),{extensions:['html']}));
app.use('/api', swaggerUi.serve, swaggerUi.setup(openApiDocumentation));
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
app.use("/v1/login", session({
name: 'auth',
secret: 'mykey',
httpOnly: true,
secure: true,
maxAge: 1000 * 60 * 60 * 7,
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: '<redacted>'
})
}));
app.get('/name', (req, res) => {
let name;
if (!req.session) {
return res.status(404).send();
}
name = req.session.user.name;
return res.status(200).send({name});
})
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
router.get("/vl/login", function(req, res) {
if (
typeof reqsession.user != "object" || (
typeof req.session.user.name == "undefined" &&
typeof req.session.user.password == "undefined")
) {
res.render("pages/index");
}
res.redirect("Login");
});
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(helmet());
app.use('/v1', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(port, () => console.log(`Server is running on Port: ${port}`));
userController.js
login: async (req, res) => {
const { userName, password } = req.body
const user = await userModel.findOne({ userName }).lean()
if (!user) {
return res.json({ status: 'error', error: 'Invalid username/password' })
}
if (await bcrypt.compare(password, user.password)) {
// the username, password combination is successful
const token = jwt.sign(
{
id: userModel._id,
userName: userModel.userName
},
JWT_SECRET
)
const { name } = req.body;
req.session.user = {
name,
isLoggedIn: true
}
try {
await req.session.save();
} catch (err) {
console.error('Error saving to session storage: ', err);
return next(new Error('Error creating user'));
}
return res.json({ status: 'ok', data: token })
}
res.json({ status: 'error', error: 'Invalid username/password' })
},
logout: async (req, res, next) => {
try {
await await req.session == null;
} catch (err) {
console.error('Error logging out:', err);
return next(new Error('Error logging out'));
}
return res.json({ status: 'ok'})
},
routes.js
const express = require('express');
const router = express.Router();
const newUser = require('../controllers/userController');
const company = require('../controllers/companyController');
const upload = require('../controllers/upload');
const auth = require('../middleware/auth');
/* GET response for '/'/*
router.get('/', (req, res) => {
res.redirect('/');
}) */
//generate token
router.get('/token', newUser.generateToken);
//login
router.post('/login', newUser.login);
//logout
router.post('/logout', newUser.logout);
//create service user
router.post('/addServiceUser', newUser.addServiceUser);
//Add user
router.post('/users', newUser.addUser);
//remove user
router.delete('/users/:id',auth, newUser.removeUser);
//Get All users
router.get('/users',auth, newUser.getAllUsers);
//Get User
router.get('/user/:id',auth, newUser.getUser);
//Get first name
router.get('/users/:id/firstName',auth, newUser.getUserFirstName);
//Set first name
router.put('/users/:id/firstName',auth, newUser.setUserFirstName);
//Get last name
router.get('/users/:id/lastName',auth, newUser.getUserLastName);
//Set last name
router.put('/users/:id/lastName',auth, newUser.setUserLastName);
//Get user email
router.get('/users/:id/email',auth, newUser.getUserEmail);
//set user email
router.put('/users/:id/email',auth, newUser.setUserEmail);
//Get user phone
router.get('/users/:id/phone',auth, newUser.getUserPhone);
//set user phone
router.put('/users/:id/phone',auth, newUser.setUserPhone);
//get user age
router.get('/users/:id/age',auth, newUser.getUserAge);
//set user age
router.put('/users/:id/age',auth, newUser.setUserAge);
//set user status
router.put('/users/:id/status',auth, newUser.setUserStatus);
//get user status
router.get('/users/:id/status',auth, newUser.getUserStatus);
//set user level
router.put('/users/:id/level',auth, newUser.setUserLevel);
//get user level
router.get('/users/:id/level',auth, newUser.getUserLevel);
//get user gender
router.get('/users/:id/gender',auth, newUser.getUserGender);
//set user gender
router.put('/users/:id/gender',auth, newUser.setUserGender);
//set user address
router.put('/users/:id/address',auth, newUser.setUserAddress);
//get user address
router.get('/users/:id/address',auth, newUser.getUserAddress);
//get active users
router.get('/users/status/active',auth, newUser.getActiveUsers);
//get inactive users
router.get('/users/status/inactive',auth, newUser.getInActiveUsers);
//get non admin users
router.get('/users/level/intern',auth, newUser.getInternUsers);
//get mentor users
router.get('/users/level/mentor',auth, newUser.getMentorUsers);
//Get Avatar
router.get('/users/:id/avatar',auth, newUser.getUserAvatar);
//Set Avatar
router.put('/users/:id/avatar',auth, upload.single('avatar'), newUser.setUserAvatar);
//Delete Avatar
router.delete('/users/:id/avatar',auth, newUser.removeUserAvatar);
//Add Companies
router.post('/companies/:id/team', auth, company.setUserTeamName);
module.exports= router;
It looks like in your logout function, the way your attempting to "logout" the user is setting req.session to null.
As you've figured out this doesn't act how you've expected. The correct way to logout a user would be calling req.session.destroy() usually accompanied by a redirect back to the login page:
return res.redirect("/login");
This will completely remove or, destroy the session and log the user out.
I've watched a video on YouTube about Authentication on NodeJS. I already have a project just with get requisitions. That's the code that involves the login:
var sessions = require('express-session');
var session = {};
app.use(bodyParser.urlencoded({ extended: true }));
app.use(sessions({
secret: 'aisdh2782782hjda82',
resave: false,
saveUninitialized: true
}))
Methods
app.get('/login', function(req, res) {
session = req.session;
if(session.uniqueId) {
resp.redirect('/redirects');
}
})
app.post('/login', function(req,res) {
session = req.session;
if(req.body.username == 'admin' && req.body.password == 'admin'){
session.uniqueiD = req.body.username;
}
resp.redirect('/redirects');
});
app.post('/logout', function(req,res) {
req.session.destroy();
});
app.get('/redirects', function(req, res) {
session = req.session;
if(session.uniqueiD) {
resp.redirect('/home');
} else {
end('Wrong. Try it again');
}
});
Tests
I'm testing the source with postman. For instance I've tried using post login method passing as parameter this JSON:
{
"username": "admin",
"password": "admin"
}
Then I got this:
resp is not defined
May someone help me? I have limited knowledge of node and I don't really know what's wrong in my code (I just copied). Obs: I'll use mysql to fetch user data.
I haven't yet implemented your code myself, but it comes to my eye that you pass in the parameters (req, res) and refer to the later with "resp" instead of "res". It might just be a simple typo.
Also you don't handle a correct login diffrent from an incorrect one. Implement an "else {}" case after you ceck for successful login.
I have some problems with the express session where I cannot retrieve my session variable that I had stored previously. Below are parts of my codes that I had written.
server.js
let express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
config = require('./config/database'),
expressSession = require('express-session'),
uid = require('uid-safe'),
db;
let app = express();
//Import Routes
let auth = require('./routes/auth'),
chimerListing = require('./routes/chimer-listing'),
brandListing = require('./routes/brand-listing');
//Specifies the port number
let port = process.env.PORT || 3000;
// let port = 3000;
// Express session
app.use(expressSession({
secret: "asdasd",
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
secure: false
}
}));
//CORS Middleware
app.use(cors());
//Set Static Folder
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));
//Body Parser Middleware
app.use(bodyParser.json());
//MongoDB
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.database, (err, database) => {
if (err) return console.log(err)
db = database;
//Start the server only the connection to database is successful
app.listen(port, () => {
console.log('Server started on port' + port);
});
});
//Make db accessbile to routers;
app.use(function(req, res, next) {
req.db = db;
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//Routes
app.use('/login', auth);
app.use('/user-listing', userListing);
app.use('/brand-listing', brandListing);
//Index Route
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
genuuid = function() {
return uid.sync(18);
};
auth.js
let express = require('express'),
router = express.Router(),
db;
//Login Router for chimer
router.post('/chimer', (req, res, next) => {
db = req.db;
// let client = req.client;
db.collection('chimeUser').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
//If there is such user
if (docs.length >= 1) {
req.session.chimerId = docs[0]._id;
console.log(req.session);
req.session.save(function(err) {
// session saved
if (err)
console.log(err)
res.json({
success: true,
chimerId: docs[0]._id
//objects: docs
});
})
} else {
res.json({
success: false,
//objects: docs
})
}
});
});
//Login Router brand
router.post('/brand', (req, res, next) => {
db = req.db;
db.collection('brand').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
req.session.brand = docs;
console.log(req.session.brand);
//If there is such user
if (docs.length >= 1) {
res.json({
success: true,
//objects: docs
})
} else {
res.json({
success: false,
//objects: docs
})
}
//db.close()
});
});
});
module.exports = router;
user-listing.js
let express = require('express'),
moment = require('moment'),
router = express.Router(),
// ObjectID = require('mongodb').ObjectID,
db, client;
// let applyListing = require('../models/chimer-listing');
//Retrieve All Listing
router.get('/getAllListing', (req, res, next) => {
db = req.db;
console.log(req.session)
db.collection('listing').find().toArray().then(function(listing) {
//If there is any listing
if (listing.length >= 1) {
res.json({
success: true,
results: listing
})
} else {
res.json({
success: false,
})
}
//db.close()
});
});
module.exports = router;
So in my server.js, I have three routes file which is auth, user-listing, and brand-listing.
Firstly, a user will need to login with the web application which is developed in angular2 and this will trigger the auth route. It will then check for the credentials whether does it exist in the database if it exists I will then assign an ID to req.session.chimerId so that in other routes I will be able to use this chimerId.
Next, after the user has logged in, they will then retrieve an item listing. The problem arises where I can't seem to retrieve the req.session.chimerId that I had previously saved. It will be undefined
NOTE: I tried this using Postman and the browser. In the Postman it works, I am able to retrieve back the req.session.chimerId whereas when I use the angular2 application to hit the endpoints req.session.chimerId is always null
This is a resume about an authentication method.
I tried to use express.basicAuth, but it forces the browser to ask for user and pass, and I need to use my own login page, like google, facebook yahoo...
Is this right? Is there any better way to do this?
I want to avoid modules, like passport, if I can.
I want to use a function like this, using auth middleware (app.get('/loggedin', auth, function(req, res)...)
var express = require('express');
var app = express();
app.use(express.cookieParser());
var RedisStore = require('connect-redis')(express);
app.use(express.session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
pass: 'RedisPASS'
}), secret: '1234567890QWERTY'
}));
var auth = function(req, res, next) {
if (req.session.authStatus === 'loggedIn')
next();
else
res.redirect('/login');
};
app.get('/', function(req, res) {
console.log("/");
res.send('not authenticate');
});
app.get('/signin', function(req, res) {
console.log("/signin");
if (req.body.user && req.body.pass)
{
req.user = req.body.user;
req.remoteUser = req.body.user;
req.session.authStatus = 'loggedIn';
req.session.lastPage = '/signin';
res.redirect('/loggedin');
}
else
res.redirect('/login');
});
app.get('/loggedin', auth, function(req, res) {
if(req.session.lastPage) {
res.write('Last page was: ' + req.session.lastPage + '. ');
}
req.session.lastPage = '/loggedin';
res.write('Yeeeeeeeeeee');
res.end();
});
app.get('/loggedin2', auth, function(req, res) {
console.log("/loggedin2");
if(req.session.lastPage) {
res.write('Last page was: ' + req.session.lastPage + '. ');
}
req.session.lastPage = '/loggedin2';
res.write('WoWWWWW!!!!!!');
res.end();
});
app.get('/logout', auth, function(req, res) {
console.log("/logout");
req.session.destroy();
});
app.get('/login', function(req, res) {
console.log("/notlogged");
res.send('enter user and pass...');
});
app.listen(process.env.PORT || 8080);
You could use the passport middleware module in npm — the passport-local module provides authentication against a local resource such as a database.
I am new to the node.js world. I am trying to write a REST services and I am stuck with session management. So I created a separate app just to see if I can get the session to work, but it doesn't, here is the code. The req.session.username is always undefined:
var express = require('express');
var url = require('url');
var app = express()
app.use(express.cookieParser('Hiren'))
app.use(express.session({ secret: 'HirenAdesara' }))
app.use(express.bodyParser())
app.use(app.router)
//Sniff HTTP
app.all('*', function(req, res, next) {
//Check for Authentication
console.log(req.session)
if ((!(/^\/auth/g.test(req.url))) && (!req.session)) {
console.log('in app.all: Unauthorized')
res.send(401)
}
else
{
return next()
}
})
app.post('/auth', function(req, res) {
var query = req.body
console.log('Query' + JSON.stringify(query))
username = query.username;
password = query.password;
if(username == 'Hiren' && password == 'Adesara')
{
req.session.username = 'Hiren';
console.log('New Session Created..')
res.send(200)
}
else
{
console.log('New session could not be created.')
res.send(401)
}
})
app.get('/projects', function(req,res) {
console.log('inside projects' + req.session.username);
res.send(req.session.username); })
app.listen(2048)
console.log('Listening on port 2048...')
It doesn't work and I have no idea what is wrong here.
Star by moving the 3 lines in your app.get('/'...) outside of it:
var express = require('express');
var querystring = require('querystring');
var app = express()
app.use(express.cookieParser('Hiren')); // This line
app.use(express.session({ secret: 'HirenAdesara' })); // This line
app.use(express.bodyParser()); // This line
app.get('/', function(req, res){
res.send('hello from the root page');
})
// the rest of your code