Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format components/server with prettier #8801

Merged
merged 1 commit into from
Mar 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions components/server/ee/src/auth/email-domain-service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
* See License.enterprise.txt in the project root folder.
*/

import * as chai from 'chai';
import { suite, test, timeout } from 'mocha-typescript';
import { testContainer as dbTestContainer } from '@gitpod/gitpod-db/lib/test-container';
import { ContainerModule } from 'inversify';
import { EMailDomainService, EMailDomainServiceImpl } from '../auth/email-domain-service';
import * as chai from "chai";
import { suite, test, timeout } from "mocha-typescript";
import { testContainer as dbTestContainer } from "@gitpod/gitpod-db/lib/test-container";
import { ContainerModule } from "inversify";
import { EMailDomainService, EMailDomainServiceImpl } from "../auth/email-domain-service";
const expect = chai.expect;

const testContainerModule = new ContainerModule((bind, unbind, isBound, rebind) => {
Expand All @@ -34,4 +34,4 @@ export class EMailDomainServiceSpec {
}
}

module.exports = new EMailDomainServiceSpec();
module.exports = new EMailDomainServiceSpec();
18 changes: 9 additions & 9 deletions components/server/ee/src/auth/email-domain-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
*/

import { injectable, inject } from "inversify";
import * as SwotJs from 'swot-js';
import * as SwotJs from "swot-js";

import { EmailDomainFilterDB } from "@gitpod/gitpod-db/lib/email-domain-filter-db";
import { EduEmailDomainDB } from "@gitpod/gitpod-db/lib/edu-email-domain-db";
import { BlockedUserFilter } from "../../../src/auth/blocked-user-filter"
import { BlockedUserFilter } from "../../../src/auth/blocked-user-filter";

export const EMailDomainService = Symbol('EMailDomainService');
export const EMailDomainService = Symbol("EMailDomainService");
export interface EMailDomainService extends BlockedUserFilter {
hasEducationalInstitutionSuffix(email: string): Promise<boolean>;
}
Expand Down Expand Up @@ -39,27 +39,27 @@ export class EMailDomainServiceImpl implements EMailDomainService {

protected async checkDBForEducationalInstitutionSuffix(domain: string): Promise<boolean> {
const entries = await this.eduDomainDb.readEducationalInstitutionDomains();
const domains = entries.map(entry => entry.domain);
return domains.some(d => domain === d);
const domains = entries.map((entry) => entry.domain);
return domains.some((d) => domain === d);
}

protected async checkSwotJsForEducationalInstitutionSuffix(email: string): Promise<boolean> {
const swotJs = await this.swotJsPromise;
return !!swotJs.check(email);
}

protected parseMail(email: string): { user: string, domain: string } {
const parts = email.split('@');
protected parseMail(email: string): { user: string; domain: string } {
const parts = email.split("@");
if (parts.length !== 2) {
throw new Error('Invalid E-Mail address: ' + email);
throw new Error("Invalid E-Mail address: " + email);
}
return { user: parts[0], domain: parts[1].toLowerCase() };
}

protected initSwotJs(): Promise<any> {
return new Promise((resolve, reject) => {
const swotCallback = () => resolve(result);
const result = new SwotJs(swotCallback)
const result = new SwotJs(swotCallback);
});
}
}
22 changes: 10 additions & 12 deletions components/server/ee/src/auth/host-container-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,21 @@ import { gitHubContainerModuleEE } from "../github/container-module";

@injectable()
export class HostContainerMappingEE extends HostContainerMapping {

public get(type: string): interfaces.ContainerModule[] | undefined {
let modules = super.get(type) || [];

switch (type) {
case "GitLab":
return (modules || []).concat([gitlabContainerModuleEE]);
case "Bitbucket":
return (modules || []).concat([bitbucketContainerModuleEE]);
// case "BitbucketServer":
case "GitLab":
return (modules || []).concat([gitlabContainerModuleEE]);
case "Bitbucket":
return (modules || []).concat([bitbucketContainerModuleEE]);
// case "BitbucketServer":
// FIXME
// return (modules || []).concat([bitbucketContainerModuleEE]);
case "GitHub":
return (modules || []).concat([gitHubContainerModuleEE]);
default:
return modules;
case "GitHub":
return (modules || []).concat([gitHubContainerModuleEE]);
default:
return modules;
}
}

}
}
44 changes: 26 additions & 18 deletions components/server/ee/src/bitbucket/bitbucket-app-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,48 +12,57 @@ import { URL } from "url";

@injectable()
export class BitbucketAppSupport {

@inject(TokenProvider) protected readonly tokenProvider: TokenProvider;

async getProviderRepositoriesForUser(params: { user: User, provider: AuthProviderInfo }): Promise<ProviderRepository[]> {
async getProviderRepositoriesForUser(params: {
user: User;
provider: AuthProviderInfo;
}): Promise<ProviderRepository[]> {
const token = await this.tokenProvider.getTokenForHost(params.user, params.provider.host);
const oauthToken = token.value;

const api = new Bitbucket({
notice: false,
baseUrl: `https://api.${params.provider.host}/2.0`,
auth: {
token: oauthToken
}
token: oauthToken,
},
});

const result: ProviderRepository[] = [];
const ownersRepos: ProviderRepository[] = [];

const identity = params.user.identities.find(i => i.authProviderId === params.provider.authProviderId);
const identity = params.user.identities.find((i) => i.authProviderId === params.provider.authProviderId);
if (!identity) {
return result;
}
const usersBitbucketAccount = identity.authName;

const workspaces = (await api.workspaces.getWorkspaces({ pagelen: 100 })).data.values?.map(w => w.slug!) || [];
const workspaces =
(await api.workspaces.getWorkspaces({ pagelen: 100 })).data.values?.map((w) => w.slug!) || [];

const reposPromise = Promise.all(workspaces.map(workspace => api.repositories.list({
workspace,
pagelen: 100,
role: "admin" // installation of webhooks is allowed for admins only
}).catch(e => {
console.error(e)
})));
const reposPromise = Promise.all(
workspaces.map((workspace) =>
api.repositories
.list({
workspace,
pagelen: 100,
role: "admin", // installation of webhooks is allowed for admins only
})
.catch((e) => {
console.error(e);
}),
),
);

const reposInWorkspace = await reposPromise;
for (const repos of reposInWorkspace) {
if (repos) {
for (const repo of (repos.data.values || [])) {
for (const repo of repos.data.values || []) {
let cloneUrl = repo.links!.clone!.find((x: any) => x.name === "https")!.href!;
if (cloneUrl) {
const url = new URL(cloneUrl);
url.username = '';
url.username = "";
cloneUrl = url.toString();
}
const fullName = repo.full_name!;
Expand All @@ -67,7 +76,7 @@ export class BitbucketAppSupport {
cloneUrl,
updatedAt,
accountAvatarUrl,
})
});
}
}
}
Expand All @@ -76,5 +85,4 @@ export class BitbucketAppSupport {
result.unshift(...ownersRepos);
return result;
}

}
}
24 changes: 17 additions & 7 deletions components/server/ee/src/container-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,16 @@ import { MonitoringEndpointsAppEE } from "./monitoring-endpoint-ee";
import { MonitoringEndpointsApp } from "../../src/monitoring-endpoints";
import { WorkspaceHealthMonitoring } from "./workspace/workspace-health-monitoring";
import { AccountService } from "@gitpod/gitpod-payment-endpoint/lib/accounting/account-service";
import { AccountServiceImpl, SubscriptionService, TeamSubscriptionService } from "@gitpod/gitpod-payment-endpoint/lib/accounting";
import { ChargebeeProvider, ChargebeeProviderOptions, UpgradeHelper } from "@gitpod/gitpod-payment-endpoint/lib/chargebee";
import {
AccountServiceImpl,
SubscriptionService,
TeamSubscriptionService,
} from "@gitpod/gitpod-payment-endpoint/lib/accounting";
import {
ChargebeeProvider,
ChargebeeProviderOptions,
UpgradeHelper,
} from "@gitpod/gitpod-payment-endpoint/lib/chargebee";
import { ChargebeeCouponComputer } from "./user/coupon-computer";
import { ChargebeeService } from "./user/chargebee-service";
import { EligibilityService } from "./user/eligibility-service";
Expand Down Expand Up @@ -100,11 +108,13 @@ export const productionEEContainerModule = new ContainerModule((bind, unbind, is

// payment/billing
bind(ChargebeeProvider).toSelf().inSingletonScope();
bind(ChargebeeProviderOptions).toDynamicValue(ctx => {
const config = ctx.container.get<Config>(Config);
return config.chargebeeProviderOptions;
}).inSingletonScope();
bind(ChargebeeProviderOptions)
.toDynamicValue((ctx) => {
const config = ctx.container.get<Config>(Config);
return config.chargebeeProviderOptions;
})
.inSingletonScope();
bind(UpgradeHelper).toSelf().inSingletonScope();
bind(ChargebeeCouponComputer).toSelf().inSingletonScope();
bind(ChargebeeService).toSelf().inSingletonScope();
});
});
2 changes: 1 addition & 1 deletion components/server/ee/src/github/container-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ import { GitHubService } from "../prebuilds/github-service";

export const gitHubContainerModuleEE = new ContainerModule((_bind, _unbind, _isBound, rebind) => {
rebind(RepositoryService).to(GitHubService).inSingletonScope();
});
});
50 changes: 28 additions & 22 deletions components/server/ee/src/github/github-app-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ import { log } from "@gitpod/gitpod-protocol/lib/util/logging";

@injectable()
export class GitHubAppSupport {

@inject(GithubApp) protected readonly githubApp: GithubApp;
@inject(UserDB) protected readonly userDB: UserDB;
@inject(TokenProvider) protected readonly tokenProvider: TokenProvider;

async getProviderRepositoriesForUser(params: { user: User, provider: string, hints?: object }): Promise<ProviderRepository[]> {
async getProviderRepositoriesForUser(params: {
user: User;
provider: string;
hints?: object;
}): Promise<ProviderRepository[]> {
const { user, provider, hints } = params;
const result: ProviderRepository[] = [];
const probot = this.githubApp.server?.probotApp;
Expand All @@ -31,7 +34,7 @@ export class GitHubAppSupport {
return result; // Just GitHub.com for now
}

const identity = user.identities.find(i => i.authProviderId === "Public-GitHub");
const identity = user.identities.find((i) => i.authProviderId === "Public-GitHub");
if (!identity) {
return result;
}
Expand All @@ -41,29 +44,33 @@ export class GitHubAppSupport {

const findInstallationForAccount = async (account: string) => {
try {
return await appApi.apps.getUserInstallation({ username: account })
return await appApi.apps.getUserInstallation({ username: account });
} catch (error: any) {
if (error instanceof RequestError) {
// ignore 404 - not found
} else {
log.debug(error);
}
}
}
const listReposForInstallation = async (installation: RestEndpointMethodTypes["apps"]["getUserInstallation"]["response"]) => {
};
const listReposForInstallation = async (
installation: RestEndpointMethodTypes["apps"]["getUserInstallation"]["response"],
) => {
const sub = await probot.auth(installation.data.id);
try {
// it seems like `sub.paginate` flattens the result and the typings are off. We do the same with the typings to mimic the shape we get.
const accessibleRepos = (await sub.paginate(sub.rest.apps.listReposAccessibleToInstallation, { per_page: 100 })) as any as RestEndpointMethodTypes["apps"]["listReposAccessibleToInstallation"]["response"]["data"]["repositories"];
return accessibleRepos.map(r => {
const accessibleRepos = (await sub.paginate(sub.rest.apps.listReposAccessibleToInstallation, {
per_page: 100,
})) as any as RestEndpointMethodTypes["apps"]["listReposAccessibleToInstallation"]["response"]["data"]["repositories"];
return accessibleRepos.map((r) => {
return <ProviderRepository>{
name: r.name,
cloneUrl: r.clone_url,
account: r.owner?.login,
accountAvatarUrl: r.owner?.avatar_url,
updatedAt: r.updated_at,
installationId: installation.data.id,
installationUpdatedAt: installation.data.updated_at
installationUpdatedAt: installation.data.updated_at,
};
});
} catch (error: any) {
Expand All @@ -73,14 +80,14 @@ export class GitHubAppSupport {
log.debug(error);
}
}
}
};

const listReposAccessibleToInstallation = async (account: string) => {
const installation = await findInstallationForAccount(account);
if (installation) {
return await listReposForInstallation(installation);
}
}
};

const ownRepos = await listReposAccessibleToInstallation(usersGitHubAccount);
if (ownRepos) {
Expand All @@ -92,15 +99,15 @@ export class GitHubAppSupport {
const token = await this.tokenProvider.getTokenForHost(user, provider);
if (token.scopes.includes("read:org")) {
const api = new Octokit({
auth: token.value
auth: token.value,
});
const { data } = await api.orgs.listMembershipsForAuthenticatedUser();
organizations.push(...data.map(o => o.organization.login));
organizations.push(...data.map((o) => o.organization.login));
}
} catch { }
} catch {}

// Add Orgs we learned about from previous installations
for (const org of (user.additionalData?.knownGitHubOrgs || [])) {
for (const org of user.additionalData?.knownGitHubOrgs || []) {
if (!organizations.includes(org)) {
organizations.unshift(org);
}
Expand All @@ -116,13 +123,13 @@ export class GitHubAppSupport {
//
const installationId = parseInt((hints as any)?.installationId, 10);
if (!isNaN(installationId)) {
if (!result.some(r => r.installationId === installationId)) {
const installation = await appApi.apps.getInstallation({installation_id: installationId});
if (!result.some((r) => r.installationId === installationId)) {
const installation = await appApi.apps.getInstallation({ installation_id: installationId });
if (installation) {
const additional = await listReposForInstallation(installation);
if (additional) {
for (const repo of additional) {
if (result.some(r => r.account === repo.account && r.name === repo.name)) {
if (result.some((r) => r.account === repo.account && r.name === repo.name)) {
continue; // avoid duplicates when switching between "selected repos" and "all repos"
}

Expand All @@ -132,8 +139,8 @@ export class GitHubAppSupport {
// optionally store newly identified organization of a user,
// just because the `listMembershipsForAuthenticatedUser` operation of the GH API
// requires an extra permission of the org's maintainer.
user.additionalData = user.additionalData || {}
user.additionalData.knownGitHubOrgs = user.additionalData.knownGitHubOrgs || [ ];
user.additionalData = user.additionalData || {};
user.additionalData.knownGitHubOrgs = user.additionalData.knownGitHubOrgs || [];
if (!user.additionalData.knownGitHubOrgs.includes(repo.account)) {
user.additionalData.knownGitHubOrgs.push(repo.account);
await this.userDB.updateUserPartial(user);
Expand All @@ -143,10 +150,9 @@ export class GitHubAppSupport {
} else {
log.debug(`Provided installationId appears to be invalid.`, { installationId });
}

}
}

return result;
}
}
}
Loading