将express和node js app部署到谷歌应用引擎

时间:2018-01-31 21:03:18

标签: node.js express oauth-2.0 passport.js

我已经在本地测试了我的整个应用程序并且它运行良好,但是当我将其部署到谷歌应用引擎时,通过谷歌登录的整个Oauth2进程停止工作。我不知道问题是什么。

我现在正在测试的一个用例是使用一个带有登录链接的ejs文件。如果您点击该链接,它应该使用谷歌oauth2登录,并且您登录后显示的页面是您的显示名称(从您的谷歌帐户获得)。当我刷新此站点时,此显示名称消失表示它已经退出(由于某种原因),即使它应该保持登录状态。在我的localhost副本上,它完全有效,它保持登录状态,并且显示名称保持不变。

const express = require('express');
const Datastore = require('@google-cloud/datastore');
const bodyParser = require('body-parser');
const passport = require('passport');
const session = require('express-session');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

const app = express();
const datastore = Datastore();
app.enable('trust proxy');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('cookie-parser')());

const projectId = 'ece6102-guestbookapp';
const GOOGLE_CLIENT_ID      = "";
const GOOGLE_CLIENT_SECRET  = "";
const Logging = require('@google-cloud/logging');

function getLogEntries () {
  // Instantiates a client
  const logging = Logging();

  const options = {
    pageSize: 10,
    filter: 'resource.type="cloud_function"'
  };

  // Retrieve the latest Cloud Function log entries
  // See https://googlecloudplatform.github.io/gcloud-node/#/docs/logging
  return logging.getEntries(options)
    .then(([entries]) => {
      console.log('Entries:');
      entries.forEach((entry) => console.log(entry));
      return entries;
    });
}


passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
    clientID:     GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "/auth/google/callback",
    //NOTE :
    //Carefull ! and avoid usage of Private IP, otherwise you will get the device_id device_name issue for Private IP during authentication
    //The workaround is to set up thru the google cloud console a fully qualified domain name such as http://mydomain:3000/ 
    //then edit your /etc/hosts local file to point on your private IP. 
    //Also both sign-in button + callbackURL has to be share the same url, otherwise two cookies will be created and lead to lost your session
    //if you use it.
    passReqToCallback   : true
  },
  function(request, accessToken, refreshToken, profile, done) {
          console.log("Calling into this");
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's Google profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the Google account with a user record in your database,
      // and return that user instead.

      return done(null, profile);
    });
  }
));


function insertMessage (message, guestbook, user) {
    let mess = 'An anonymous person wrote:';
    if (user) {
        mess = user.displayName + ' wrote:';
    }
    return datastore.save({
        key: datastore.key(guestbook),
        data: {
            timestamp: new Date(),
            username: mess,
            message: message
        }
    });
}

function getMessages (guestbook) {
  const query = datastore.createQuery(guestbook)
    .order('timestamp', { descending: true })
    .limit(10);

  return datastore.runQuery(query)
    .then((results) => {
      return results[0];
    })
    .catch((error) => {
    });
}

app.set('views', './views');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use( session({ 
    secret: 'cookie_secret',
    resave: true,
    saveUninitialized: true
}));
app.use( passport.initialize());
app.use( passport.session());

app.get('/', (req, res) => {
    console.log(req.query);
    res.render('index', {
        user: req.user
    });
    // if ('book' in req.query) {
    //  getMessages(req.query['book']).then((results) => {
    //      res.render('index', {
    //          messages: results,
    //          guestbookname: req.query['book'],
    //          user: req.user
    //      });
    //  });
    // } else {
    //  getMessages('message').then((results) => {
    //      res.render('index', {
    //          messages: results,
    //          guestbookname: 'message',
    //          user: req.user
    //      });
    //  });
    // }

});

app.post('/addEntry', (req, res) => {
    console.log(req.user);
    insertMessage(req.body.entry, req.body.book, req.user)
    .then(() => getMessages())
    .then((messages) => {
        res.redirect('/?book=' + req.body.book);
    });
});

app.get('/auth/google', passport.authenticate('google', { scope: [
       'https://www.googleapis.com/auth/plus.login'] 
}));


app.get('/auth/google/callback', passport.authenticate('google'), (req, res) => {
    res.redirect('/');
});

app.get('/auth/logout', (req, res) => {
    req.logout();
    res.redirect('/');
});

const server = app.listen(8080, () => {
  const host = server.address().address;
  const port = server.address().port;

  console.log(`Example app listening at http://${host}:${port}`);
});

这是我编写的代码的副本,以及关于它应该做什么的一些照片:

This the the first image with the login button

This is the second image after logging in

0 个答案:

没有答案