$ npm run setup
# Edit ./config.js file$ npm run first
$ npm run second| package-lock.json | |
| node_modules/** | |
| .editorconfig | |
| .eslintrc.yaml | |
| .prettierrc.json | |
| config.js |
| const ClientId = "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"; | |
| const ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; | |
| const RedirectURI = "https://example.com/"; | |
| module.exports = { ClientId, ClientSecret, RedirectURI }; |
| const { ClientId, RedirectURI } = require("./config"); | |
| // https://developers.google.com/photos/library/guides/authorization | |
| const GooglePhotosScope = "https://www.googleapis.com/auth/photoslibrary.readonly"; | |
| const redirectUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth"); | |
| redirectUrl.searchParams.set("response_type", "code"); | |
| redirectUrl.searchParams.set("client_id", ClientId); | |
| redirectUrl.searchParams.set("redirect_uri", RedirectURI); | |
| redirectUrl.searchParams.set("access_type", "offline"); | |
| redirectUrl.searchParams.set("prompt", "consent"); | |
| redirectUrl.searchParams.set("state", "dummy"); | |
| redirectUrl.searchParams.set("scope", `${GooglePhotosScope}`); | |
| console.log(redirectUrl.toString()); |
| { | |
| "name": "nodejs-script", | |
| "author": "mryhryki", | |
| "private": true, | |
| "license": "MIT", | |
| "engines": { | |
| "node": "18.x", | |
| "npm": "9.x" | |
| }, | |
| "scripts": { | |
| "setup": "test -f ./config.js || cp ./config.example.js ./config.js", | |
| "first": "node ./first.js", | |
| "second": "node ./second.js" | |
| } | |
| } |
| const { ClientId, ClientSecret, RedirectURI } = require("./config"); | |
| const redirectedUrl = new URL( | |
| "https://mryhryki.com/api/health?state=dummy&code=4/0AfgeXvuDCXZiDTWjQNK3-Hd7XIN-YJ1WwYdRLEefaZp0Lx2LLrHXul-jEp1-xdxXuscHuA&scope=https://www.googleapis.com/auth/photoslibrary.readonly" | |
| ); | |
| const code = redirectedUrl.searchParams.get("code"); | |
| console.log("Code:", code); | |
| const body = new URL("https://example.com"); | |
| body.searchParams.set("grant_type", "authorization_code"); | |
| body.searchParams.set("access_type", "offline"); | |
| body.searchParams.set("client_id", ClientId); | |
| body.searchParams.set("redirect_uri", RedirectURI); | |
| body.searchParams.set("code", code); | |
| const basicAuth = Buffer.from(`${ClientId}:${ClientSecret}`).toString("base64"); | |
| fetch("https://oauth2.googleapis.com/token", { | |
| method: "POST", | |
| headers: { | |
| Authorization: `Basic ${basicAuth}`, | |
| "Content-Type": "application/x-www-form-urlencoded" | |
| }, | |
| body: body.search.slice(1) | |
| }).then((response) => response.json()) | |
| .then((body) => { | |
| console.log("[Response]") | |
| Object.entries(body).forEach(([key, val]) => { | |
| console.log(`${key.padEnd(20, " ")}: ${val}`); | |
| }); | |
| }); |