How can I uppercase a hashed md5 in my query? - sql

How can I uppercase a hashed md5 before it goes into the database?
I tried the following:
connection.query("UPDATE penguins SET password = UPPER(password)");
This works, but it does not uppercase the user that just registered. It does uppercase every other md5 hash in the database.
This is my INSERT query:
var insertQuery = "INSERT INTO penguins (moderator, registrationdate, inventory, email, password, username, nickname ) VALUES ('" + moderator + "','" + registrationdate + "','" + inventory + "','" + email + "', + MD5('" + password + "'), '" + username + "', '"+username+"')";
This is my whole passport strategy:
var moment = require('moment');
var datetime = moment().format('x')
var mysql = require('mysql');
var LocalStrategy = require('passport-local').Strategy;
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root'
});
connection.query('USE kitsune');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM penguins WHERE id = " + id, function(err, rows) {
done(err, rows[0]);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'username',
passwordField: 'password',
gameusernameField: 'username',
nicknameField: 'nickname',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// here you read from req
const email = req.body.email
const nickname = req.body.nickname
const inventory = '%1'; // This is what the user gets on register. You can set this to anything that you want like: %1%2%3%4%5%6%7%8%9%10%11%12%13%14%15%16
const moderator = '0';
const registrationdate = datetime
passport.serializeUser(function(username, done) {
done(null, username);
});
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
connection.query("SELECT * FROM `penguins` WHERE `username` = '" + username + "'", function(err, rows) {
console.log(rows);
console.log("above row object");
if (err) return done(err);
if (rows.length) {
return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUserMysql = new Object();
newUserMysql.registrationdate = registrationdate;
newUserMysql.moderator = moderator;
newUserMysql.inventory = inventory;
newUserMysql.email = email;
newUserMysql.password = password; // use the generateHash function in our user model
newUserMysql.username = username;
newUserMysql.nickname = nickname;
var insertQuery = "INSERT INTO penguins (moderator, registrationdate, inventory, email, password, username, nickname ) VALUES ('" + moderator + "','" + registrationdate + "','" + inventory + "','" + email + "', + MD5('" + password + "'), '" + username + "', '"+username+"')";
console.log(insertQuery);
console.log('Query is rolling!');
connection.query(insertQuery, function(err, rows) {
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
}
});
}));
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, email, password, username, nickname, done) { // callback with email and password from our form
connection.query("SELECT * FROM `penguins` WHERE `username` = '" + username + "'", function(err, rows) {
if (err) return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!(rows[0].password == password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, rows[0]);
});
}));
};

Have you tried UPPER() at insert statement, hope this may work.
var insertQuery = "INSERT INTO penguins (moderator, registrationdate, inventory, email, password, username, nickname ) VALUES ('" + moderator + "',UNIX_TIMESTAMP(),'" + inventory + "','" + email + "', + UPPER(MD5('" + password + "')), '" + username + "', '"+username+"')";

Related

Difference between where and like in CLEARDB

I'm trying a simple nodejs login system and want to use the following query:
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
But it simply doesn't return anything so I had to do it like this:
'SELECT * from admin_cred where username like "%'+username+'%" AND password like "%'+password+'%"'
This is the code segment:
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
// 'SELECT * from admin_cred where username like "%'+username+'%" AND password like
"%'+password+'%"'
);
Can anyone point out why the first query is not working?
And the difference bertween the two statements?
N.B: This is the first time i'm using cleardb on heroku and a few things seems different from MySql. Everything else in the code works so I've narrowed the problem down
EDIT 1
I just noticed that the second query is running even though the password was wrong
UPDATE 1
Here is the node js code as requested:
class auth {
constructor(app, database) {
this.login(app, database);
}
//http://localhost:8000/api/auth/v1/login
login(app, database) {
app.post("/api/auth/v1/login", async (request, response) => {
const username = request.body.username;
const password = request.body.password;
try {
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?'", [username]
);
console.log(result);
if(result.length > 0){
if(password === result[0].password){
response.json({
loggedIn:"true",
data: username
})
}else{
response.json({
loggedIn:"false",
data: "wrong username or pass"
})
}
}else{
response.json({
loggedIn:"false",
data:"username doesnt exist"
})
}
} catch (error) {
console.log(error);
}
});
}
}
And here is the post request from ReactJs:
const handleLogin = async (e) =>{
e.preventDefault();
const admin = {username, password};
const response = await axios.post(
"http://localhost:8000/api/auth/v1/login",
admin
);
if(response.length > 0){
console.log("response: " + response);
}else{
console.log("no response")
}
};
Use:
const result = await database.query(
'SELECT * FROM admin_cred WHERE username = "?" AND password = "?"', [username, password]
);
Tip: never use LIKE for authentication queries and try to encrypt passwords.

