Diego
Diego

Reputation: 964

How to authenticate with github with Node and Express

I have my Node Example using Express and node-github. I'm requesting the tokens so the user can authorize the app for creating a gist. The issue I'm having is that the gist are being created with like an anonymous user.

If I removed the github.authenticate from the code gist are being created in an anonymous way. If I leave the github.authenticate no gist are created and no error is being display.

I assume that issue consist on where I have to located the github.authenticate.

I have my callback

app.get('/auth/github/callback',function (req, res) {

  var url = Url.parse(req.url);
    var path = url.pathname;
    var query = querystring.parse(url.query);

  var code = req.query.code;
  console.log('/callback');

  OAuth2.AuthCode.getToken({
    code: code,
    redirect_uri: 'http://127.0.0.1:3000/auth/github/callback'
  }, saveToken);

  github.authenticate({
    type: "oauth",
    token: accessToken
  });

  res.redirect('home');
  function saveToken(error, result) {
    if (error) { console.log('Access Token Error', error.message); }
    accessToken = OAuth2.AccessToken.create(result);
  }
});

And this is my post. Here the gist is created.

app.post('/test', function(req, res){
    github.gists.create({
      "description": "the description for this gist",
      "public": true,
      "files": {
        "TEST_2.md": {
          "content": "<html><h1>This is a Test!</h1><b>Hello</b></html>"
        }
      }
    }, function(err, rest) {
      console.log(rest);
      res.render('/');
    });
});

I have been trying to look for an similar question but just found this one question and the answers where to use the modules I'm using.

Upvotes: 5

Views: 3846

Answers (2)

Pankaj
Pankaj

Reputation: 237

I did the same in below way:

let express = require('express'),
    app = express(),
    passport = require('passport'),
    session = require('express-session');
let GithubStrategy = require('passport-github').Strategy;

/***************************************************************
 *********** Github Configuration setup...
 ***************************************************************/

passport.use(new GithubStrategy({
    clientID: " APP CLIENT ID",
    clientSecret: "APP CLIENT SECRET",
    callbackURL: "http://localhost:3000/auth/github/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // we will just use the profile object returned by GitHub
    return done(null, profile);
  }
));

// Express and Passport Session
app.use(session({secret: "jsonworldbestplaformforjsframeworks"}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
    // placeholder for custom user serialization
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    // placeholder for custom user deserialization.
    // maybe you are getoing to get the user from mongo by id?

    done(null, user); // null is for errors
});

// we will call this to start the GitHub Login process
app.get('/auth/github', passport.authenticate('github'));

// GitHub will call this URL
app.get('/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/' }),
  function(req, res) {
      res.redirect('/');
  });

app.get('/', function (req, res) {
    var html = "<ul>\
      <li><a href='/auth/github'>GitHub</a></li>\
      <li><a href='/logout'>logout</a></li>\
    </ul>";

    // data fetched from github server
    if (req.isAuthenticated()) {
      html += "<p>authenticated as user:</p>"
      html += "<pre>" + JSON.stringify(req.user, null, 4) + "</pre>";
    }

    res.send(html);
});

app.get('/logout', function(req, res){
    req.logout();
    res.redirect('/');
});

// Simple route middleware to ensure user is authenticated.
//  Use this route middleware on any resource that needs to be protected.  If
//  the request is authenticated (typically via a persistent login session),
//  the request will proceed.  Otherwise, the user will be redirected to the login page.

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/')
}

app.get('/protected', ensureAuthenticated, function(req, res) {
    res.send("acess granted");
});

app.listen(3000, function () {
    console.log('App listening at port: 3000');
});

Upvotes: 0

Diego
Diego

Reputation: 964

I found the solution. Instead of using simple oauth, I change it to oauth. Hope it helps someone.

var oauth = require("oauth").OAuth2;
var OAuth2 = new oauth(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, "https://github.com/", "login/oauth/authorize", "login/oauth/access_token");

app.get('/auth/github',function(req,res){
   res.writeHead(303, {
     Location: OAuth2.getAuthorizeUrl({
       redirect_uri: 'http://127.0.0.1:3000/auth/github/callback',
       scope: "user,repo,gist"
     })
    });
    res.end();
});

app.get('/auth/github/callback',function (req, res) {
  var code = req.query.code;
  OAuth2.getOAuthAccessToken(code, {}, function (err, access_token, refresh_token) {
    if (err) {
      console.log(err);
    }
    accessToken = access_token;
    // authenticate github API
    console.log("AccessToken: "+accessToken+"\n");
    github.authenticate({
      type: "oauth",
      token: accessToken
    });
  });
  res.redirect('home');
});

github.gists.create({
      "description": "the description for this gist",
      "public": true,
      "files": {
        "TEST_2.md": {
          "content": "<html><h1>This is a Test!</h1><b>Hello</b></html>"
        }
      }
    }, function(err, rest) {
      console.log(rest);
      console.log(err);
      res.render('/');
    });

Upvotes: 4

Related Questions