<reponame>Jash271/KCP<filename>OAuth_Handler/server.js<gh_stars>0const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { raw } = require('express');


// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
 * Reads previously authorized credentials from the save file.
 *
 * @return {Promise<OAuth2Client|null>}
 */
async function loadSavedCredentialsIfExist() {
  try {
    const content = await fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch (err) {
    return null;
  }
}

/**
 * Serializes credentials to a file comptible with GoogleAUth.fromJSON.
 *
 * @param {OAuth2Client} client
 * @return {Promise<void>}
 */
async function saveCredentials(client) {
  const content = await fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content);
  const key = keys.installed || keys.web;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: key.client_id,
    client_secret: key.client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  await fs.writeFile(TOKEN_PATH, payload);
}

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
  let client = await loadSavedCredentialsIfExist();
  if (client) {
    return client;
  }
  client = await authenticate({
    scopes: SCOPES,
    keyfilePath: CREDENTIALS_PATH,
  });
  if (client.credentials) {
    await saveCredentials(client);
  }
  return client;
}

/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function listLabels(auth) {
  const gmail = google.gmail({version: 'v1', auth});
  const res = await gmail.users.labels.list({
    userId: 'me',
  });
  const labels = res.data.labels;
  if (!labels || labels.length === 0) {
    console.log('No labels found.');
    return;
  }
  console.log('Labels:');
  labels.forEach((label) => {
    console.log(`- ${label.name}`);
  });
}


const oauth2Client = new google.auth.OAuth2(
  '564790885481-7d0fdgi7jirh5mke5u4r3v2dqvbj8ba9.apps.googleusercontent.com',
  '949d1u22cbffbrarjh182eig55721odj',
  'http://localhost:5000/oauth2callback'
);

const app = express();
app.use(cors());
app.use(morgan('dev'));

app.use(express.json({ extended: false }));

const PORT = 5000;
app.listen(PORT, () => {
    console.log(`Hey! listening to you on port ${PORT}`);
  });

  app.get('/', async(req, res) => {
      console.log(req.headers)
    res.sendFile(path.join(__dirname, 'index.html'));
  });

  app.get('/oauth2callback',async(req,res)=>{
    
    console.log(req.query);
    const {tokens} = await oauth2Client.getToken(req.query['code']);
    console.log(tokens)

    res.send({
        'msg':"Hi"
    })
  })
  /*
  app.post('/oauth2callback',async(req,res)=>{
    console.log(req)
    res.send({
        'msg':"Hi"
    })
  })

  app.get('/login',async(req,res)=>{
    authorize().then(listLabels).catch(console.error);
    res.send({
        "msg":'hi'
    })
  })
  */