node mssql binding in query

I'm new to SQL Server. When I was using MySQL, it was so easy to bind variables using '?'. However, I don't know how to bind variables in mssql.
I tried this:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
var Myquery = "INSERT INTO person (idNumber, forename, surname, age, address, maritalStatus)" +
" VALUES( " + req.body.idNumber + ", " + req.body.forename + ", " + req.body.surname +
", " + req.body.age + ", " + req.body.address + ", " + req.body.maritalStatus + " )";
pool.request().query(Myquery, function (err, result) {
res.json(result);
})
I get this error:
Invalid column name 'single'.
However, when I execute the query I created here (Myquery) directly in SQL Server, it goes smoothly. How can I fix this?
edit:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
const ps = new SQL.PreparedStatement(pool);
ps.input('param', SQL.NVarChar);
ps.prepare('SELECT * FROM #param', function (err) {
if (err) console.log('error: ' + err);
else {
ps.execute({param: 'person'}, function (err, result) {
console.log(result);
})
}
});
error: ConnectionError: Connection not yet open.
I used this too:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
pool.request().input('param', SQL.NVarChar, 'person')
.query("SELECT * FROM #param", function (err, result) {
if (err) console.log('error: ' + err);
console.log(result);
});
error: ConnectionError: Connection is closed.
You need single quotes around your text values:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
var Myquery = "INSERT INTO person (idNumber, forename, surname, age, address, maritalStatus)" +
" VALUES( " + req.body.idNumber + ", '" + req.body.forename + "', '" + req.body.surname +
"', " + req.body.age + ", '" + req.body.address + "', '" + req.body.maritalStatus + "' )";
pool.request().query(Myquery, function (err, result) {
res.json(result);
})
Also its a SUPER bad idea to create queries based on inputs this way as it allows SQL injection. You should use #parameters (https://blogs.msdn.microsoft.com/sqlphp/2008/09/30/how-and-why-to-use-parameterized-queries/)

Can I use busboy with passport.js?

I'm using FormData() in my React app. I was going to use it for registration and login too. I have a working passport.js registration piece of code and was going to use it with busboy but it looks like it reads fields one by one whenever there is one and it seems like I can't use it with Account.register.
I've inserted Account.register in busboy.on('field') but then realized it won't work. I didn't change req.body.username etc in my original code, ignore them.
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
Account.register(new Account({ nickname: req.body.username, email: req.body.email }), req.body.passwordOne, (err, user) => {
if(err){
helpers.errors(err, res);
} else {
helpers.registerSuccess(res);
}
});
});
busboy.on('finish', function() {
console.log('Done parsing form!');
//res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
I'm using nickname instead of username in passport.js because I'm using email as the username field. Working code:
router.post('/register', (req, res, next)=>{
var busboy = new Busboy({ headers: req.headers });
let nickname = '';
let email = '';
let password = '';
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
if(fieldname == 'username') { nickname = val; }
if(fieldname == 'email') { email = val; }
if(fieldname == 'password') { password = val; }
});
busboy.on('finish', function() {
console.log('Done parsing form!');
console.log('email: ' + email + 'password: ' + password + 'username: ' + nickname);
Account.register(new Account({ nickname: nickname, email: email }), password, (err, user) => {
if(err){
helpers.errors(err, res);
} else {
helpers.registerSuccess(res);
}
});
});
req.pipe(busboy);
});

Looping through JSON using Node.js

I am trying to loop through JSON using Node so that I can call a stored procedure in a sql database. the JSON is:
[ { boardid: '1', accesid: '2' },
{ boardid: '2', accesid: '3' },
{ boardid: '8', accesid: '4' } ]
the pseudo code i want to implement is: (I have the UserID)
var data = req.body.addJSON
for each JSON object {
con.query(
"CALL addUserToBoard('" + UserID + "', '" + BoardID + "','" + AccessTypeID + "');",
function(err, result, fields) {
if (err) throw err;
}
);
}
You can always interate in an Object a follows
var jsonresponse = JSON.parse(data);
Object.keys(jsonresponse).forEach( function(param , index) {
console.log(jsonresponse[param]);
console.log(index);
});
You could do this using a simple forEach,
var data = req.body.addJSON
data.forEach(value => {
con.query("CALL addUserToBoard('" + UserID + "', '" + value.boardid + "','" + value.accesid + "');", function (err, result, fields)
{
if (err) throw err;
});
})

WL.Server.getActiveUser returns Null

I need the ability to get a users login userid/password in a java adapter. After reading lots of articles, the best way seems to be to call
WL.Server.getActiveUser from a javascript function that gets called from the java adapter. So, I added a getIdentity function to the http adapter that authenticates our app. I have verified that getActiveUser works in the authentication function that the login pages calls...
When I call the getIdentity function, getActiveUser returns null using The same authentication realm. I have set the realm in the application_descriptor file. Not sure what else I have to do. Any ideas?
function performAuthentication(username, password) {
WL.Logger.info("In performAuthentication: username = " + username + " password = " + password + "Time = " + new Date(new Date().getTime()).toLocaleString());
var invocationData = {
adapter : 'BluePages',
procedure : 'authenticate',
parameters : [username, password]
};
var invocationResult = WL.Server.invokeProcedure(invocationData);
var fullName = invocationResult.result.fullName;
if (invocationResult.result.success == false) {
return {
authRequired: true,
loginPassed: false
};
}
else {
userIdentity = {
userId: username,
credentials: password,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
var activeUser = WL.Server.getActiveUser("AuthRealm");
WL.Logger.info("activeUser = " + activeUser);
if(activeUser && activeUser.userId == username){
WL.Logger.info("Active userId = " + activeUser.userId + " password = " + activeUser.credentials);
WL.Logger.info("User has been logged in!");
return {
loginPassed: true,
authRequired: false,
fullName: fullName,
result: invocationResult.result
};
}
else {
WL.Logger.info("Else Clause...");
if(activeUser != null)
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
}
return {
authRequired: false,
loginPassed: true,
fullName: fullName
};
}
}
function getIdentity() {
WL.Logger.info("AuthAdapter: In getIdentity: Time = " + new Date(new Date().getTime()).toLocaleString());
WL.Logger.info("AuthAdapter: userIdentity = " + userIdentity);
var activeUser = WL.Server.getActiveUser("AuthRealm");
WL.Logger.info("AuthAdapter: getIdentity: getActiveUser returned = " + activeUser);
if (activeUser) {
WL.Logger.info("AuthAdapter: getIdentity userId = " + activeUser.userId);
return {
userId: activeUser.userId,
credentials: activeUser.credentials,
};
}
}
There could be 2 reasons to get null when using WL.Server.getActiveUser:
1)If no realm is defined on the adapter, the method returns null (active user is unknown)
2)If a realm is defined on the adapter:
If there is no strong identity associated with the user (the user was authenticated in this session or in a previous session), the method returns null.
In your case you said the realm is exist so I suggest to try #2
You can find more information here:
https://www.ibm.com/support/knowledgecenter/SSZH4A_6.0.0/com.ibm.worklight.help.doc/apiref/r_method_wl_server_getactiveuser.html