Unable to switch user to root using Node.js ssh2 module - javascript

Trying to SSH to a server and able to. However, when I try to run sudo command it prompts me to enter the password of the userid mentioned. How do I prevent any keyboard interruption and hardcode the password so it doesn't prompt for password.
server.js
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('sudo ls -lrt',{ stdin: 'password\n', pty: true }, (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'user1',
password: 'password'
});
The prompt I get:
STDOUT: [sudo] password for user1:
STDOUT:
sudo: timed out reading password

The below code works for me.
const Client = require('ssh2').Client;
const conn = new Client();
const encode = 'utf8';
const connection = {
host: 'hostname.foo.com',
username: 'iamgroot',
password: 'root#1234'
}
conn.on('ready', function() {
// Avoid the use of console.log due to it adds a new line at the end of
// the message
process.stdout.write('Connection has been established');
let password = 'root#1234';
let command = '';
let pwSent = false;
let su = false;
let commands = [
`ls -lrt`,
`sudo su - root`,
`ls -lrt`
];
conn.shell((err, stream) => {
if (err) {
console.log(err);
}
stream.on('exit', function (code) {
process.stdout.write('Connection closed');
conn.end();
});
stream.on('data', function(data) {
process.stdout.write(data.toString(encode));
// Handles sudo su - root password prompt
if (command.indexOf('sudo su - root') !== -1 && !pwSent) {
if (command.indexOf('sudo su - root') > -1) {
su = true;
}
if (data.indexOf(':') >= data.length - 2) {
pwSent = true;
stream.write(password + '\n');
}
} else {
// Detect the right condition to send the next command
let dataLength = data.length > 2;
let commonCommand = data.indexOf('$') >= data.length - 2;
let suCommand = data.indexOf('#') >= data.length - 2;
console.log(dataLength);
console.log(commonCommand);
console.log(suCommand);
if (dataLength && (commonCommand || suCommand )) {
if (commands.length > 0) {
command = commands.shift();
stream.write(command + '\n');
} else {
// su requires two exit commands to close the session
if (su) {
su = false;
stream.write('exit\n');
} else {
stream.end('exit\n');
}
}
}
}
});
// First command
command = commands.shift();
stream.write(command + '\n');
});
}).connect(connection);

Related

How can I setup anti-spam for my socket.io chatroom?

I want to add an anti-spam function in my socket.io chatroom using the socket-anti-spam module but I have no clue how to. I've tried a couple stuff, but they didn't seem to work.
If you can't help with the socket-anti-spam module, any other module is fine aswell. This version of my server.js has the anti-spam setup but it doesn't seem to work.
If you need any other information (which I doubt you'll need) like HTML or CSS, just comment and I'll update this question.
My server.js:
var PORT = process.env.PORT || 3000;
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var moment = require("moment");
var connectedUsers = {};
var prefix = "^";
var sysusername = "Twintails🎀";
function sleep(ms) {
var unixtime_ms = new Date().getTime();
while (new Date().getTime() < unixtime_ms + ms) {}
}
const SocketAntiSpam = require('socket-anti-spam')
const socketio = require('socket.io').listen(8080)
const socketAntiSpam = new SocketAntiSpam({
banTime: 30, // Ban time in minutes
kickThreshold: 2, // User gets kicked after this many spam score
kickTimesBeforeBan: 1, // User gets banned after this many kicks
banning: true, // Uses temp IP banning after kickTimesBeforeBan
io: socketio, // Bind the socket.io variable
})
app.use(express.static(__dirname + "/public"));
io.on("connection", function(socket) {
socketAntiSpam.event.on('ban', data => {
socket.emit("message", {
username: sysusername,
text: "A user was banned...",
timestamp: moment().valueOf()
});
})
console.log("A user is connected.");
socket.on("disconnect", function() {
var userData = connectedUsers[socket.id];
if (typeof userData !== "undefined") {
socket.leave(connectedUsers[socket.id]);
io.to(userData.room).emit("message", {
username: sysusername,
text: userData.username + " has left!",
timestamp: moment().valueOf()
});
delete connectedUsers[socket.id];
}
});
socket.on("joinRoom", function(req, callback) {
if (req.username.replace(/\s/g, "") !== "Twintails🎀") {
if (req.username.replace(/\s/g, "").length < 24) {
if (
req.room.replace(/\s/g, "").length > 0 &&
req.username.replace(/\s/g, "").length > 0
) {
var nameTaken = false;
Object.keys(connectedUsers).forEach(function(socketId) {
var userInfo = connectedUsers[socketId];
if (
userInfo.username.toUpperCase() === req.username.toUpperCase()
) {
nameTaken = true;
}
});
if (nameTaken) {
callback({
nameAvailable: false,
error: "This username is taken, please choose another one."
});
} else {
connectedUsers[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit("message", {
username: sysusername,
text: req.username + " has joined!",
timestamp: moment().valueOf()
});
callback({
nameAvailable: true
});
}
} else {
callback({
nameAvailable: false,
error: "Please complete the forum."
});
}
} else {
callback({
nameAvailable: false,
error: "Please make a username less than 24 characters."
});
}
} else {
callback({
nameAvailable: false,
error: "Your username can't be: " + sysusername
});
}
});
socket.on("message", function(message, callback, req) {
if (message.text.length > null) {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text !== " ") {
if (message.text.length < 200) {
message.timestamp = moment().valueOf();
io.to(connectedUsers[socket.id].room).emit(
"message",
message
);
}
}
}
}
}
}
}
}
}
}
}
});
socket.emit("message", {
username: sysusername,
text: "Ask someone to join this chat room to start talking.",
timestamp: moment().valueOf()
});
socket.on("message", function(message) {
if (message.text === prefix + "discord") {
socket.emit("message", {
username: sysusername,
text: "Join the Twintails🎀 server here: https://discord.gg/fK9ynNq",
timestamp: moment().valueOf()
});
sleep(1000);
}
});
socket.on("message", function(message) {
if (message.text === prefix + "bot") {
socket.emit("message", {
username: sysusername,
text: "Coming soon...",
timestamp: moment().valueOf()
});
sleep(1000);
}
});
});
http.listen(PORT, function() {
console.log("Server started on port " + PORT);
});
Thanks!
you can store the messages that the user sends and prevent if the current message is like the previous one

Node JS Imap-simple disconnect error after some time

I fetch unread messages in a middle ware that triggers my function every five minutes. It is successfully completing the request but eventually It triggers and crashes my nodejs process. With an error of:
Error: This socket has been ended by the other party
I have tried adding all these catches and error handling but It seams it eventually times out my connection to my inbox? Am I not reconnecting on every request to access my inbox?
Here is my code (also I have tried with authTimeout: 3000 in the config before anyone suggests that is the issue):
imap: {
user: 'myemail#gmail.com',
password: 'myPW',
host: 'imap.gmail.com',
port: 993,
tls: true,
keepalive: true
}
imaps.connect(settings.emailConfig).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['UNSEEN'];//only grab unread messages in LTS email
var fetchOptions = {
bodies: ['HEADER', 'TEXT', ''],
markSeen: true//mark as read
};
return connection.search(searchCriteria, fetchOptions).then(function (messages) {
console.log('looking for unread messages')
if (messages.length > 0) {
console.log('unread messages to save')
console.log('looking at messages : ' + util.inspect(messages, { depth: null }))
var saveUnreadEmais = messages.map(function (item) {//resolve each promise of unread message
var all = _.find(item.parts, { "which": "" })
var id = item.attributes.uid;
var idHeader = "Imap-Id: " + id + "\r\n";
simpleParser(idHeader + all.body, (err, mail) => {
var BarCode = "";
var subject = mail.subject;
var to = mail.to.value[0].address;
var from = mail.from.value[0].address;
var text = mail.text;
if (mail.subject.includes('Barcode :')) {//if the message to the system includes BarCode in the subject line grab it
var split = mail.subject.split(':');
BarCode = split[1];
}
if (!subject) {
subject = "LTS Email Recieved - Barcode : " + BarCode;
}
if (!text) {
text = "LTS auto email"
}
var newrec = {};
newrec.MessageDate = new Date();
newrec.MessageFor = to;
newrec.MessageFrom = from;
newrec.Message = text;
newrec.MessageAbout = BarCode;
newrec.MessageSubject = subject;
newrec.MessageStatusCode = 1;//1 sent, 2 read, 3 saved, -1 deleted
//console.log('saving message with details of : ' + util.inspect(newrec, { depth: null }))
return db.knex('dbo.PersonnelMessages').insert(newrec).then((data) => {
return "sent";
});
});
});
return Promise.all(saveUnreadEmais).then(() => {
//do anything you want after saving all unred emails to our db.
}).catch((err) => { console.log("error : " + err) })
}
else {
console.log('no new emails')
}
}).catch((err) => { console.log("error : " + err) })
}).catch((err) => { console.log("opening inbox error : " + err) })
}).then(function () {
console.log('In the INBOX');
}).catch(function (e) {
console.log('error : ' + e);
});

NodeJS Cannot find module 'io' ( socket.io with express 4.15.3)

I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)
Error: Cannot find module 'io'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)
Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.
app.js
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');
let session;
let app = express();
let connection = db.createConnection({
host:"localhost",
user:'root',
password:'',
database:'oulala'
});
connection.connect((error)=>{
if(error){
console.log('Error')
}else{
console.log("connected");
}
});
//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
resave:false,
saveUninitialized:true
}))
//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
app.use(express.static(__dirname + '/public'));
//Global Vars
app.use((req,res,next)=>{
res.locals.errors = null;
res.locals.isAuthenticated = false;
next();
});
app.use(expressValidator({
errorFormatter: (param,msg,value)=>{
let namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam+= '['+namespace.shift()+']';
}
return {
param : formParam,
msg : msg,
value : value
}
}
}));
app.get('/logout',(req,res)=>{
req.session.destroy((error)=>{
res.redirect('/');
})
})
app.post('/login',(req,res) => {
session = req.session;
req.checkBody('username','Username is required').notEmpty();
req.checkBody('password','Password is required').notEmpty();
errors = req.validationErrors();
if ( errors ) {
res.render('login',{
title:"Login",
errors:errors
});
}else{
if(req.body.username == 'admin' && req.body.password == 'admin'){
session.uniqueID = req.body.username;
isAuthenticated = true;
}
res.redirect('/');
}
})
app.get('/:page?',(req,res) => {
//res.send('Hello first page');
//res.json(people);
let page = req.params.page;
if ( page ) {
if ( page == 'posts' ){
connection.query("SELECT * FROM members",(error,rows,fields)=>{
if(error){
connection.release();
console.log('Error in the query - '+error);
}else{
res.render(page,{
title:page,
users:rows
});
}
});
}else{
res.render(page,{
title:page,
user:authenticate
});
}
}else{
session = req.session;
if(session.uniqueID){
res.render('index',{
title:"Index",
user:authenticate
});
}else{
res.render('login',{
title:"Login",
user:authenticate
});
}
}
});
// get form submition, post request
app.post('/users/add',(req,res) => {
//console.log(req.body.first_name); // req.body - request object
req.checkBody('first_name','Fisrtname is required').notEmpty();
req.checkBody('last_name','Lastname is required').notEmpty();
req.checkBody('email','Email is required').notEmpty();
errors = req.validationErrors();
if ( errors ) {
res.render('index',{
title:"Customers",
users:people,
errors:errors
});
}else{
var newUser = {
first_name:req.body.first_name,
last_name:req.body.last_name,
email:req.body.email
}
people.push(newUser);
res.render(page,{
title:page,
users:people,
user:authenticate
});
}
});
app.listen(3000, () => {
console.log('server started on port 3000....');
});
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});
client.js
$(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInput = $('.usernameInput'); // Input for username
var $messages = $('.messages'); // Messages area
var $inputMessage = $('.inputMessage'); // Input message input box
var $loginPage = $('.login.page'); // The login page
var $chatPage = $('.chat.page'); // The chatroom page
// Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
// Sets the client's username
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
}
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// tell server to execute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
// Log a message
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// Adds the visual chat typing message
function addChatTyping (data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// Adds a message element to the messages and scrolls to the bottom
// el - The element to add as a message
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// Setup default options
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// Apply options
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// Updates the typing event
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat – ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
socket.on('disconnect', function () {
log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
});
index.ejs
<% include partials/header %>
<h1><%= title %></h1>
<ul class="pages">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title">What's your nickname?</h3>
<input class="usernameInput" type="text" maxlength="14" />
</div>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/javascript/socket.io.js"></script>
<script src="/javascript/client.js"></script>
<% include partials/footer %>
package.json
{
"name": "customerapp",
"version": "1.0.0",
"description": "Simple customer managment app",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Anna Gabrielyan",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.2",
"ejs": "^2.5.6",
"express": "^4.15.3",
"express-session": "^1.15.3",
"express-validator": "^3.2.0",
"mysql": "^3.10.10",
"oauth2-server": "^2.4.1",
"socket.io": "^2.0.2"
}
}
First you need to install packages using below command
npm install
This command will install all the packages from your package.json once done you can run this program.
did you install socket.io using npm. if not try
npm install --save socket.io
can you show me package.json,?
I find my bug.
I removed this code
app.listen(3000, () => {
console.log('server started on port 3000....');
});
and added this
server.listen(3000);
after this
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
thanks to #Curious for helping and great answer
socket.io - can't get it to work, having 404's on some kind of polling call

Node project works locally but fails when installing via NPM?

I have this straightforward node project, with a main.js file when I run it locally node main.js it works fine. But when I do an npm install -g cli-tweet and then try to run it, it outputs this error :
/home/USER/.npm-global/bin/tweet: 1: /home/USER/.npm-global/bin/tweet: Syntax error: "(" unexpected
The package.json looks something like this :
{
"name": "cli-tweet",
"main": "main.js",
"bin": {
"tweet": "main.js"
},
[...]
}
Any idea on how to fix this ?
Edit 1:
The code for main.js
var OAuth = require('oauth').OAuth,
colors = require('colors'),
Twitter = require('twitter'),
fs = require('fs'),
get_args = require('cli-pipe');
var CONFIG_FILE = '.tweet.json',
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token',
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token',
OAUTH_VERSION = '1.0', HASH_VERSION = 'HMAC-SHA1';
var key = "XYZ",
secret = "XYZ", tweetText;
function getAccessToken(oa, oauth_token, oauth_token_secret, pin) {
oa.getOAuthAccessToken(oauth_token, oauth_token_secret, pin,
function (error, oauth_access_token, oauth_access_token_secret, results2) {
if (error && parseInt(error.statusCode) == 401) {
throw new Error('The pin number you have entered is incorrect'.bold.red);
}
var keys = {
'ACCESS_TOKEN_KEY': oauth_access_token,
'ACCESS_TOKEN_SECRET': oauth_access_token_secret
};
fs.open(CONFIG_FILE, "wx", function (err, fd) {
try {
fs.close(fd, function (err) {
});
} catch (e) {
}
});
fs.writeFileSync(CONFIG_FILE, JSON.stringify(keys));
console.log('Try echo "test" | cli-tweet'.cyan);
process.exit(1);
});
}
function getRequestToken(oa) {
oa.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) {
if (error) {
throw new Error(([error.statusCode, error.data].join(': ')).bold.red);
} else {
console.log(('https://twitter.com/oauth/authorize?oauth_token=' + oauth_token).underline.blue)
console.log('Enter the pin number here:'.bold.yellow);
var stdin = process.openStdin();
stdin.on('data', function (chunk) {
var pin = chunk.toString().trim();
getAccessToken(oa, oauth_token, oauth_token_secret, pin);
});
}
});
}
function tweet(userTokens) {
var client = new Twitter({
consumer_key: key,
consumer_secret: secret,
access_token_key: userTokens.oauth_access_token,
access_token_secret: userTokens.oauth_access_token_secret
});
console.log("Tweet :" + tweetText.bold.cyan);
if (tweetText.length > 0) {
client.post('statuses/update', {status: tweetText}, function (error, tweet, response) {
if (error) {
console.log("Error :" + JSON.stringify(error));
}
process.exit(1);
});
} else {
console.log("Pipe a tweet".bold.red);
}
}
var isConfig = process.argv[2];
if (isConfig === undefined || isConfig.toLowerCase() != "config") {
try {
var contents = fs.readFileSync(CONFIG_FILE).toString(), tokens = JSON.parse(contents);
} catch (e) {
console.log("Error: Try running 'tweet config' command".bold.red);
}
if (tokens != undefined && (tokens.ACCESS_TOKEN_KEY != undefined && tokens.ACCESS_TOKEN_SECRET != undefined)) {
try {
get_args(function (args) {
tweetText = args[2];
tweet({
"oauth_access_token": tokens.ACCESS_TOKEN_KEY,
"oauth_access_token_secret": tokens.ACCESS_TOKEN_SECRET
});
});
} catch (e) {
console.log("Error: Unexpected error while tweeting".bold.red);
}
} else {
console.log("Try running 'cli-tweet config' command".bold.red);
}
} else {
var oa = new OAuth(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, key, secret, OAUTH_VERSION, 'oob', HASH_VERSION);
getRequestToken(oa);
}
Edit 2 :
Running the code like this: node /home/USER/.npm-global/lib/node_modules/cli-tweet/main.js seems to work
1) Add folder bin
2) Add file bin/tweet with
#!/usr/bin/env node
require('../main.js');
3) change package.json
"bin": {
"tweet": "./bin/tweet",
}

Exporting Mysql Connection in nodeJS

In my database.js I have
var Mysql = require('Mysql');
var Jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
var supersecretkey = 'JMDub_Super_Secret_key';
var config = require('./config');
var signupErrors = require('./Signuperrors.js');
var sucessMsg = require('./SucessMessages.js');
var App_errors = require('./error.js');
var query = require('./queryDB.js');
var connection = Mysql.createConnection({
"host": "******",
"user": "****",
"password": "***",
"database": "***"
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
//Sign Up Methods
var createUser = function createwithCredentails(post,callback) {
bcrypt.hash(post.password, 10, function(err, hash){
//console.log('Cache Hash : +',hash);
var createUserQuery = connection.query('INSERT INTO users SET ?',{"email":post.email,"password":hash,"username":post.username},function(err,result){
if (err) {
if (err.code == 'ER_DUP_ENTRY') {
//console.log(err.code);
callback(signupErrors.error_5000);
}
else callback(App_errors.error_1003);
}
if (result) {
callback(sucessMsg.success_signup);
}
});
});
}
//connection.query('SELECT * FROM Users Where Username = '' AND Password = ''');
var validateUser = function ValidateUserWithUserNameAndPassword(post,callback) {
var UserCheckQuery = connection.query('SELECT * FROM users WHERE email="'+post.email+'"',function(err, results, fields) {
if (err){
console.log(err);
callback(App_errors.error_1000);
}
if (results.length == 1) {
//console.log(results[0].password,post.password);
var givenPassword = post.password;
var DBhash = results[0].password;
bcrypt.compare(givenPassword, DBhash,function(err, res) {
if (res) {
console.log('Password matched');
var token = Jwt.sign({"email":post.email,"username":post.username},supersecretkey, {
expiresIn: 60*60*5 // expires in 5 hours
});
callback({
message:{
"success":1,
"description":"sucessfully logged in - please cache the token for any queries in future",
"environment":"test",
"errorCode":null
},
"token":token
});
}
if (!res) {
console.log('password doesnt match');
callback(signupErrors.error_6000);
}
if (err) {
console.log('Error Comparing Passwords');
callback(App_errors.error_1004);
}
});
}
else{
callback(signupErrors.error_6000);
}
});
};
var isauthenticate = function isauthenticated(post,route,callback) {
if (post.headers.token) {
Jwt.verify(post.headers.token, supersecretkey, function(err, decoded) {
if (decoded) {
//console.log(decoded);
//From this part the user is Sucessully Authenticated and autherization params can be extracted from token if required
//Write Business Logic in future as per the requirement
//Operation 1 - Update Profile
//Profile Details consists of {1.first name 2.last name 3. profile pictur(base 64 encoded) 4.further settings in future that can be added to DB if required}
if (route == '/update-profile') {
query.updateProfile(connection,decoded.email,post.body,function(response) {
callback(response);
});
}
//callback({"message":"is a valid token"});
}
if (decoded == null) {
console.log('is not a valid token');
//callback(App_errors.error_1000);
}
if (err) {
console.log('error verifying token');
callback(App_errors.error_1000);
}
});
}
else{
callback(App_errors.error_1001);
}
};
module.exports = {
validateUser:validateUser,
createUser:createUser,
isauthenticate:isauthenticate,
connection:connection
}
I am exporting connection object to queryDB.js file. But when I try to log the exported connection object I get undefined object. Why is this happening?
When I pass connection object as function argument, everything works fine. Not sure why?
below is queryDB.js file
var errors = require('./error.js')
var Dbconnection = require('./Database.js').connection;
var updateProfile = function profiledata(connection,email,data,callback) {
console.log(Dbconnection);
if ((!data)|| (Object.keys(data).length < 1)) {
//console.log(data);
callback(errors.error_1001);
}
else{
callback({"message":"update Sucesss"});
//console.log(connection);
//var updateData = mapProfileDataTomodel(data);
//console.log(updateData);
connection.query('SELECT * FROM users WHERE email = "'+email+'"',function(err, result,feilds) {
if (err) throw err;
if (result) {
console.log(result);
}
});
}
}
var mapProfileDataTomodel = function mapProfileDataTomodel(data) {
var profileDataModel = {};
for (var key in data) {
//console.log('looping and mapping data');
if (data.firstname) {
profileDataModel.firstname = data.firstname;
}
if (data.lastname) {
profileDataModel.lastname = data.lastname;
}
if (data.profilepic) {
profileDataModel.profilepic = data.profilepic;
}
}
return profileDataModel;
}
module.exports = {
updateProfile:updateProfile
}
I have commented out connection object log via function arguments.
So, Why I am unable to get the connection object that is exported? But I used the same exported connection object in my app.js file. It did work fine there.

Categories

Resources