Skip to content

Commit

Permalink
replace api client with apiv2 client (#3993)
Browse files Browse the repository at this point in the history
  • Loading branch information
bkendall committed Jan 20, 2022
1 parent 6d291e8 commit 2559abb
Show file tree
Hide file tree
Showing 9 changed files with 346 additions and 435 deletions.
18 changes: 10 additions & 8 deletions src/accountExporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ var os = require("os");
var path = require("path");
var _ = require("lodash");

var api = require("./api");
var utils = require("./utils");
const { Client } = require("./apiv2");
const { googleOrigin } = require("./api");
var { FirebaseError } = require("./error");
var utils = require("./utils");

const apiClient = new Client({
urlPrefix: googleOrigin,
});

// TODO: support for MFA at runtime was added in PR #3173, but this exporter currently ignores `mfaInfo` and loses the data on export.
var EXPORTED_JSON_KEYS = [
Expand Down Expand Up @@ -161,12 +166,9 @@ var serialExportUsers = function (projectId, options) {
if (!options.timeoutRetryCount) {
options.timeoutRetryCount = 0;
}
return api
.request("POST", "/identitytoolkit/v3/relyingparty/downloadAccount", {
auth: true,
json: true,
data: postBody,
origin: api.googleOrigin,
return apiClient
.post("/identitytoolkit/v3/relyingparty/downloadAccount", postBody, {
skipLog: { resBody: true }, // This contains a lot of PII - don't log it.
})
.then(function (ret) {
options.timeoutRetryCount = 0;
Expand Down
19 changes: 11 additions & 8 deletions src/accountImporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
var clc = require("cli-color");
var _ = require("lodash");

var api = require("./api");
const { Client } = require("./apiv2");
const { googleOrigin } = require("./api");
const { logger } = require("./logger");
var utils = require("./utils");
var { FirebaseError } = require("./error");
var utils = require("./utils");

const apiClient = new Client({
urlPrefix: googleOrigin,
});

// TODO: support for MFA at runtime was added in PR #3173, but this importer currently ignores `mfaInfo` and loses the data on import.
var ALLOWED_JSON_KEYS = [
Expand Down Expand Up @@ -302,12 +307,10 @@ var validateUserJson = function (userJson) {

var _sendRequest = function (projectId, userList, hashOptions) {
logger.info("Starting importing " + userList.length + " account(s).");
return api
.request("POST", "/identitytoolkit/v3/relyingparty/uploadAccount", {
auth: true,
json: true,
data: _genUploadAccountPostBody(projectId, userList, hashOptions),
origin: api.googleOrigin,
const postData = _genUploadAccountPostBody(projectId, userList, hashOptions);
return apiClient
.post("/identitytoolkit/v3/relyingparty/uploadAccount", postData, {
skipLog: { body: true }, // Contains a lot of PII - don't log.
})
.then(function (ret) {
if (ret.body.error) {
Expand Down
6 changes: 3 additions & 3 deletions src/defaultCredentials.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as fs from "fs";
import * as path from "path";

import * as api from "./api";
import { clientId, clientSecret } from "./api";
import { Tokens, User, Account } from "./auth";
import { logger } from "./logger";

Expand Down Expand Up @@ -63,8 +63,8 @@ export function clearCredentials(account: Account): void {
function getCredential(tokens: Tokens): RefreshTokenCredential | undefined {
if (tokens.refresh_token) {
return {
client_id: api.clientId,
client_secret: api.clientSecret,
client_id: clientId,
client_secret: clientSecret,
refresh_token: tokens.refresh_token,
type: "authorized_user",
};
Expand Down
12 changes: 7 additions & 5 deletions src/functionsConfig.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as _ from "lodash";
import * as clc from "cli-color";

import * as api from "./api";
import { firebaseApiOrigin } from "./api";
import { Client } from "./apiv2";
import { ensure as ensureApiEnabled } from "./ensureApiEnabled";
import { FirebaseError } from "./error";
import { needProjectId } from "./projectUtils";
Expand All @@ -10,6 +11,8 @@ import * as args from "./deploy/functions/args";

export const RESERVED_NAMESPACES = ["firebase"];

const apiClient = new Client({ urlPrefix: firebaseApiOrigin });

interface Id {
config: string;
variable: string;
Expand Down Expand Up @@ -70,10 +73,9 @@ export function getAppEngineLocation(config: any): string {

export async function getFirebaseConfig(options: any): Promise<args.FirebaseConfig> {
const projectId = needProjectId(options);
const response = await api.request("GET", "/v1beta1/projects/" + projectId + "/adminSdkConfig", {
auth: true,
origin: api.firebaseApiOrigin,
});
const response = await apiClient.get<args.FirebaseConfig>(
`/v1beta1/projects/${projectId}/adminSdkConfig`
);
return response.body;
}

Expand Down
84 changes: 34 additions & 50 deletions src/gcp/rules.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import * as _ from "lodash";

import * as api from "../api";
import { rulesOrigin } from "../api";
import { Client } from "../apiv2";
import { logger } from "../logger";
import * as utils from "../utils";

const API_VERSION = "v1";

const apiClient = new Client({ urlPrefix: rulesOrigin, apiVersion: API_VERSION });

function _handleErrorResponse(response: any): any {
if (response.body && response.body.error) {
return utils.reject(response.body.error, { code: 2 });
Expand All @@ -21,15 +24,15 @@ function _handleErrorResponse(response: any): any {
* Gets the latest ruleset name on the project.
* @param projectId Project from which you want to get the ruleset.
* @param service Service for the ruleset (ex: cloud.firestore or firebase.storage).
* @returns Name of the latest ruleset.
* @return Name of the latest ruleset.
*/
export async function getLatestRulesetName(
projectId: string,
service: string
): Promise<string | null> {
const releases = await listAllReleases(projectId);
const prefix = `projects/${projectId}/releases/${service}`;
const release = _.find(releases, (r) => r.name.indexOf(prefix) === 0);
const release = _.find(releases, (r) => r.name.startsWith(prefix));

if (!release) {
return null;
Expand All @@ -44,12 +47,10 @@ const MAX_RELEASES_PAGE_SIZE = 10;
*/
export async function listReleases(
projectId: string,
pageToken?: string
pageToken = ""
): Promise<ListReleasesResponse> {
const response = await api.request("GET", `/${API_VERSION}/projects/${projectId}/releases`, {
auth: true,
origin: api.rulesOrigin,
query: {
const response = await apiClient.get<ListReleasesResponse>(`/projects/${projectId}/releases`, {
queryParams: {
pageSize: MAX_RELEASES_PAGE_SIZE,
pageToken,
},
Expand Down Expand Up @@ -105,12 +106,11 @@ export interface RulesetSource {
* @return Array of files in the ruleset. Each entry has form { content, name }.
*/
export async function getRulesetContent(name: string): Promise<RulesetFile[]> {
const response = await api.request("GET", `/${API_VERSION}/${name}`, {
auth: true,
origin: api.rulesOrigin,
const response = await apiClient.get<{ source: RulesetSource }>(`/${name}`, {
skipLog: { resBody: true },
});
if (response.status === 200) {
const source: RulesetSource = response.body.source;
const source = response.body.source;
return source.files;
}

Expand All @@ -124,15 +124,14 @@ const MAX_RULESET_PAGE_SIZE = 100;
*/
export async function listRulesets(
projectId: string,
pageToken?: string
pageToken: string = ""
): Promise<ListRulesetsResponse> {
const response = await api.request("GET", `/${API_VERSION}/projects/${projectId}/rulesets`, {
auth: true,
origin: api.rulesOrigin,
query: {
const response = await apiClient.get<ListRulesetsResponse>(`/projects/${projectId}/rulesets`, {
queryParams: {
pageSize: MAX_RULESET_PAGE_SIZE,
pageToken,
},
skipLog: { resBody: true },
});
if (response.status === 200) {
return response.body;
Expand Down Expand Up @@ -178,14 +177,7 @@ export function getRulesetId(ruleset: ListRulesetsEntry): string {
* by a release, the operation will fail.
*/
export async function deleteRuleset(projectId: string, id: string): Promise<void> {
const response = await api.request(
"DELETE",
`/${API_VERSION}/projects/${projectId}/rulesets/${id}`,
{
auth: true,
origin: api.rulesOrigin,
}
);
const response = await apiClient.delete(`/projects/${projectId}/rulesets/${id}`);
if (response.status === 200) {
return;
}
Expand All @@ -200,11 +192,11 @@ export async function deleteRuleset(projectId: string, id: string): Promise<void
export async function createRuleset(projectId: string, files: RulesetFile[]): Promise<string> {
const payload = { source: { files } };

const response = await api.request("POST", `/${API_VERSION}/projects/${projectId}/rulesets`, {
auth: true,
data: payload,
origin: api.rulesOrigin,
});
const response = await apiClient.post<unknown, { name: string }>(
`/projects/${projectId}/rulesets`,
payload,
{ skipLog: { body: true } }
);
if (response.status === 200) {
logger.debug("[rules] created ruleset", response.body.name);
return response.body.name;
Expand All @@ -229,11 +221,10 @@ export async function createRelease(
rulesetName,
};

const response = await api.request("POST", `/${API_VERSION}/projects/${projectId}/releases`, {
auth: true,
data: payload,
origin: api.rulesOrigin,
});
const response = await apiClient.post<unknown, { name: string }>(
`/projects/${projectId}/releases`,
payload
);
if (response.status === 200) {
logger.debug("[rules] created release", response.body.name);
return response.body.name;
Expand All @@ -260,14 +251,9 @@ export async function updateRelease(
},
};

const response = await api.request(
"PATCH",
`/${API_VERSION}/projects/${projectId}/releases/${releaseName}`,
{
auth: true,
data: payload,
origin: api.rulesOrigin,
}
const response = await apiClient.patch<unknown, { name: string }>(
`/projects/${projectId}/releases/${releaseName}`,
payload
);
if (response.status === 200) {
logger.debug("[rules] updated release", response.body.name);
Expand All @@ -290,11 +276,9 @@ export async function updateOrCreateRelease(
}

export function testRuleset(projectId: string, files: RulesetFile[]): Promise<any> {
return api.request("POST", `/${API_VERSION}/projects/${encodeURIComponent(projectId)}:test`, {
origin: api.rulesOrigin,
data: {
source: { files },
},
auth: true,
});
return apiClient.post(
`/projects/${encodeURIComponent(projectId)}:test`,
{ source: { files } },
{ skipLog: { body: true } }
);
}
66 changes: 0 additions & 66 deletions src/prepareFirebaseRules.js

This file was deleted.

0 comments on commit 2559abb

Please sign in to comment.