I am using express-session module in node.js for session management. I created session for login and getting session Id But, when I checked with postman it shows always same session Id for every login until until session destroy.
How can I create proper sessions with Id and how can I check whether session is live or not using session Id. Finally how to destroy the session with session using session Id.
what I tried is
var userLogin = function(req,callback){
var sess = req.session;
var data = req.body;
var query = "call userLogin(?,?)";
var table = [data.email,data.pass];
query = Repo.format(query,table);
Repo.execute(query,function(err,result){
if(err){
}else{
sess.email = data.email;
sess.pass = data.pass;
console.log("session ID is ",req.sessionID);
if(req.sessionID){
console.log("session is in");
}
else{
console.log("session is out");
}
sess.destroy();
console.log(req.sessionID);
if(req.sessionID){
console.log("aft session is in");
}
else{
console.log("aft session is out");
}
}
outPut(callback,err,result);
});
}
Thank you.
Related
I'm trying to upload my user's files to a bucket connected to their uid. So, in order to do it I try to grab their uid from the following code in my upload.js file:
const uploader = document.getElementById("uploader");
const fileButton = document.getElementById("fileButton");
fileButton.addEventListener('change', function(e)
{
// Get file
var file = e.target.files[0];
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
console.log("state = definitely signed in");
firebase.storage().ref('users').child(user.uid + "designs").put(file);
} else {
// No user is signed in.
console.log("state = definitely signed out");
}
});
});
Even after the user is logged in and the it directs them to the new page I always get informed that they aren't signed in. Should I use information from the session cookie instead? Any help would be appreciated!
After a few days I realised that I wasn't calling the id token correlated with the user that is logged in. This solved it:
firebase.auth().onAuthStateChanged(function(user)
{
if (user)
{
// User is signed in.
console.log(user);
user.getIdToken().then(function(idToken)
{ // <------ Check this line
console.log(idToken); // It shows the Firebase token now
});
console.log(user.uid);
firebase.storage().ref('users').child(user.uid + "/designs").put(file);
}
else
{
// No user is signed in.
console.log("state = definitely signed out");
}
});
I have a function authenticate of users in node js, and I'm not using an authentication, passport or other lib, I couldn't understand it well, so I did my own authentication function.
However, my function is only authentic for users, it does not create cookies, I need to create cookies on a "expiration date" node, and that as soon as it waits, it redirects me back to the login route. I want to implement this in this function:
function verify(req,res,username,password){
db.serialize(function (){
const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
db.all(query,[username, password],function(err,rows){
if(err) {
console.log(err);
}
if(rows.length == 1){
console.log(rows);
console.log("Correct user");
res.render(__dirname + "/View/Home/index.handlebars");
}
else{
console.log("Incorrecto user!")
res.redirect('/login')
}
});
});
}
This is my route in node js
app.get("/login", (req,res) => {
res.render(__dirname + "/View/Home/login.handlebars");
});
app.post("/",(req,res) => {
const username = req.body.username
const password = req.body.password
verify(req,res,username,password)
});
I need to create a cookie within the verify () function if the user is valid and when the cookie expires the user is redirected to the "/ login" route again
Assuming you're using Express server, you can set cookies using res.cookie(name, value, options). options is an object, and the maxAge property is probably what you want, which is a number is miliseconds before it expires. For example, if the user is valid you could do res.cookie('username', username, {maxAge: 172800000 /* two days */}).
You can access the request's cookies with req.cookies, which is an object of cookie name keys and string values. You can check if the 'username' key exists and is valid, and if not, redirect using res.redirect.
function verify(req,res,username,password){
// Place this block wherever you want it to check for a valid cookie
// Depending on the context when this function is called, that might not be at the start
if(typeof(req.cookies.username) != 'string')
res.redirect('/login');
db.serialize(function (){
const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'
db.all(query,[username, password],function(err,rows){
if(err) {
console.log(err);
}
if(rows.length == 1){
console.log(rows);
console.log("Correct user");
// Set Cookie
res.cookie('username', username, {maxAge: 172800000 /* two days */});
res.render(__dirname + "/View/Home/index.handlebars");
}
else{
console.log("Incorrecto user!")
res.redirect('/login')
}
});
});
}
Use Keycloak
Download
Offical Keycloak Download Page
Install For Linux/Unix
./bin/standalone.sh
** Install For Windows**
\bin\standalone.bat
Use arg -b to Bind network address (default is 127.0.0.1) like so
./bin/standalone.sh -b 192.168.1.150
Install Keycloak-nodejs-connect
npm install keycloak-connect
Official Node.js Example from Github
Reference: Getting Started Guide
I have an Express post route which updates a mongo db based on data sent to it from a DataTables Editor inline field. So far so good and the database is updating fine. Where it falls over is after the update query executes successfully and I want to then redirect back to the originating page. The Node console seems to indicate that the GET route to the originating page is being called, but the page itself doesn't load.
The code for the POST function is as follows:
router.post('/edit', function(req,res){
var theKeys = _.keys(req.body);
var theMeat = theKeys[1];
var bits1 = theMeat.split("][");
// this is the updated value
var newVal = req.body[theMeat];
// this is the row _id
var cleanId = bits1[0].replace("data[row_","");
// this is the field to update
var cleanRow = bits1[1].replace("]","");
// cast the id string back to an ObjectId
var updId = new ObjectId(cleanId);
var query = {};
query[cleanRow] = newVal;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/gts';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Error connecting to the server", err);
}else{
//console.log("Connected for Edit");
var collection = db.collection('events');
collection.updateOne({"_id":updId},{$set:query},function(err,result){
if(err){
console.log("Error adding message", err);
}else if(result){
//console.log("Update attempted", result.result);
res.redirect('/admin');
}else{
console.log("Unknown error");
}
});
}
});
});
The GET route works fine when called directly, but seems to halt when called like this.
I'm pretty sure that there's nothing in the POST route that is causing this as the same thing happens when I strip out everything except the redirect itself.
router.post('/test',function(req,res){
res.redirect('/admin');
});
Please help!
I'm currently using Firebase such that users sign in with their Google accounts to access the app. However, closing the page/opening the page in a new tab requires the user to sign in again. Is there a way to prevent users from having to re-login?
Here is the login code I am using (the example from the firebase docs)
function firebaseLogin() {
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
document.getElementById('user-name').innerHTML = user.displayName;
document.getElementById('propic').src = user.photoURL;
addClass(login, 'hidden');
removeClass(logout, 'hidden');
var snackbarData = {
message: 'Login Successful',
timeout: 2000
};
snackbarContainer.MaterialSnackbar.showSnackbar(snackbarData);
console.log(user);
reloadList();
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
var snackbarData = {
message: 'Login Unsuccessful',
timeout: 2000
};
snackbarContainer.MaterialSnackbar.showSnackbar(snackbarData);
console.error(error);
});
}
I'm not sure if this is the official way to do it, but I ended up saving the user returned from firebase.auth().currentUser in localStorage, and then checking if a user could be found in localStorage on document load. If a user is found, I just set firebase.auth().currentUser to equal the user from localStorage, and everything seemed to work as intended. (For example, if there wasn't an authenticated user, the client wouldn't be able to make calls to the database, but setting currentUser in this fashion allowed accessing the database.)
I need help how to push notification to specific user. I can now push notifcation but all user will get that notification. I can filter it on clinet side but I think it is unsecure...
First I send data with laravel 5:
$redis = Redis::connection();
$redis->publish('update.answer', json_encode($events));
here is my node.js i emite data:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('update.group', function(err, count) {
});
redis.subscribe('update.question', function(err, count) {
});
redis.subscribe('update.answer', function(err, count) {
});
redis.subscribe('update.comment', function(err, count) {
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(message);
io.emit(channel, message);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
and with angularjs I take data and push to the client.
socket.on('update.answer',function(data){
if($scope.remove){
$scope.remove = false;
}
$scope.feed = $("#feed").val();
if(parseInt($scope.feed) === parseInt(data.userID)){
$scope.answers.push(data);
$scope.$digest();
}
});
WIth this part:
$scope.feed = $("#feed").val();
if(parseInt($scope.feed) === parseInt(data.user_id) && data.admin_id !== null){
}
I check if client should get notification but it is unsecure...
Any way to improve this?
To push message to specific user , you must store his/her reference somewhere.
for ex
io.on('connection', function(socket) {
socket.on('add-user', function(data){
clients[data.username] = socket;
});
});
now to push message to specific user just use his username to retrive his socket
clients[data.username].emit(channel, message);
Update : Explanation
This Assume that each user who uses you web app is having some sort of authentication.
As soon as user login into your application , let him join on the nodejs backend socket.
on client side
socket.emit('add-user',userObj);
});
userObj is object that contains user details,you can send the username alone too
socket.emit('add-user',username);
in your nodejs first decalre one array that contains the socket of all the users who joins the website
var clients = [];
now in your nodejs application write this additional code
io.on('connection', function(socket) {
socket.on('add-user', function(data){
clients[data.username] = socket;
});
});
up to this moment the user who login into your website will call add-user event from client side which will in turn call add-user on nodejs and there socket will be added into the clients array
now to send message to any particular user you must know there username,so if you know the username of the user then you can simply emit message to them using
clients[data.username].emit(channel, message);