Advertisement
Guest User

Untitled

a guest
Jul 5th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. import { Strategy as FacebookStrategy } from 'passport-facebook';
  2. import db from 'api/db';
  3.  
  4. const { User, Auth } = db.App;
  5.  
  6. export async function facebookPassportCallback(req, accessToken, refreshToken, profile, done) {
  7. try {
  8. const [auth, created] = await Auth.findOrCreate({
  9. where: {
  10. provider: profile.provider,
  11. providerId: profile.id
  12. }
  13. });
  14.  
  15. let user = req.user;
  16.  
  17. if (!user) {
  18. user = await User.findOne({ where: { email: profile.emails[0].value } });
  19.  
  20. if (!user) {
  21. user = await User.create({
  22. email: profile.emails[0].value,
  23. nick: profile.displayName || null,
  24. birthday: null, // TODO: Use age_range instead of birthday
  25. photo: (profile.photos && profile.photos.hasOwnProperty('0') && profile.photos[0].value) || null,
  26. gender: profile.gender || null,
  27. password: null
  28. });
  29. }
  30. }
  31.  
  32. if (created) {
  33. await user.addAuth(auth);
  34. }
  35.  
  36. await auth.update({ accessToken, refreshToken });
  37.  
  38. if (!user.email) {
  39. user.email = profile.emails[0].value;
  40. await user.save();
  41. }
  42.  
  43. done(null, user);
  44. } catch (err) {
  45. done(err, null);
  46. }
  47. }
  48.  
  49. export default function facebook(app, passport, config) {
  50. passport.use(new FacebookStrategy({
  51. clientID: config.passport.facebook.appId,
  52. clientSecret: config.passport.facebook.appSecret,
  53. callbackURL: config.passport.facebook.callbackUrl,
  54. enableProof: true,
  55. scope: ['email', 'public_profile', 'user_friends'],
  56. profileFields: ['id', 'email', 'displayName', 'age_range', 'gender', 'photos'],
  57. passReqToCallback: true,
  58. }, facebookPassportCallback));
  59.  
  60. app.get('/auth/facebook',
  61. passport.authenticate('facebook', { display: 'popup' }),
  62. () => {
  63. // The request will be redirected to Facebook for authentication, so this
  64. // function will not be called.
  65. });
  66.  
  67. app.get('/auth/facebook/callback',
  68. passport.authenticate('facebook', config.passport.facebook));
  69.  
  70. app.get('/auth/facebook/loginSuccess', (req, res) => {
  71. // res.send(JSON.stringify(req.user) + '<script language="javascript">window.close();</script>');
  72. res.send('<script language="javascript">window.close();</script>');
  73. });
  74.  
  75. app.get('/auth/facebook/loginFail', (req, res) => {
  76. res.send('<script language="javascript">window.close();</script>');
  77. });
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement