Created
March 24, 2019 08:02
-
-
Save potato4d/55641332ec306a37eb35060bfd318792 to your computer and use it in GitHub Desktop.
TypeScript x Express で雑に Passport で Twitter 認証するときに使い回すやつ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express, { Request, Response } from 'express' | |
import session from 'express-session' | |
import passport from 'passport' | |
import cookieParser from 'cookie-parser' | |
import { inspect } from 'util' | |
import { Strategy } from 'passport-twitter' | |
const app = express() | |
app.use(cookieParser()) | |
app.use( | |
session({ | |
secret: '__credential', | |
resave: true, | |
saveUninitialized: true | |
}) | |
) | |
app.use(passport.initialize()) | |
app.use(passport.session()) | |
passport.use( | |
new Strategy( | |
{ | |
consumerKey: `${process.env.TWITTER_CK}`, | |
consumerSecret: `${process.env.TWITTER_CS}`, | |
callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback' | |
}, | |
(token: any, tokenSecret: any, profile: any, done: any) => { | |
;(passport.session as any).id = profile.id | |
profile.twitter_token = token | |
profile.twitter_token_secret = tokenSecret | |
process.nextTick(() => done(null, profile)) | |
} | |
) | |
) | |
passport.serializeUser((user: any, done: any) => { | |
done(null, user) | |
}) | |
passport.deserializeUser((user: any, done: any) => { | |
done(null, user) | |
}) | |
app.get('/', async (req: Request, res: Response) => { | |
if (req.user) { | |
res.send(`<pre>${inspect(req.user)}</pre>`) | |
} else { | |
res.redirect('/auth/twitter') | |
} | |
}) | |
app.get('/auth/twitter', passport.authenticate('twitter')) | |
app.get( | |
'/auth/twitter/callback', | |
passport.authenticate('twitter', { failureRedirect: '/?auth_failed' }), | |
(req: any, res: any) => { | |
res.redirect('/') | |
} | |
) | |
app.listen(3000, '0.0.0.0', () => { | |
console.log('http://127.0.0.1:3000') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment