Nomination part 7 - connecting to facebook

Version en español

This post is part of the series about creating an app with node.js, express for Facebook

Lets connect to fcebook to get the user information and store in session the tokens for request, we will only save the userid and name in the db.

For this we will use a module called "facebook-j", this module its already installed, so lets add it to our "app.js" at the beginning of the file with the other modules like this:

var fb = require('facebook-js');

And then lets add some routes, first for the login that will send to the facebook page for the user login or if its already logged in he must accept the app in order to let the app get information from the profile

     * Login page
    app.get('/login', function(req, res){
        log.notice('trying to login:' + new Date());
            client_id: '264644053569277', //put the client id
            redirect_uri: 'http://nomi-nation.pinguxx.c9.io/auth/fb', //cambiar si es necesario
            scope: 'offline_access,publish_stream,read_stream'
     * FB return
    app.get('/auth/fb', function(req, res){
        log.notice('response from fb: ' + new Date());
        fb.getAccessToken('264644053569277', //clientid
            '76ded2bf195073ce7a183a1ef1cd0b8a', //app secret
            'http://nomi-nation.pinguxx.c9.io/auth/fb', //cambiar si es necesario
            function (error, access_token, refresh_token) {
                if (error){
                    log.debug('error getting access token:' + error);
                    throw new Error('Error getting the acccess token');
                log.notice('trying to get the tokens:' + new Date());
                req.session.user = {};
                req.session.user.access_token = access_token;
                req.session.user.access_token_secret = refresh_token;
                fb.apiCall('GET', '/me/', {access_token: req.session.user.access_token}, function(error, response, body){
                    if (error){
                        log.debug('error getting user info:' + error);
                        throw new Error('Error getting user information');
                    log.notice('getting info from user:' + body.id);
                    req.session.user.name = body.username;
                    req.session.user.id = body.id;

Line 4-5: got the login path and log that someone is trying to access

6: we redirect to whatever Facebook api returns

7: add the client id that we got from Facebook, if you need help creating and app in Facebook let me know in the comments section

8: the "redirect_uri" its where we are going to return once the user has accepted our ap

9: the scope of our app, meaning what things are going to see from the app, we will need publish and read, we may not need to read it but for know lets leave it like that, the offline access is to read the user profile.

15 y 16: path is needed to put where to return and then we log whatever Facebook returns

17-21: we ask an access token to Facebook, we pass the "client_id" and the secrecy key of the app

22-25: if something bad happens lets report it

26-30: logging and storing in session the access token and we make another call to the api but this time to get the user information from "/me", we send the access token that we just got

31-38: check errors again, log and save the name and we redirect to the "/dashboard" path
Bien para manejar la ruta y las próximas rutas de dashboard usaremos otro archivo que le llamaremos dashboard.js en este por el momento solo declararemos la ruta principal

Lets create a file called "dashboard.js" to hold all the paths for the actual app, it will look like this:

 * Rutas dashboard
module.exports = function(app, log){

     * Dashboard landing
    app.get('/dashboard', function(req, res){
        log.notice('landed on dashboard user: ' +
            req.session.user.id + ' on: ' + new Date() );
        res.render('dashboard', { user: req.session.user });

Simple, just log out and send the dashboard template with the user object

lets add this dashboard routes to the "app.js" just like before, add it after index.js

require('./routes/dashboard')(app, log);

OK, our new view will be called "dashboard.jade" and right now we will show only the data that we store from Facebook

.username #{t('dashboard.user_name')}: #{user.name}
.userid #{t('dashboard.user_id')}: #{user.id}

Using our i18next module we add the name and the id, so we just need to update the "translation.json" for all the languages

        "user_name" : "Nombre del usuario",
        "user_id" : "Id del usuario"

And we are set, our app is now connected to Facebook and downloading info from there, in later posts you will see how to get other information

Fork the code in github:


No comments:

Post a Comment