LinkedIn get people by Id in node.js - node.js

I want to get some data from an API of LinkedIn with Node.js.
I followed this tutorial https://www.npmjs.com/package/node-linkedin and I wrote this program that is suposed to send data to the console in the callback.
var Linkedin = require('node-linkedin')('XXX', 'XXX', 'http://localhost:3000/oauth/linkedin/callback');
var express = require('express');
var app = express()
// Initialize
var scope = ['r_basicprofile', 'r_emailaddress'];
var linkedinVariables = {
'accessToken': null,
'client': null
}
app.get('/oauth/linkedin', function(req, res) {
// This will ask for permisssions etc and redirect to callback url.
Linkedin.auth.authorize(res, scope);
});
app.get('/oauth/linkedin/callback', function(req, res) {
Linkedin.auth.getAccessToken(res, req.query.code, req.query.state, function(err, results) {
if (err)
return console.error(err);
console.log(results);
linkedinVariables.accessToken = results.access_token;
console.log("ACCESS TOKEN IS ", linkedinVariables.accessToken);
linkedinVariables.client = Linkedin.init(linkedinVariables.accessToken);
/* linkedinVariables.client.people.me(function(err, $in) {
console.log($in);
});*/
/*linkedinVariables.client.people.me('linkedin_id', ['id', 'first-name', 'last-name'], function(err, $in) {
// Loads the profile by id.
console.log($in);
});*/
linkedinVariables.client.people.id('HM3nX8nJD6', function(err, $in) {
console.log($in)
});
// return res.redirect('/');
});
});
app.listen(3000);
Now this program works fine and I get the data with this line:
linkedinVariables.client.people.me('linkedin_id', ['id', 'first-name', 'last-name'], function(err, $in) {
// Loads the profile by id.
console.log($in);
});
which get me a JSON response in my console but following the tutorial I'm suposed to get other informations about companies and people by ID but the response is blank even when I put my own ID to get my own information.
Is there something wrong with my code or is LinkedIn refusing all get requests?

use this
var scope = ['r_basicprofile', 'r_fullprofile', 'r_emailaddress', 'r_network', 'r_contactinfo', 'rw_nus', 'rw_groups', 'w_messages'];
insted of
var scope = ['r_basicprofile', 'r_emailaddress'];

Related

How do I store user action data? i.e userID date/time and action code

The action code being whichever page the user interacts with
please refer to javascript/nodejs code below.
for example at each router.get() if a user is accesing this i need to store his/her userID the dateTime and an action code matching to each router.
router.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/eventlist.html'));
});
router.get('/watchlist', function(request, response) {
response.sendFile(path.join(__dirname + '/watchlist.html'));
});
router.get('/search', function(request, response) {
response.sendFile(path.join(__dirname + '/search.html'));
});
app.post('/search', function(req,res){
let inputContent = req.body.srchterm;
var sequelize = require('./db');
sequelize.query('SELECT * FROM main_table WHERE jobname = :jobname OR jobstream = :jobstream OR workstation = :workstation ',
{ replacements: { jobname: inputContent, jobstream: inputContent, workstation: inputContent }, type: sequelize.QueryTypes.SELECT }
)
.then(function(searchib) {
console.log(searchib);
if (searchib == "") {
res.send(srcharray);
} else {
var srcharray = [];
searchib.forEach(function(items){
console.log('displaying srchadata');
srcharray.push ({workstation: items.workstation,
jobstream: items.jobstream,
jobdate: (items.jobdate.toLocaleString('en-GB', { timeZone: 'GMT'})),
jobname: items.jobname
});
console.log(srcharray);
});
// return response.json(srcharray);
res.send(srcharray);
}
});
});
app.use('/', router);
Create your own middleware (storeUserActionDataMiddleware) to store the data like below:
function storeUserActionDataMiddleware(req, res, next) {
let data = {
userId: 42 /* get userId somehow */,
dateTime: new Date(),
actionCode: `${req.method} ${req.originalUrl}`,
};
console.log({ data });
// Store user action data here
// store(data);
// then execute routes
next();
}
If you want to store the data only for specific router, then use the middleware at the top of the router like:
// only specific router will store user action data
router.use(storeUserActionDataMiddleware);
router.get(/* ... */)
router.post(/* ... */)
Or, if you want to store the data application wide, then use the middleware at the top of the app like:
// all routes will store user action data
app.use(storeUserActionDataMiddleware);
app.use(/* ... */)
app.get(/* ... */)
app.post(/* ... */)
You need to use middleware, and in the middle ware you need to get the token from the user, where you can decode it for user data, and then store this with timestamp

render dynamic value from passport.socketio to jade view

I'm relatively new to node and socketio. What I'm trying to achieve is authenticate users using passport and send total number logged user count to the view. Such that if a logged in user can see the total number of current-logged-in users and if a user logs that the count decreases or increases when someone else log-ins respectively.
Using passport.socketio to access authenticated passport user information from a socket.io connection.
In the callback, I'm storing the username in a mongoose collection, and accordingly on the logout removing the user from the collection. I get a count of the number of users in the model which I need to pass and bind to the view. Jade being the template engine. Below is how my onAuthorizeSuccess callback looks like where I try to pass the count to home.jade.
function onAuthorizeSuccess(data, accept) {
var username = data.user.username;
var User = mongoose.model('loggedusers', userSchema);
var user = new User({
username: username
});
user.save(function (err, data) {
if (err) console.log(err);
else {
console.log('Saved : ', data);
}
User.count({}, function (err, c) {
console.log('Count is ' + c);
app.get('/', function (req, res) {
res.render('home', {
count: {
countData: c
}
});
});
});
});
console.log('successful connection to socket.io ');
accept(); //Let the user through
}
And in the jade view I try to set it using
li Logged Users ---> #{countData.c}
But, countData is undefined in the view.
How should I go about rendering a dynamic value from the server to the view in jade?
Any assistance much appreciated.
Thanks,
Arnab
Your variable is wrong you should use instead #{count} with:
res.render('home', {count: c});
Figured this out.
Made a function to server content over a socket, that the control helps updating on the front-end
module.exports = function (socket) {
setInterval(function () {
var UserSchema = require('mongoose').model('loggedusers');
UserSchema.count({}, function(err, c){
console.log('Count is ' + c);
socket.emit('send:count', {
count: c
});
});
}, 1000);
};
And the angular controller
angular.module('myApp.controllers', []).
controller('AppCtrl', function ($scope, socket) {
socket.on('send:count', function (data) {
$scope.count = data.count;
});
});
and in jade {{count}} and add div.container(ng-controller='AppCtrl') should give the updated count on the front-end.
Arnab

How to keep persistent ftp connection in nodejs

Can you please help me make a connection persistent script. I used jsftp node module to connect to ftp server. What I need to do is to check if the user is already authenticated every time he send a request. Thanks in advance! here's my code:
var Ftp = require('jsftp');
var dumpLog = function (event){
console.log('Code: '+ event.code);
console.log('Message: '+ event.text);
}
var FtpController = {
index : function (req , res) {
res.view('ftp/login');
},
auth : function (req , res){
// Initialize some common variables
var user = req.param('user');
var pass = req.param('pass');
var ftp = new Ftp({
host: req.param('host'),
port: req.param('port') // Defaults to 21
});
ftp.auth( user, pass, function (err , auth_res){
if (err) throw err;
dumpLog(auth_res);
});
res.view('ftp/folder');
},
serve_folder : function(req,res){
res.view('ftp/folder');
},
};
module.exports = FtpController;
Best way to do stuff like this is probably a policy, since you'll want to be able to apply the check to various controllers as you build out your app. Here's what your policy might look like:
// policies/ftpAuthenticated.js
module.exports = function loginToFTP (req, res, next) {
if (req.session.ftpAuthenticated) {
// Onward!
next();
}
else {
// authenticate here (we assume it works in this example)
var success = true;
if (success) {
// Track that the user is connected via ftp for next time
req.session.ftpAuthenticated = true;
// save the connection object
req.session.ftp = theFTPConnectionThing;
next();
}
// if an error occurs, use the default error handler
else {
next( new Error('Sorry, an error occurred authenticating with FTP') );
}
}
}

authentication using node.js and mongodb

Guys I am trying to get myself authenticated and for this I am using node.js and mongo DB.But the thing is that after registarion the user is not able to authenticate himself.Here is my snippet
app.post('/login',function(req,res){
ContactProvider.findAll(function(error, posts) {
var aut = req.body;
if (aut.user == posts.user && aut.pass == posts.pass) {
req.session.name = {name:aut.user};
res.redirect('/home');
} else {
res.send('Bad user/pass');
}
});
});
Below is my snippet for registering the user
app.post('/register',function(req, res) {
var post=req.body;
if(post.pass!=post.cpass) {
res.send("Error:Password doesnt match");
} else {
ContactProvider.save({
user: req.param('user'),
pass: req.param('pass'),
cpass: req.param('cpass'),
email: req.param('email')
}, function(error, docs) {
res.redirect('/');
});
}
});
The ContactProvider is the one below where post provider is a different file where all the mongoose things happen
var ContactProvider = require('./PostProvider').ContactProvider;
var ContactProvider= new ContactProvider();
This is the finone query in the postprovider file
ContactProvider.prototype.findone = function(name,pass, callback) {
Post.findOne({name:name},{pass:pass}, function (err, post) {
callback(null, post);
});
};
Something's seriously wrong with your code ( why you use name posts for an array of ContactProvider? ). You have to search for ContactProvider based on username and password. Something like this:
app.post('/login',function(req,res){
var aut = req.body;
ContactProvider.findOne(
{
user: aut.user,
pass: aut.pass
},
function(err, usr) {
if (error || !usr) {
res.send('Bad user/pass');
} else {
// we have a user, authenticate!
req.session.name = {name:aut.user};
res.redirect('/home');
}
}
);
});
SIDE NOTE: This is a very simple way of authenticating users, but it is not secure at all. You should read more about authentication and security in the internet. Very useful knowledge indeed.
EDIT: There's also an issue with your registration. Your data is stored in post variable, so use it on ContactProvider as well:
// some other code
ContactProvider.save({
user: post.user,
pass: post.pass,
cpass: post.cpass, // no need to store the same thing twice
email: post.email

How can I retrieve values from the uri in express js?

Hello I want to retrieve a value from the uri and use it in my code, for example what would you do if you had something like http://mysite.com/uri1/uri2 and you wanted to get only uri2 ?
app.get("/:uri/:id", function(req, res) {
var uri = req.params.uri,
id = req.params.id;
// do code
});
To clarify :uri and :id are named url segments.
The following with also work
app.get("/rooms/:roomId", function(req, res) {
Rooms.get(req.params.roomId, function(err, rooms) {
res.render("rooms/index", { rooms: rooms });
});
});

Resources