示例#1
0
app.get('/auth', function(req, res){
	var redirect_uri = 'https://' + req.get('host') + '/auth';
	if (!req.query.code) {
		var authUrl = graph.getOauthUrl({
			'client_id': process.env.FACEBOOK_APP_ID,
			'redirect_uri': redirect_uri,
			'scope': 'user_friends'
		});
		if (!req.query.error) {
			res.redirect(authUrl);
		} else {
			res.send('access denied');
		}
		return;
	}
	graph.authorize({
		'client_id': process.env.FACEBOOK_APP_ID,
		'redirect_uri': redirect_uri,
		'client_secret': process.env.FACEBOOK_APP_SECRET,
		'code': req.query.code
	}, function (err, facebookRes) {
		res.cookie('token', facebookRes.access_token, {maxAge: facebookRes.expires});
		res.redirect('/');
	});
});
示例#2
0
	app.get('/auth', function (req, res) {
		if (!req.query.code) { // no code available
			if (!req.query.error) {
				var authUrl = graph.getOauthUrl({ 
					client_id: config.client_id, 
					redirect_uri: config.redirect_uri,
				});
				res.redirect(authUrl);
			} else {
				res.writeHead(403);
				res.write("Access Denied");
				res.end();
			}
		} else { // code available, let's get access token
			graph.authorize({
				client_id: config.client_id,
				client_secret: config.client_secret,
				redirect_uri: config.redirect_uri,
				code: req.query.code,
			}, function (err, facebookRes) {
				// facebookRes is a json object with the following properties:
				// access_token (string), expires (string)
				// we probably want to store this in the user session so we can retrieve it via socketio later
				console.log(facebookRes);
				res.redirect('/auth/loggedIn');
			});
		}
	});
示例#3
0
app.get('/auth', function(req, res) {
    if (!req.query.code) {

        var authURL = graph.getOauthUrl({
            'client_id': config.APP_ID,
            'redirect_uri': config.APP_URL + '/auth',
            'scope': config.SCOPE
        });

        if (!req.query.error)
            res.redirect(authURL);

        return;
    }

    graph.authorize({
        'client_id': config.APP_ID,
        'redirect_uri': config.APP_URL + '/auth',
        'client_secret': config.APP_SECRET,
        'code': req.query.code
    }, function (err, fbRes) {
        req.session.access_token = fbRes.access_token;
        res.redirect('/friends');
    });

});
示例#4
0
exports.fbauth = function(req, res) {

  if (!req.query.code) {
    var authUrl = graph.getOauthUrl({
        "client_id":     conf.client_id
      , "redirect_uri":  conf.redirect_uri
      , "scope":         conf.scope
    });
      
    if (!req.query.error) {
      res.redirect(authUrl);
    } else {
      res.send('access denied');
    }
    return;
  }

  // code is set
  // we'll send that and get the access token
  graph.authorize({
      "client_id":      conf.client_id
    , "redirect_uri":   conf.redirect_uri
    , "client_secret":  conf.client_secret
    , "code":           req.query.code
  }, function (err, facebookRes) {
    res.redirect('/fblogin');
  });
        
}//end funct
示例#5
0
      if (!req.query.code) {
         var authUrl = graph.getOauthUrl({
            "client_id": conf.client_id,
            "redirect_uri": conf.redirect_uri,
            "scope": conf.scope
         });

         if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
            res.redirect(authUrl);
         } else { //req.query.error == 'access_denied'
            res.send('access denied');
         }
         return;
      }

      graph.authorize({
         "client_id": conf.client_id,
         "redirect_uri": conf.redirect_uri,
         "client_secret": conf.client_secret,
         "code": req.query.code
      }, function(err, facebookRes) {
         res.redirect('/facebook');
      });

   });
