@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
95 lines (91 loc) • 2.54 kB
JavaScript
import {
OAuth2Account,
OAuth2Client,
OAuth2Grant,
vault
} from "../chunk-27ATWD3Y.js";
import "../chunk-RGLWNWDM.js";
// src/google/GoogleAccount.js
import { google } from "googleapis";
import { solids } from "@randajan/props";
var GoogleAccount = class extends OAuth2Account {
constructor(client, credentials = {}) {
super(client, credentials);
const grant = vault.get(client);
const auth = grant.createAuth();
auth.setCredentials(this.credentials);
auth.on("tokens", (_) => {
grant.onRenew(this);
});
solids(this, {
auth
});
}
oauth2() {
return google.oauth2({ auth: this.auth, version: "v2" });
}
async profile() {
const { data } = await this.oauth2().userinfo.get();
return data;
}
async tokens() {
const { token } = await this.auth.getAccessToken();
return { ...this.auth.credentials, access_token: token };
}
async scopes() {
const { auth } = this;
if (auth.credentials?.scope) {
return super.scopes(auth.credentials.scope);
}
const { token } = await auth.getAccessToken();
if (!token) {
return [];
}
const info = await auth.getTokenInfo(token);
if (!info) {
return [];
}
return super.scopes(info.scopes);
}
};
// src/google/GoogleGrant.js
import { google as google2 } from "googleapis";
var GoogleGrant = class extends OAuth2Grant {
static name = "google";
static uidKey = "id";
static scopePrefix = "https://www.googleapis.com/auth/";
static scopesCommon = ["openid", "userinfo.profile", "userinfo.email"];
static scopesNoPrefix = ["openid"];
static Account = GoogleAccount;
constructor(client, opt = {}) {
super(client, opt);
const { optExtra, clientId, clientSecret, redirectUri } = this;
this.optAuth = { ...optExtra, clientId, clientSecret, redirectUri };
this.auth = this.createAuth();
}
createAuth() {
return new google2.auth.OAuth2(this.optAuth);
}
generateAuthUrl(scope, state, extra) {
return this.auth.generateAuthUrl({
...extra,
access_type: this.isOffline ? "offline" : "online",
scope,
state
});
}
async swapCodeForTokens(code) {
const { tokens } = await this.auth.getToken(code);
return tokens;
}
};
// src/google/index.js
var createGoogleOAuth2 = (options = {}) => new OAuth2Client(GoogleGrant, options);
var google_default = createGoogleOAuth2;
export {
GoogleAccount,
GoogleGrant,
createGoogleOAuth2,
google_default as default
};
//# sourceMappingURL=index.js.map