Node.js - Passport& Google Auth

时间:2018-06-02 10:52:14

标签: node.js google-calendar-api passport-google-oauth

我想从谷歌日历(公共)获取所有日历数据。我创建了一个小脚本,应该在node.js中获取数据。 在尝试加载页面时,我被重定向到谷歌登录页面。是否可以在完整的应用程序中一次性加载所有事件而无需在google / sign上登录?

var util = require('util');
var express = require('express');

var config = require('./config');
var gcal = require('./node_modules/google-calendar/GoogleCalendar');

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');


var app = express();
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;

app.use(cookieParser());

app.use(bodyParser.urlencoded({
    extended: true
}));

var sessionConfig = {
    secret: 'backendCalendar',
    cookie: {},
    resave: false,
    saveUninitialized: true,
    signed: true
};

app.use(session(sessionConfig));

app.use(passport.initialize());
app.use(passport.session());

app.listen(8082);


passport.use(new GoogleStrategy({
    clientID: '***',
    clientSecret: '***',
    callbackURL: "/auth/google/callback",
    scope: [
        'https://www.googleapis.com/auth/calendar'
    ]
},
function (accessToken, refreshToken, profile, done) {
    profile.accessToken = accessToken;
    return done(null, profile);
}
));

app.get('/auth',
   passport.authenticate('google', {session: false}));

app.get('/auth/callback',
   passport.authenticate('google', {session: false, failureRedirect: '/login'}),
   function (req, res) {
       req.session.access_token = req.user.accessToken;
       res.redirect('/');
});


app.use('/', function (req, res) {

    if (!req.session.access_token) return res.redirect('/auth');
    var accessToken = req.session.access_token;

    gcal(accessToken).calendarList.list(function (err, data) {
        if (err) return res.send(500, err);
        return res.send(data);
    });
});

app.use('/:calendarId', function (req, res) {

    if (!req.session.access_token) return res.redirect('/auth');
    var accessToken = req.session.access_token;
    var calendarId = req.params.calendarId;

    gcal(accessToken).events.list(calendarId, {maxResults: 1}, function (err, data) {
        if (err) return res.send(500, err);

        console.log(data)
        if (data.nextPageToken) {
            gcal(accessToken).events.list(calendarId, {
                maxResults: 1,
                pageToken: data.nextPageToken
            }, function (err, data) {
                console.log(data.items)
            })
        }


        return res.send(data);
    });
});

1 个答案:

答案 0 :(得分:0)

非常怀疑它,但您可以尝试使用此SO post中提到的API KEYS。