示例#6
0
文件: app.js 项目: osphie/Cheep-Cheep
app.get('/auth/facebook', function(req, res) {

  // we don't have a code yet
  // so we'll redirect to the oauth dialog
  if (!req.query.code) {
  	var authUrl = graph.getOauthUrl({
  		"client_id":     conf.client_id
  		, "redirect_uri":  conf.redirect_uri
  		, "scope":         conf.scope
  	});

    if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
    	res.redirect(authUrl);
    } else {  //req.query.error == 'access_denied'
    res.send('access denied');
}
return;
}

  // code is set
  // we'll send that and get the access token
  graph.authorize({
  	"client_id":      conf.client_id
  	, "redirect_uri":   conf.redirect_uri
  	, "client_secret":  conf.client_secret
  	, "code":           req.query.code
  }, function (err, facebookRes) {
  	res.redirect('/UserHasLoggedIn');
  });


});
示例#7
0
app.get(authBase, function(req, res) {
	if(!req.query.code) {
		var authUrl = graph.getOauthUrl({
			"client_id": conf.client_id,
			"redirect_uri": conf.redirect_uri,
			"scope": conf.scope
		});

		if (!req.query.error) {
			res.redirect(authUrl);
		} else {
			res.send('access denied');
		}
		return;
	}

	graph.authorize({
		"client_id":      conf.client_id,
        "redirect_uri":   conf.redirect_uri,
      	"client_secret":  conf.client_secret,
      	"code":           req.query.code
	}, function(err, facebookRes){
		req.session.code = graph.getAccessToken();
		res.redirect('/');
	});
});
  //passport.authenticate('facebook', {scope: ['email, user_about_me, user_birthday']}),
  function(req, res){
    if (!req.query.code) {
      var authUrl = Facebook.getOauthUrl({
        'client_id': process.env.FACEBOOK_APP_ID,
        //'redirect_uri': 'http://localhost:3000/auth/facebook',
        'redirect_uri': 'http://b7chenglab1.herokuapp.com/auth/facebook',
        //'scope': ['email', 'user_about_me', 'user_photos', 'user_birthday']
      });

      if (!req.query.error) {
        res.redirect(authUrl);
      } else {
        res.send('access denied');
      }
      return;
    }

    Facebook.authorize({
      "client_id": process.env.FACEBOOK_APP_ID,
      //"redirect_uri": 'http://localhost:3000/auth/facebook',
      "redirect_uri": 'http://b7chenglab1.herokuapp.com/auth/facebook',
      "client_secret": process.env.FACEBOOK_APP_SECRET,
      "code": req.query.code
    }, function(err, facebookRes) {
      res.redirect('/UserHasLoggedIn');
    });
  });
