File size: 1,497 Bytes
4ae338e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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');
});