Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Strategy as FacebookStrategy } from 'passport-facebook';
- import db from 'api/db';
- const { User, Auth } = db.App;
- export async function facebookPassportCallback(req, accessToken, refreshToken, profile, done) {
- try {
- const [auth, created] = await Auth.findOrCreate({
- where: {
- provider: profile.provider,
- providerId: profile.id
- }
- });
- let user = req.user;
- if (!user) {
- user = await User.findOne({ where: { email: profile.emails[0].value } });
- if (!user) {
- user = await User.create({
- email: profile.emails[0].value,
- nick: profile.displayName || null,
- birthday: null, // TODO: Use age_range instead of birthday
- photo: (profile.photos && profile.photos.hasOwnProperty('0') && profile.photos[0].value) || null,
- gender: profile.gender || null,
- password: null
- });
- }
- }
- if (created) {
- await user.addAuth(auth);
- }
- await auth.update({ accessToken, refreshToken });
- if (!user.email) {
- user.email = profile.emails[0].value;
- await user.save();
- }
- done(null, user);
- } catch (err) {
- done(err, null);
- }
- }
- export default function facebook(app, passport, config) {
- passport.use(new FacebookStrategy({
- clientID: config.passport.facebook.appId,
- clientSecret: config.passport.facebook.appSecret,
- callbackURL: config.passport.facebook.callbackUrl,
- enableProof: true,
- scope: ['email', 'public_profile', 'user_friends'],
- profileFields: ['id', 'email', 'displayName', 'age_range', 'gender', 'photos'],
- passReqToCallback: true,
- }, facebookPassportCallback));
- app.get('/auth/facebook',
- passport.authenticate('facebook', { display: 'popup' }),
- () => {
- // The request will be redirected to Facebook for authentication, so this
- // function will not be called.
- });
- app.get('/auth/facebook/callback',
- passport.authenticate('facebook', config.passport.facebook));
- app.get('/auth/facebook/loginSuccess', (req, res) => {
- // res.send(JSON.stringify(req.user) + '<script language="javascript">window.close();</script>');
- res.send('<script language="javascript">window.close();</script>');
- });
- app.get('/auth/facebook/loginFail', (req, res) => {
- res.send('<script language="javascript">window.close();</script>');
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement