index.js 2.71 KB
var express = require('express');
var router = express.Router();
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const bodyParser = require('body-parser');

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var gcal = require('google-calendar');

passport.use(new GoogleStrategy({
  clientID:'978869138601-u3euf0c04sbdor68r30m599gilvjn91e.apps.googleusercontent.com',
  clientSecret:'N7Uh_oVQZt-almzA4DkM4bm_',
  callbackURL:'http://localhost:3000/auth/google/callback',
  scope:['openid','email','https://www.googleapis.com/auth/calendar.readonly',
  'https://www.googleapis.com/auth/calendar']
},
function(accessToken,refreshToken,params,profile,done){
  profile.accessToken = accessToken;
  return done(null,profile);
}));

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

 calList = new Array();
  Calendars = new Array();

/* GET home page. */
router.get('/login', function(req, res, next) {
  if(!req.session.access_token) return res.redirect('/auth/google');
 
  var accessToken = req.session.access_token;
  getAllcalendarID(accessToken);
  //console.log(calList);
  //getAllCalendars(accessToken);
  //console.log(Calendars);
  res.redirect('/');
});

router.get('/',function(req,res,next){
  res.render('index',{title:'Reminder-Talk'});
});

router.get('/logout', function(req, res) { 
  req.logout(); 
  req.session = null; 
  res.redirect('/'); 
});



function getAllcalendarID(accessToken){
  gcal(accessToken).calendarList.list(function(err,data){
    if(err) return console.log(err);
    //console.log(data.items);
    data.items.forEach(element => {
      var cid =  element.id;
      calList.push(cid);
      getAllCalendars(accessToken,cid);
    });  
  }); 
};
var a = function(){
  console.log(Calendars);
}
function getAllCalendars(accessToken,id){
  gcal(accessToken).events.list(id,{maxResult:1},function(err,data){
    if(err) return console.log(err);
    for(var i =0 ; i< data.items.length;i++){
      var cal = new Object();
      cal.cid = id;
      cal.id = data.items[i].id;
      cal.summary = data.items[i].summary;
      cal.start = data.items[i].start;
      cal.end = data.items[i].end;
      console.log(cal);
      Calendars.push(cal);
    } 
  })  
}






module.exports = router;

//db에 id 별 이벤트 저장하고 calendar page 에서 출력해주자!
//문제점 : 비동기식 진행이어서 getAllcalendarID 함수 실행 후 바로 list 출력 안됨. console.log 먼저 출력됨