示例#9
0
app.get('/auth/facebook', function(req, res) {

  // we don't have a code yet
  // so we'll redirect to the oauth dialog
  if (!req.query.code) {
    var authUrl = graph.getOauthUrl({
        "client_id":     process.env.graph_client_id
     , "redirect_uri":  process.env.redirect_uri
      , "scope":         process.env.scope
    });
    
    if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
      res.redirect(authUrl);
      //console.log("Constructed the OauthURL: "+authURL);
    } else {  //req.query.error == 'access_denied'
      res.send('access denied');
    }
    return;
  }

  // code is set
  // send and get the access token..
  //ONLY after we obtain code from fb
  graph.authorize({
      "client_id":      process.env.graph_client_id
    , "redirect_uri":   process.env.redirect_uri
    , "client_secret":  process.env.graph_client_secret
    , "code":           req.query.code
  }, function (err, facebookRes) {
	console.log("After authorization: " + JSON.stringify(facebookRes))
	console.log("Access Token set: " + graph.getAccessToken())
    res.redirect('/UserHasLoggedIn');
  });
});
示例#10
0
FB_Proxy.prototype.authorize = function (req, res, redirectPath) {
    // we don't have a code yet
    // so we'll redirect to the oauth dialog
    console.log("FB_Proxy.authorize | User not logged in - checking code existence. req.query.code:", req.query.code);
    if (!req.query.code) {
        console.log("FB_Proxy.authorize | Code not found! Sending request for new one...");
        var authUrl = graph.getOauthUrl({
            "client_id": this.configuration.client_id, "redirect_uri": this.configuration.redirect_uri, "scope": this.configuration.scope
        });

        if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
            console.log("FB_Proxy.authorize | Access to app successful. Redirecting to: ", authUrl);
            res.redirect(authUrl);
        } else {  //req.query.error == 'access_denied'
            console.log("FB_Proxy.authorize | User denied access to app!");
            res.send('access denied');
        }
        return;
    }

    // code is set
    // we'll send that and get the access token
    graph.authorize({
        "client_id": this.configuration.client_id, "redirect_uri": encodeURI(this.configuration.redirect_uri), "client_secret": this.configuration.client_secret, "code": req.query.code
    }, function (err, facebookRes) {
        if (err) {
            console.log("FB_Proxy.authorize | err: ", err);
        }
        console.log("FB_Proxy.authorize | Received access_token. Setting token and redirecting to: ", redirectPath);
        graph.setAccessToken(facebookRes.access_token);
        res.redirect(redirectPath);
    });
};
示例#11
0
function authorizeFacebook(options, cb) {
	graph.authorize({
		client_id: options.client_id || config.client_id,
		client_secret: options.client_secret || config.client_secret,
		redirect_uri: options.redirect_uri,
		code: options.code
	}, cb);
}
示例#12
0
module.exports.oauth = function(req,res) {
  if (!req.query.code) {
    var authUrl = graph.getOauthUrl({
      'client_id': config.facebook.appId,
      'redirect_uri': config.facebook.redirectUri,
      'scope': 'email, user_about_me, user_birthday, user_location'
    });
    if (!req.query.error) {
      return res.redirect(authUrl);
    } else {
      return res.status(400).json({message: 'Access Denied'});
    }
  }
  graph.authorize({
    'client_id': config.facebook.appId,
    'client_secret': config.facebook.secret,
    'redirect_uri': config.facebook.redirectUri,
    'code': req.query.code
  }, function(err, fb) {
    if (err) {
      return res.status(400).json(err);
    } else {
      graph.setAccessToken(fb.access_token);
      graph.get('me', function(err, me) {
        if (err || !me) return res.status(400).json(err);
        var linkAccount = {
          authData: {
            facebook: {
              id: me.id,
              access_token: fb.access_token,
              expiration_date: new Date(Date.now() + (~~fb.expires)).toISOString()
            }
          },
          _headers: {
            'X-Parse-Master-Key': config.parse.masterKey
          }
        };
        proxy.request({
          url: '/parse/users' + (req.user ? '/' + req.user.id : ''),
          method: (req.user ? 'put' : 'post'),
          body: linkAccount
        }, function(err, data) {
          if (err || data.statusCode != 200) return res.status(400).json(err);
          if (!req.user) {
            req.logIn(data.body, function(err) {
              if (err) return res.status(400).json(err);
              req.session.passport.user.token = data.body.sessionToken;
              req.session.passport.user.id = data.body.objectId;
              return res.status(data.statusCode).json(_.extend({message: 'You have been logged in.'}, data.body));
            });
          } else {
            return res.status(data.statusCode).json(_.extend({message: 'You have been logged in.'}, data.body));
          }
        });
      });
    }
  });
};
示例#13
0
app.get('/auth/facebook', function(req, res) {
  req.session.user = false;
  if (!req.query.code) {

    var authUrl = graph.getOauthUrl(conf.fb);
    if (!req.query.error) {
      res.redirect(authUrl);
    } else {
      res.render('auth/denied', {
        layout: "layout-mini"
      });
    }
    return;
  }

  graph.authorize({
      "client_id":      conf.fb.client_id
    , "redirect_uri":   conf.fb.redirect_uri
    , "client_secret":  conf.fb.client_secret
    , "code":           req.query.code
    , "scope":          conf.fb.scope
  }, function (err, facebookRes) {
    if (facebookRes.access_token) {
      var hashed_token = crypto.createHash('md5').update(facebookRes.access_token).digest("hex");

      graph.get('me', function(err, data) {
        if (data) {
          var user = {
            hash: hashed_token,
            access_token: facebookRes.access_token,
            email: data.email,
            name: data.name,
            link: data.link
          };

          db_users.set(hashed_token, JSON.stringify(user));
          req.session.user = user;

          db_friends.get("generating:" + user.hash, function(err, reply) {
            if (!reply) {
              db_friends.del(user.hash);
              resque.enqueue('fb', 'generate', [user.hash]);
              db_friends.set("generating:" + user.hash, true);
            }
          });

          res.redirect('/friends');
          return;
        } else {
          res.redirect('/');
          return;
        }
      });
    }
  });
});
示例#14
0
      server.get('/auth/facebook', function (req, res) {
         var redirectTo = req.query.r || req.session.authCallback || '/256';
         var redirect = "http://" + req.headers.host + "/auth/facebook";
         // The Facebook app is configured to send a code= parameter in its callback
         // to this function, so if it doesn't exist, show the OAuth dialog.
         if (!req.query.code) {
            req.session.authCallback = redirectTo;
            var authUrl = graph.getOauthUrl({
               "client_id": conf.FB_APPID,
               "redirect_uri": redirect,
               "scope": conf.scope
            });

            if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
               res.redirect(authUrl);
            } else {  //req.query.error == 'access_denied'
               res.send('access denied');
            }
            return;
         }

         // code is set
         // we'll send that and get the access token

         graph.authorize({
            "client_id": conf.FB_APPID,
            "redirect_uri": redirect,
            "client_secret": conf.FB_SECRET,
            "code": req.query.code
         }, function (err, result) {
            if(!err){
               req.session.fbToken = result.access_token;
               graph.get('/me',function(err,fbUser){
                  if(err){
                     return res.send("failed to query FB user with access token");
                  }
                  db.findUser(fbUser.id).then(function(user){
                     if(user){
                        req.session.userId = user._id.toString();
                        return res.redirect(redirectTo);
                     }
                     user = {
                        facebookId: fbUser.id,
                        name: fbUser.name,
                        email: fbUser.email
                     };
                     db.createUser(user).then(function(result){
                        req.session.userId = result._id.toString();
                        res.redirect(redirectTo);
                     });
                  });
               });
            }
         });
      });
示例#15
0
app.get('/auth/facebook', function(req, res) {
  // we don't have a code yet
  // so we'll redirect to the oauth dialog
  if (!req.query.code) {
    var authUrl = graph.getOauthUrl({
        "client_id":     conf.client_id
      , "redirect_uri":  conf.redirect_uri
      , "scope":         conf.scope
    });

    if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
      res.redirect(authUrl);
    } else {  //req.query.error == 'access_denied'
      res.send('access denied');
    }
    return;
  }
  graph.authorize({
      "client_id":      conf.client_id
    , "redirect_uri":   conf.redirect_uri
    , "client_secret":  conf.client_secret
    , "code":           req.query.code
  }, function (err, facebookRes) {
    // res.redirect('/UserHasLoggedIn');
    function errResp(e, r) {
      if (e) {
        console.log(e);
      }
      else {
        console.log(r);
      }
    }
    var params = { fields: 'id, name, first_name, middle_name, last_name, gender, locale, languages, link,'
                         + 'username, age_range, third_party_id, installed, timezone, updated_time,'
                         + 'verified, bio, birthday, cover, currency, devices, education, email, hometown,'
                         + 'interested_in, location, political, payment_pricepoints, favorite_athletes,'
                         + 'favorite_teams, picture, quotes, relationship_status, religion, security_settings,'
                         + 'significant_other, video_upload_limits, website, work' 
                 };
    graph.get("me", params,  function(err, resp) {
      // errResp(err, resp);
      var query = { 'user.first_name': resp.first_name }
      User.findOneAndUpdate(query, { user: resp, date: new Date() }, function (er, usr) {
        if (!usr) {
          var user = new User ({ user: resp });
          user.save(function(err) {
            if (err) console.log(err);
          });        
        }
        res.redirect('/')
      })
    });;
  });
});
示例#16
0
   function(req,res){
     graph.setAccessToken(FB_ACCESS_TOKEN);
     graph.authorize({
         "client_id":      conf.client_id
       , "redirect_uri":   conf.redirect_uri
       , "client_secret":  conf.client_secret
       , "code":           req.query.code
     }, function (err, facebookRes) {
               exports.graph = graph;
       res.redirect('/UserHasLoggedIn');
   });
 });
 return new rsvp.Promise(function (fulfil, reject) {
     console.log('getting token from facebook...');
     console.log('gat: ' + fb.getAccessToken());
     fb.authorize({
         client_id: config.client_id,
         client_secret: config.client_secret,
         redirect_uri: config.redirect_uri,
         code: code
     }, function (err, fbRes) {
         if (err) {
             reject(err);
         }
         console.log(fbRes);
         fulfil(fbRes);
     });
 });
示例#18
0
	function getSocialFeed (source, sourceId, cb) {
		switch (source) {
			case 'facebook':
				facebook.authorize({
				      "client_id":      fbconfig.id
				      , "client_secret":  fbconfig.secret
				      , "grant_type":     "client_credentials"
				    }, 
				    function (authErr, authRes){
					    if (!authErr) {
					    	facebook.get(sourceId + "/feed", function (err, data){
					    		if (err) {
					    			logError(err);
					    			data = null;
					    		}
					    		cb(data);
							});
					    }else{
					    	logError(authError);
					    	cb(null);
					    }
				});
				break;
			case 'twitter':
				twitter.get( 'statuses/user_timeline', { screen_name: sourceId }, function( data, err, status ){
					if (err instanceof Error) {
						logError(err);
						data = null;
					}
					cb(data);
				} );
				break;
			case 'youtube':
				youtube.feeds.videos({q:sourceId}, function (err, data) {
					if (err instanceof Error) {
						logError(err);
						data = null;
					}
					cb(data);
				});
				break;
			default:
				cb();
				break;
		}
	}
示例#19
0
  auth: function(req, res) {

    var parsedUrl = url.parse(req.url, true);

    if (!parsedUrl.query.code) {
      var authUrl = graph.getOauthUrl({
        'client_id': config.facebook.client_id,
        'redirect_uri': config.facebook.redirect_uri,
        'scope': config.facebook.scope
      });

      if (!parsedUrl.query.error) { //checks whether a user denied the app facebook login/permissions
        res.writeHead(302, { 'Location': authUrl });
        res.end();
      } else {  //req.query.error == 'access_denied'
        log.error('Facebook login error: ', parsedUrl.query.error);
        res.send('access denied');
      }
    } else {
      // code is set
      // we'll send that and get the access token
      graph.authorize({
        'client_id': config.facebook.client_id,
        'client_secret': config.facebook.client_secret,
        'redirect_uri': config.facebook.redirect_uri,
        'code': parsedUrl.query.code
      }, function (err, facebookRes) {
        if(err) {
          log.error(err);
          res.writeHead(400);
          res.write(err);
          res.end();
        }
        log.info('Facebook access token: ', facebookRes.access_token, '\n');
        graph.setAccessToken(facebookRes.access_token);
        events.emit('hasFbToken');
        res.writeHead(201);
        res.end();
      });
    }

  },
function auth(req, res) {
	// we don't have a code yet
	// so we'll redirect to the oauth dialog
	if(!req.query.code) {
		var authUrl = graph.getOauthUrl({
			"client_id": conf.client_id,
			"redirect_uri": conf.redirect_uri,
			"scope": conf.scope
		});

		if(!req.query.error) { //checks whether a user denied the app facebook login/permissions
			res.redirect(authUrl);
		} else { //req.query.error == 'access_denied'
			res.send('access denied');
		}
		return;
	}

	// code is set
	// we'll send that and get the access token
	graph.authorize({
		"client_id": conf.client_id,
		"redirect_uri": conf.redirect_uri,
		"client_secret": conf.client_secret,
		"code": req.query.code
	}, function(err, facebookRes) {
		console.log(facebookRes.access_token);
		access_token = facebookRes.access_token;

		graph.get("/me", function(err, obj) {

			var link = obj.id;
			authRepo.add(link, access_token, function(err, obj) {
				if(err) console.log(err)
				else console.log("saved auth");
				return res.redirect('/')
			})

		})
	});
}
示例#21
0
文件: fb.js 项目: rhansby/marissafy
 login: function(req,res) {
   if (!req.query.code) {
     var authUrl = graph.getOauthUrl({
       "client_id": conf.fb().client_id,
       "redirect_uri": conf.fb().redirect_uri
     });
     if (!req.query.error) {
       res.redirect(authUrl);
     } else {
       res.send('access denied');
     }
     return;
   }
   graph.authorize({
     "client_id": conf.fb.client_id,
     "redirect_uri": conf.fb.redirect_uri,
     "client_secret": conf.fb.client_secret,
     "code": req.query.code
   }, function (err, facebookRes) {
     res.redirect('/?auth=true&auth_type=fb');
   });
 }
示例#22
0
module.exports = function(req, res) {
  if (!req.query.code) {
    var authUrl = graph.getOauthUrl({
      client_id: config.client_id,
      redirect_uri: 'http://local.host:' + config.port + '/getAccessToken',
      scope: config.scope
    });

    if (!req.query.error) res.redirect(authUrl);
    else res.send('access denied');
    return ;
  }

  graph.authorize({
    client_id:      config.client_id,
    redirect_uri:   'http://local.host:' + config.port + '/getAccessToken',
    client_secret:  config.client_secret,
    code:           req.query.code
  }, function (err, facebookRes) {
    res.send(facebookRes);
  });
}
示例#23
0
exports.fb_login = function (code, done) {
    logger.debug('code',code);
    graph.authorize({
        "client_id": fb_config.client_id
        , "redirect_uri": fb_config.redirect_uri
        , "client_secret": fb_config.client_secret
        , "code": code
    }, function (err, facebookRes) {
        if (err) {
            logger.error('err', err);
            done(err)
        } else {
            console.log('test', facebookRes);
            console.log('test', facebookRes.access_token);
            var token = facebookRes.access_token;
            graph.get("me", function (err, res) {
                logger.debug('res', res);
                done(null, res, token)

            });
        }
    });
}
示例#24
0
app.get('/auth/facebook', function(req, res) {
	// we don't have a code yet
	// so we'll redirect to the oauth dialog
	if (!req.query.code) {
		var authUrl = graph.getOauthUrl({
			"client_id":     process.env.FB_APPID
			, "redirect_uri":  process.env.FB_ROOTURL
			, "scope":         process.env.FB_SCOPE
		});

		if (!req.query.error) { //checks whether a user denied the app facebook login/permissions
			res.redirect(authUrl);
		} 
		else {  //req.query.error == 'access_denied'
			res.send('access denied');
		}

		console.log("return? also what is code");
		console.log(req.query.code);

		return;
	}

	console.log(req.query.code);
	// code is set
	// we'll send that and get the access token
	graph.authorize({
		"client_id":      process.env.FB_APPID
		, "redirect_uri":   process.env.FB_ROOTURL
		, "client_secret":  process.env.FB_APPSECRET
		, "code":           req.query.code
	}, function (err, facebookRes) 
	{
		console.log("login success?");
		res.redirect('/loggedin');
	});
});
示例#25
0
文件: member.js 项目: suro95/reevio
router.get('/FbCallback/:video_name', function(req, res, next) {
    var get=req.params;

    graph.authorize({
        "client_id":      '507341756125702'
        , "redirect_uri":   'http://localhost:3001/member/FbCallback/' + get.video_name
        , "client_secret":  'a687a2d85e59aca8b1ffa09ef62673bc'
        , "code":           req.query.code
    }, function (err, facebookRes) {
        if(err) res.redirect('/video-designs');

        graph.setAccessToken(facebookRes.access_token);
        var wallPost = {
            message: "I'm gonna come at you like a spider monkey, chip!"
        };
        graph.post("/feed", wallPost, function(err, res) {
            // returns the post id
        });

        res.redirect('/video-designs');
        res.end();
    });

});
示例#26
0
app.get('/auth/facebook', function(req, res) {
	if (!req.query.code) {
		var authUrl = graph.getOauthUrl({
			'client_id': process.env.facebook_client_id,
			'redirect_uri': 'http://localhost:3000/auth/facebook',
			'scope': 'user_about_me'//you want to update scope to what you want in your app
		});

		if (!req.query.error) {
			res.redirect(authUrl);
		} else {
			res.send('access denied');
		}
		return;
	}
	graph.authorize({
		'client_id': process.env.facebook_client_id,
		'redirect_uri': 'http://localhost:3000/auth/facebook',
		'client_secret': process.env.facebook_client_secret,
		'code': req.query.code
	}, function( err, facebookRes) {
		res.redirect('/UserHasLoggedIn');
	});
});
示例#27
0
app.get('/auth/facebook', function(req, res) {
	if (!req.query.code) {
		var authUrl = graph.getOauthUrl({
			'client_id': process.env.facebook_client_id,
			'redirect_uri': 'http://cogs121-ass2.herokuapp.com/auth/facebook',
			'scope': 'user_about_me, user_likes, user_friends'//you want to update scope to what you want in your app
		});

		if (!req.query.error) {
			res.redirect(authUrl);
		} else {
			res.send('access denied');
		}
		return;
	}
	graph.authorize({
		'client_id': process.env.facebook_client_id,
		'redirect_uri': 'http://cogs121-ass2.herokuapp.com/auth/facebook',
		'client_secret': process.env.facebook_client_secret,
		'code': req.query.code
	}, function( err, facebookRes) {
		res.redirect('/facebook');
	});
});
示例#28
0
/**
 * Routes requiring Facebook interactions will first be run through this function to ensure we
 * have an active access_token with which to make requests to Facebook.
 */
function checkFbSession(req, res, next) {

    // First we look for the cookie set by Facebook when a user logs in and authorises an app.
    // The format of the cookie name is 'fbsr_' followed by the Application ID
    var fbCookie = req.cookies['fbsr_' + config.client_id],
        parsedToken, base64data;

    // If there's no Facebook cookie, the user is not authorized, so we shouldn't proceed further.
    if (!fbCookie) {
        handleError('No Facebook cookie detected.', null, req, res);
        return;
    }

    // The cookie is the same format as a Facebook signed request:
    // https://developers.facebook.com/docs/authentication/signed_request/
    base64data = fbCookie.split('.', 2);
    parsedToken = JSON.parse(new Buffer(base64data[1], 'base64').toString('ascii'));

    // If we already have a Facebook session saved, and the User ID and Auth Code match those
    // that are in the Facebook cookie, we can assume we're successfully authenticated with
    // Facebook, and proceed to the next step in the route.
    //
    // We check the user ID and code are the same in case the user has logged out and in on the
    // client side (invalidating the server session) or if there is now a different user logged in
    // on the client side.
    if (req.session.fb && req.session.fb.user_id == parsedToken.user_id && req.session.fb.code == parsedToken.code) {
        graph.setAccessToken(req.session.fb.access_token);
        next();
    } else {

        // If we don't have a Facebook session saved locally, we'll need to swap the code in our
        // Facebook cookie for an access_token.
        console.log("Found Facebook cookie. Swapping Auth code for access_token...");

        // Save the Facebook user ID and auth code to the session so we can check they are valid
        // in subsequent requests.
        req.session.fb = {
            user_id: parsedToken.user_id,
            code: parsedToken.code
        };

        // Make the call to Facebook to swap our Auth token for an access_token
        graph.authorize({
            "redirect_uri":   "", // Facebook JS SDK sets redirect_uri to ''
            "client_id":      config.client_id,
            "client_secret":  config.client_secret,
            "code":           parsedToken.code
        }, function(err, facebookRes) {

            if (err) {
                handleError('Error obtaining Facebook access_token.', facebookRes, req, res);
                return;
            }

            console.log("Successfully obtained Facebook access_token.");

            // Save the access token to the session, and activate it for the current request.
            req.session.fb.access_token = facebookRes.access_token;
            graph.setAccessToken(facebookRes.access_token);
            next();
        });
    }
}