Last active
August 11, 2020 15:04
-
-
Save ryohey/e43cef8b2334ef156f04 to your computer and use it in GitHub Desktop.
Node.js Passport Twitter login and storing user with MongoDB (mongoose)
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
| # launch the mongoDB before running the server | |
| # mongod --dbpath /path/to/db | |
| # ------------------------------ | |
| # passport | |
| # ------------------------------ | |
| passport = require("passport") | |
| TwitterStrategy = require("passport-twitter").Strategy | |
| passport.use new TwitterStrategy( | |
| consumerKey: "TWITTER_CONSUMER_KEY" | |
| consumerSecret: "TWITTER_CONSUMER_SECRET" | |
| callbackURL: "http://localhost:3000/auth-callback/" | |
| , (token, tokenSecret, profile, done) -> | |
| User.findOne {twitter_id: profile.id}, (err, user) -> | |
| return done(null, user) if user | |
| user = new User | |
| user.twitter_id = profile.id | |
| user.name = profile.username | |
| user.screen_name = profile.displayName | |
| user.description = profile._json.description | |
| user.url = profile._json.url | |
| user.save (err) -> | |
| done(err, user) | |
| ) | |
| passport.serializeUser (user, done) -> | |
| done null, user.id | |
| passport.deserializeUser (id, done) -> | |
| User.findById id, (err, user) -> | |
| done err, user | |
| # ------------------------------ | |
| # mongoose | |
| # ------------------------------ | |
| mongoose = require "mongoose" | |
| Schema = mongoose.Schema | |
| ObjectId = Schema.ObjectId | |
| # User | |
| UserSchema = new Schema | |
| twitter_id: Number | |
| name: String | |
| screen_name: String | |
| description: String | |
| url: String | |
| User = mongoose.model "User", UserSchema | |
| mongoose.connect "mongodb://localhost/YOURAPP" | |
| # ------------------------------ | |
| # express | |
| # ------------------------------ | |
| express = require "express" | |
| app = express() | |
| # Config | |
| session = require "express-session" | |
| cookieParser = require "cookie-parser" | |
| bodyParser = require "body-parser" | |
| app.use cookieParser() | |
| app.use bodyParser() | |
| app.use session(secret: "YOURSESSIONSECRET") | |
| app.use passport.initialize() | |
| app.use passport.session() | |
| # Routes | |
| app.get "/", (req, res) -> | |
| res.redirect "/auth" unless req.isAuthenticated() | |
| console.log req.user | |
| res.send "You are already authenticated." | |
| app.get "/auth", passport.authenticate("twitter") | |
| app.get "/auth-callback", passport.authenticate("twitter", | |
| successRedirect: "/" | |
| failureRedirect: "/failure" | |
| ) | |
| app.get "/failure", (req, res) -> | |
| res.send "something wrong" | |
| app.listen 3000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment