Express authentication handling does not function - node.js

I am building a demo authentication system using express in combination with sqlite 3. Authentication functions the way it should, but the client does not react to any of the responses such as:
res.send('welcome to website');
or
res.redirect(login.html);
or
res.redirect('http://google.com');
How can I properly handle a login after it is approved?
Server side:
app.get('/login/username/:userN/password/:passW', function (req, res) {
var username = req.params.userN,
password = req.params.passW;
console.log('initiating login');
db.get('SELECT * FROM users WHERE username=?', [username], (err, row) => {
if (row == undefined){
console.log('login fail (user doesnt exist)')
}
else if (row.password == password) {
res.redirect('http://google.com');
console.log('user: ' + username + ' logged in');
}
else {
console.log('login fail (wrong password)');
}
})
});
Clientside:
function get(url) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:3000/" + url, true);
xmlhttp.send();
};
$('#login').click(function server() {
var username = document.getElementById('user').value;
var password = document.getElementById('pass').value;
var url = 'login/username/' + username + '/password/' + password;
get(url);
});

Related

JSONP callback doesn't seem to be working

I've been working with the Firebase Admin SDK for Nodejs in the cloud functions to create custom auth tokens using Spotify and Firebase auth.
I've been trying to use the example given by Google that goes as follows:
exports.token = functions.https.onRequest((req, res) => {
try {
cookieParser()(req, res, () => {
functions.logger.log('Received verification state:', req.cookies.state);
functions.logger.log('Received state:', req.query.state);
if (!req.cookies.state) {
throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
} else if (req.cookies.state !== req.query.state) {
throw new Error('State validation failed');
}
functions.logger.log('Received auth code:', req.query.code);
Spotify.authorizationCodeGrant(req.query.code, (error, data) => {
if (error) {
throw error;
}
functions.logger.log(
'Received Access Token:',
data.body['access_token']
);
Spotify.setAccessToken(data.body['access_token']);
Spotify.getMe(async (error, userResults) => {
if (error) {
throw error;
}
functions.logger.log(
'Auth code exchange result received:',
userResults
);
// We have a Spotify access token and the user identity now.
const accessToken = data.body['access_token'];
const spotifyUserID = userResults.body['id'];
const profilePic = userResults.body['images'][0]['url'];
const userName = userResults.body['display_name'];
const email = userResults.body['email'];
// Create a Firebase account and get the Custom Auth Token.
const firebaseToken = await createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken);
// Serve an HTML page that signs the user in and updates the user profile.
res.jsonp({token: firebaseToken});
});
});
});
} catch (error) {
res.jsonp({error: error.toString()});
}
return null;
});
Here's the code from the client for making the request
const loginError = ref(null)
const route = useRoute()
console.log(route.query)
const { code, state, error } = route.query
function tokenReceived(data) {
if (data.token) {
projectAuth.signInWithCustomToken(data.token).then((userCredential) => {
console.log(userCredential)
})
} else {
console.error(data)
document.body.innerText = 'Error in the token Function: ' + data.error
}
}
if (error) {
loginError.value = 'Error back from the Spotify auth page: ' + error
} else if (code) {
// Use JSONP to load the 'token' Firebase Function to exchange the auth code against a Firebase custom token.
const script = document.createElement('script')
script.type = 'text/javascript'
// This is the URL to the HTTP triggered 'token' Firebase Function.
// See https://firebase.google.com/docs/functions.
const tokenFunctionURL =
'http://localhost:5001/pacelist-main/us-central1/token'
script.src =
tokenFunctionURL +
'?code=' +
encodeURIComponent(code) +
'&state=' +
encodeURIComponent(state) +
'&callback=' +
tokenReceived.name
document.head.appendChild(script)
}
const signIn = () => {
// Start the auth flow.
window.location.href =
'http://localhost:5001/pacelist-main/us-central1/redirect'
}
return { loginError, signIn }
Full repository here: https://github.com/firebase/functions-samples/tree/main/spotify-auth
But the jsonp callback doesn't seem to run when it goes back to my site. It should "Serve an HTML page that signs the user in and updates the user profile." and log the user in, but it does nothing. Been stuck on this one for days...

NodeJs login form with SQL Server user auth

I am having an issue with authenticating users using a SQL Server database. I have established the connection with the database and can pull user from the database. However when trying to query the database for authentication I get an "unhandledpromise - connection is closed" error.
app.js file:
var sql = require("mssql");
var express = require("express");
var session = require("express-session");
var bodyParser = require("body-parser");
var path = require("path");
var dbconfig = {
server: "Server",
database: "Test",
user: "########",
password: "####################",
port: 1433,
options : {
encrypt: false
}
};
var app = express();
app.use(session({
secret: 'Secret',
resave: true,
saveUninitalized: true
}));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/login.html'));
});
app.post('/auth', function(request, response) {
var username = request.body.username;
var password = request.body.password;
var conn = new sql.ConnectionPool(dbconfig);
var req = new sql.Request(conn);
if (username && password) {
conn.connect();
req.query('Select * from Admin where username = ? and password = ?', [username, password], function(error, results, fields) {
if (results.length > 0) {
request.session.loggedin = true;
resquest.session.username = username;
response.redirect('/home');
} else {
response.send('Username and/or Password not found');
}
conn.close();
response.end();
});
} else{
response.send('Please enter Username and Password');
}
});
app.get('/home', function(request, response){
if(request.session.loggedin){
response.send('Welcome back,' + request.session.username + '!');
}else{
response.send('Please sign');
}
response.end();
});
app.listen(3000);
function getEMP() {
var conn = new sql.ConnectionPool(dbconfig);
var req = new sql.Request(conn);
conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
req.query("Select * from Admin", function(err, recordset) {
if (err) {
console.log(err)
} else {
console.log(recordset)
}
conn.close();
});
});
}
getEMP();
The getEMP function returns all of the admins from the database as expected. This is why I am positive the connection is working. This function was used for testing connection.
Error
UnhandledPromiseRejectionWarning: ConnectionError: Connection is closed.
at Request._query (///nodeconSQL/node_modules/mssql/lib/base/request.js:447:37)
at Request._query (///nodeconSQL/node_modules/mssql/lib/tedious/request.js:346:11)
at shared.Promise (///nodeconSQL/node_modules/mssql/lib/base/request.js:413:12)
at new Promise ()
at Request.query (///nodeconSQL/node_modules/mssql/lib/base/request.js:412:12)
at /home/devops-01/nodeconSQL/app.js:43:13
at Layer.handle [as handle_request] (///nodeconSQL/node_modules/express/lib/router/layer.js:95:5)
at next (///nodeconSQL/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (///nodeconSQL/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (///nodeconSQL/node_modules/express/lib/router/layer.js:95:5)
Your function getEMP() uses the callback from conn.connect() in order to wait until the connection is established before trying to execute the query.
The function that tries to login executes the query immediately after attempting to open the connection, however since the connection takes some time to be established, this is why you get the error that your connection is not open.
Put your login query inside the conn.connect(function(err){ /* login code */ }) construct like it is in your getEMP() function. You will then need to make sure that you can access the request and response objects in the callback function, for example by using .bind() on your callback function to put the request and response objects into the this object. Another option is to use closure functions to get data to the callbacks.
Example using closures:
app.post('/auth', function(request, response) {
var username = request.body.username;
var password = request.body.password;
if (username && password) {
var conn = new sql.ConnectionPool(dbconfig);
conn.connect((function(){
var thisConn = conn;
var req = new sql.Request(thisConn);
return function(){ //connect callback
req.query('Select * from Admin where username = ? and password = ?', [username, password],
(function(){
var req = request;
var resp = response;
var conn = thisConn;
return function(error, results, fields) { // query callback
if (results.length > 0) {
req.session.loggedin = true;
req.session.username = username;
resp.redirect('/home');
} else {
response.send('Username and/or Password not found');
}
conn.close();
resp.end();
};
})());
};
})());
} else {
response.send('Please enter Username and Password');
}
});
Example using bind:
...
// Inside your /auth route
// make an object with the data our callback needs, to use with .bind()
var callbackData = {"conn": conn, "request": request, "response": response};
var connectCallback = function(err){
if (err) {
console.log(err);
return;
}
req.query('Select * from Admin where username = ? and password = ?',
[username, password], function(error, results, fields) {
// 2nd level of callback, query callback
if (results.length > 0) {
this.request.session.loggedin = true;
this.resquest.session.username = username;
this.response.redirect('/home');
} else {
this.response.send('Username and/or Password not found');
}
this.conn.close();
this.response.end();
}.bind(this)); // pass our 'this' object through to the next level
}.bind(callbackData);
conn.connect(connectCallback);
...

how to create login api using odoo-node?

I simply want to create api for login . no signup is there, username and password is already there in database.
simply want to get username and password from front end and , i have to check with existing database, whether username and password matching, then i have to send some success message or token, what ever it be.
font end side is angularjs. and in angularjs im using
$http.post("/api address",usedata).success(data,success){}
like that but i have no idea how to do it in backend side. anyone please help.....
what i have tried with oddo is given below.
var express = require('express');
var app = express();
var fs = require("fs");
var Odoo = require('node-odoo');
var odoo = new Odoo({
host: '192.168.1.121',
port: 8091,
database: 'oaveg_demo',
username: 'dkashyap#oaveg.com',
password: 'abcd#1234'
});
app.get('/api/userdetails',function(req, res) {
odoo.connect(function(err) {
if (err) {
return console.log(err);
}
odoo.get('res.users', 14, function(err, partner) {
if (err) {
return console.log(err);
}
var userData = {};
userData.name = partner.display_name;
userData.email = partner.email;
userData.id = partner.id;
userData.password = partner.password;
console.log('PARTNER GET====> ', userData);
});
var params = [['login','=','aritha#oaveg.com'],['password' , '=' , '']];
odoo.search('res.users', params, function(err, partner) {
if (err) {
return console.log(err);
}
console.log('PARTNER SEARCH===> ', partner);
})
});
});
app.listen(3001);

NodeJS + Express: How to use sessions variables in other methods. (Session-variable: undefined)

I'm using NodeJS 0.10.18 and Express 3.4.0 for a webserver to work with an PhoneGap application.
I want to use Session Variables/Sessions to store the users Username to use it in other methods.
When i login in the login method, the username is stored in req.session.name (it is set because i can print it to the console). But later on when i want to use it in the reserve method the req.session.name variable is suddenly undefined.
Can you tell me what i'm doing wrong?
Here's my code:
//NodeJS Modules
var http = require('http');
var express = require("express");
//Variables
var app = express();
var listenport = '8123';
var Username = "";
var Password = "";
//Application configuration
app.configure(function(){
app.use(express.cookieParser('S3CRE7'));
app.use(express.cookieSession());
app.use(app.router);
});
//Create header for every HTTP response
app.all("*", function(req, res, next) {
res.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'});
next();
});
//Login
app.post("/MobileApplication/login", function(req, res) {
//Response 0 = correct
var loginUsername = req.param('Username');
//VALIDATE
//STORE IN SESSION
req.session.name = loginUsername;
console.log(req.session.name);
res.end("0");
});
//Reservation
app.post("/MobileApplication/reserve", function(req, res) {
var name = req.session.name;
console.log(name);
res.end("0");
});
//If the url isn't valid respond with 404
app.all("*", function(request, response) {
response.end("404!");
});
//Listen on listenport
http.createServer(app).listen(listenport);
Phonegap ajax login request:
jQuery.ajax({
url: "http://" + serverip + ":" + serverpoort + "/MobileApplication/login?Username=" + Username + "&Password=" + Password + "",
type: "POST",
beforeSend: function(data) {
console.log("login - sending");
},
success: function(data) {
console.log("login - succes!");
if (data === "0") {
$('input[type="checkbox"]').filter('#checkbox-1').each(function() {
if ($(this).is(':checked')) {
// perform operation for checked
window.localStorage.setItem("Username", Username);
window.localStorage.setItem("Password", Password);
$.mobile.navigate("#customers", {transition: "slide"});
}
else {
// perform operation for unchecked
window.localStorage.setItem("Username", "");
window.localStorage.setItem("Password", "");
$.mobile.navigate("#customers", {transition: "slide"});
}
});
}
if (data === "1") {
navigator.notification.alert(
'The username you have entered does not exist.', // message
doNothing,
'Error', // title
'Ok' // buttonName
);
}
if (data === "2") {
navigator.notification.alert(
'You have entered a wrong password.', // message
doNothing,
'Error', // title
'Ok' // buttonName
);
}
},
error: function(a, b, c) {
alert("login - error: " + a.toString() + " " + b.toString() + " " + c.toString());
navigator.notification.alert(
"login - error: " + a.toString() + " " + b.toString() + " " + c.toString(), // message
doNothing,
'Error', // title
'Ok' // buttonName
);
}
});

simpleSMTP User Auth

I'm trying to build a SMTP server with nodejs and stuck at user authentication. How can I create a function to auth the user with user: foo and pass: bar ?
var simplesmtp = require("simplesmtp"),
fs = require("fs");
var options = {
requireAuthentication: true,
debug: true
};
var smtp = simplesmtp.createServer(options);
smtp.listen(9845);
smtp.on("authorizeUser", function (connection, username, password, callback) {
callback(new Error("Auth fail!"), true);
});
smtp.on("startData", function(connection){
console.log("Message from:", connection.from);
console.log("Message to:", connection.to);
connection.saveStream = fs.createWriteStream("message.txt");
});
smtp.on("data", function(connection, chunk){
connection.saveStream.write(chunk);
});
smtp.on("dataReady", function(connection, callback){
connection.saveStream.end();
console.log("Incoming message saved to message.txt");
callback(null, "ABC1"); // ABC1 is the queue id to be advertised to the client
//callback(new Error("Rejected as spam!")); // reported back to the client
});
Did you try something like this?
smtp.on("authorizeUser", function (connection, username, password, callback) {
if (username == "foo" && password == "bar") {
callback(null, true);
} else {
callback(new Error("Auth fail!"), false);
}
});

Resources