This repository has been archived by the owner on Mar 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwitter.js
105 lines (90 loc) · 2.83 KB
/
twitter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const logger = require('./logger')
const emailer = require('./email')
const passport = require('passport')
const TwitterStrategy = require('passport-twitter').Strategy
// setup auth handling
module.exports = function (app, User) {
// Configure Passport authenticated session persistence.
passport.serializeUser(
function (user, cb) {
logger.debug(`serializing: ${user.displayName}`)
cb(null, user._id)
})
passport.deserializeUser(
function (id, cb) {
logger.debug(`deserializing: ${id}`)
User.findById(id, cb)
})
passport.use(new TwitterStrategy(
{
consumerKey: process.env.TWITTER_CONSUMER_KEY,
consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
userProfileURL: 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true',
callbackURL: process.env.TWITTER_CALLBACK_URL,
},
function (token, tokenSecret, profile, cb) {
logger.debug(`authenticating: ${profile.id}`)
// get user email if exists
let email = null
if (profile.emails && profile.emails.length > 0) {
email = profile.emails[0].value
}
// create user and save to db
const user = {
displayName: profile.displayName,
primaryEmail: email,
profileImageUrl: profile._json.profile_image_url_https,
twitter: {
id: profile.id,
accessLevel: profile._accessLevel,
token: token,
secret: tokenSecret,
},
}
User.findOne({ 'twitter.id': profile.id }).exec(function (err, res) {
if (err) {
return cb(err, null)
}
else {
if (!res && email) {
// new user - send onboarding
emailer(email, profile.displayName)
.then(() => logger.debug('sent onboarding email'))
.catch(err => logger.error(`emailer error : ${err}`))
}
User.findOrCreate(user, function (err, user) {
logger.info('created or updated a user')
return cb(err, user)
})
}
})
}
))
logger.info('inited twitter passport')
// initialize passport and restore authentication state, if any, from the session.
app.use(passport.initialize())
app.use(passport.session())
// path handlers
app.get(
'/auth/twitter',
passport.authenticate('twitter'))
app.get(
'/auth/twitter/callback',
passport.authenticate(
'twitter',
{ failureRedirect: '/login' }
),
function (req, res) {
// Successful authentication, redirect home.
logger.debug(`succesful authentication for: ${req.user.displayName}`)
res.redirect('/')
})
logger.info('setup twitter passport routes')
app.get(
'/logout',
function (req, res) {
req.logout()
res.redirect('/login')
})
logger.info('setup logout route')
}