From 0fc999a0199a877a73cd30fcfab76af49e56f0bf Mon Sep 17 00:00:00 2001 From: Daniel Kluge Date: Sat, 7 May 2022 15:38:17 +0200 Subject: [PATCH] Added script to fetch refresh token --- getToken.js | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ index.js | 0 package.json | 2 +- 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 getToken.js delete mode 100644 index.js diff --git a/getToken.js b/getToken.js new file mode 100644 index 0000000..7e110b4 --- /dev/null +++ b/getToken.js @@ -0,0 +1,80 @@ +import express from "express"; +import bodyParser from "body-parser"; +import open from "open"; +import fetch from "node-fetch"; +import {readFileSync, writeFileSync} from "fs" + +const app = express() +app.use(bodyParser.urlencoded({ extended: true })); +app.use(bodyParser.json()); +const port = 8080; + +let state = "code"; + +// Read and parse JSON +const secrets = JSON.parse(readFileSync("./secrets.json", "utf8")); + +// Express route that prints request body and query parameters +app.use("/", (req, res) => { + switch (state) { + case "code": { + state = "token"; + getToken(req.query); + res.status(200).json(req.query).end(); + break; + } + case "token": { + console.log(req.body); + res.status(200).json(req.body).end(); + break; + } + default: res.status(400).end(); + } +}); + +app.use("/token", (req, res) => { + console.log({ + get: req.query, + post: req.body + }); + res.status(200).json({ + get: req.query, + post: req.body + }).end() +}); + +const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`)); + +const token = "miau"; + +const params = new URLSearchParams({ + scope: "https://www.googleapis.com/auth/photoslibrary.readonly", + response_type: "code", + state: token, + redirect_uri: "http://localhost:8080", + client_id: secrets.clientId +}); + +open(`https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`); + +async function getToken(googleResponse) { + const response = await fetch("https://oauth2.googleapis.com/token", { + method: "POST", + body: JSON.stringify({ + client_id: secrets.clientId, + client_secret: secrets.clientSecret, + code: googleResponse.code, + grant_type: "authorization_code", + redirect_uri: "http://localhost:8080" + }), + headers: {'Content-Type': 'application/json'} + }); + const data = await response.json(); + console.log("Got the token!"); + console.log("Writing token to secrets..."); + secrets.refreshToken = data.refresh_token; + writeFileSync("./secrets.json", JSON.stringify(secrets)); + console.log("Done!"); + + server.close(); +} \ No newline at end of file diff --git a/index.js b/index.js deleted file mode 100644 index e69de29..0000000 diff --git a/package.json b/package.json index c8c8d51..8c43d41 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "main": "index.js", "type": "module", "scripts": { - "server": "node index.js", + "token": "node getToken.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [