Files
parcer/server/src/routes/auth.ts

66 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-09-15 18:44:27 +05:30
import { Router } from 'express';;
import { google } from "googleapis";
import { OAuth2Client } from 'google-auth-library'
2024-09-15 17:54:11 +05:30
2024-09-15 18:44:27 +05:30
export const router = Router()
const oauth2Client = new OAuth2Client(
'_CLIENT_ID',
'_CLIENT_SECRET',
'_REDIRECT_URI'
);
// initialize Google OAuth 2.0 flow
router.get('/auth/google', (req, res) => {
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: [
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets'
]
});
res.redirect(url);
2024-09-15 19:15:26 +05:30
});
// Callback route for Google OAuth 2.0
router.get('/auth/google/callback', async (req, res) => {
const { code } = req.query;
try {
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
// Store tokens securely (e.g., in a database)
res.send('Authentication successful');
} catch (error) {
console.error('Error during authentication:', error);
res.status(500).send('Authentication failed');
}
2024-09-15 19:16:23 +05:30
});
router.get('/sheets', async (req, res) => {
try {
const drive = google.drive({ version: 'v3', auth: oauth2Client });
const response = await drive.files.list({
q: "mimeType='application/vnd.google-apps.spreadsheet'",
fields: 'files(id, name)'
});
res.json(response.data.files);
} catch (error) {
console.error('Error listing sheets:', error);
res.status(500).send('Failed to list sheets');
}
});
2024-09-15 19:17:18 +05:30
2024-09-15 19:17:33 +05:30
router.get('/sheets/:sheetId', async (req, res) => {
2024-09-15 19:17:18 +05:30
try {
const sheets = google.sheets({ version: 'v4', auth: oauth2Client });
const response = await sheets.spreadsheets.values.get({
spreadsheetId: req.params.sheetId,
range: 'Sheet1', // Adjust range as needed
});
res.json(response.data.values);
} catch (error) {
console.error('Error reading sheet:', error);
res.status(500).send('Failed to read sheet');
}
});