public-soiz1's picture
Create app.js
4ae338e verified
const express = require('express');
const axios = require('axios');
const qs = require('qs');
const app = express();
// Google OAuth 2.0の設定
const client_id = '1033286471224-n9mv8l869fqikubj2e8q92n8ige3qr6r.apps.googleusercontent.com';
const client_secret = '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';
const redirect_uri = 'YOUR_REDIRECT_URI'; // 自分のリダイレクトURIに変更
app.get('/auth/google', (req, res) => {
const authUrl = `https://accounts.google.com/o/oauth2/auth?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code&scope=https://www.googleapis.com/auth/drive.file`;
res.redirect(authUrl);
});
app.get('/auth/google/callback', async (req, res) => {
const code = req.query.code;
// Googleからアクセストークンを取得
const tokenUrl = 'https://oauth2.googleapis.com/token';
const params = {
code: code,
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
grant_type: 'authorization_code',
};
try {
const response = await axios.post(tokenUrl, qs.stringify(params), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
const accessToken = response.data.access_token;
res.json({ accessToken }); // フロントエンドにアクセストークンを返す
} catch (error) {
res.status(500).json({ error: 'Failed to exchange code for token' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});