UNPKG

@randajan/oauth2-client

Version:

Lightweight Node.js helper that streamlines OAuth 2.0 and service-account authentication for all Google APIs, giving downstream packages hassle-free token acquisition and refresh

109 lines (105 loc) 2.87 kB
import { OAuth2Account, OAuth2Client, OAuth2Grant, RedirectError, vault } from "../chunk-27ATWD3Y.js"; import { extendURL } from "../chunk-RGLWNWDM.js"; // src/seznam/SeznamAccount.js import { google } from "googleapis"; import { solids } from "@randajan/props"; var SeznamAccount = class extends OAuth2Account { async profile() { const grant = vault.get(this.client); const { access_token } = this.credentials; return grant.fetchApiGet("/user", { Authorization: `bearer ${access_token}`, "Accept": "application/json" }); } async tokens() { return this.credentials; } async scopes() { if (this.credentials?.scopes) { return super.scopes(this.credentials.scopes); } return []; } }; // src/seznam/SeznamGrant.js import fetch from "node-fetch"; var SeznamGrant = class extends OAuth2Grant { static name = "seznam"; static uidKey = "email"; static scopePrefix = ""; // Seznam prefix nepoužívá static scopesCommon = ["identity"]; // povinný scope static scopesNoPrefix = []; // nic zvláštního static Account = SeznamAccount; createApiUrl(path, query = {}) { return extendURL( `https://login.szn.cz/api/v1${path}`, query ); } async fetchApiGet(path, headers, errorCode = 2) { const url = this.createApiUrl(path); const res = await fetch(url, { headers }); if (!res.ok) { throw new RedirectError(errorCode, await res.text()); } return res.json(); } async fetchApiPost(path, body, errorCode = 2) { const url = this.createApiUrl(path); const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify(body) }); if (!res.ok) { throw new RedirectError(errorCode, await res.text()); } return res.json(); } generateAuthUrl(scope, state, extra) { const { clientId, redirectUri, isOffline } = this; const access_type = isOffline ? "offline" : ""; return this.createApiUrl("/oauth/auth", { ...extra, access_type, response_type: "code", client_id: clientId, redirect_uri: redirectUri, scope: scope.join(","), // Seznam odděluje čárkou state }); } async swapCodeForTokens(code) { const { clientId, clientSecret, redirectUri } = this; return this.fetchApiPost("/oauth/token", { grant_type: "authorization_code", code, client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUri }, 2); } }; // src/seznam/index.js var createSeznamOAuth2 = (options = {}) => new OAuth2Client(SeznamGrant, options); var seznam_default = createSeznamOAuth2; export { SeznamAccount, SeznamGrant, createSeznamOAuth2, seznam_default as default }; //# sourceMappingURL=index.js.map