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

Allow Renaming Teams #15754

Merged
merged 4 commits into from
Jan 16, 2023
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
115 changes: 96 additions & 19 deletions components/dashboard/src/teams/TeamSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@

import { Team } from "@gitpod/gitpod-protocol";
import { BillingMode } from "@gitpod/gitpod-protocol/lib/billing-mode";
import { useContext, useEffect, useState } from "react";
import { Redirect, useLocation } from "react-router";
import React, { useCallback, useContext, useEffect, useState } from "react";
import { Redirect } from "react-router";
import Alert from "../components/Alert";
import ConfirmationModal from "../components/ConfirmationModal";
import { PageWithSubMenu } from "../components/PageWithSubMenu";
import { publicApiTeamMembersToProtocol, teamsService } from "../service/public-api";
import { getGitpodService, gitpodHostUrl } from "../service/service";
import { UserContext } from "../user-context";
import { getCurrentTeam, TeamsContext } from "./teams-context";
import { useCurrentUser } from "../user-context";
import { TeamsContext, useCurrentTeam } from "./teams-context";

export function getTeamSettingsMenu(params: { team?: Team; billingMode?: BillingMode }) {
const { team, billingMode } = params;
Expand All @@ -35,14 +36,16 @@ export function getTeamSettingsMenu(params: { team?: Team; billingMode?: Billing
}

export default function TeamSettings() {
const user = useCurrentUser();
const team = useCurrentTeam();
const { teams, setTeams } = useContext(TeamsContext);
const [modal, setModal] = useState(false);
const [teamSlug, setTeamSlug] = useState("");
const [teamNameToDelete, setTeamNameToDelete] = useState("");
const [teamName, setTeamName] = useState(team?.name || "");
const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
const [isUserOwner, setIsUserOwner] = useState(true);
const { teams } = useContext(TeamsContext);
const { user } = useContext(UserContext);
const [billingMode, setBillingMode] = useState<BillingMode | undefined>(undefined);
const location = useLocation();
const team = getCurrentTeam(location, teams);
const [updated, setUpdated] = useState(false);

const close = () => setModal(false);

Expand All @@ -60,20 +63,57 @@ export default function TeamSettings() {
const billingMode = await getGitpodService().server.getBillingModeForTeam(team.id);
setBillingMode(billingMode);
})();
}, []);
}, [team, user]);

if (!isUserOwner) {
return <Redirect to="/" />;
}
const deleteTeam = async () => {
const updateTeamInformation = useCallback(async () => {
if (!team || errorMessage || !teams) {
return;
}
try {
const updatedTeam = await getGitpodService().server.updateTeam(team.id, { name: teamName });
const updatedTeams = [...teams?.filter((t) => t.id !== team.id)];
updatedTeams.push(updatedTeam);
setTeams(updatedTeams);
setUpdated(true);
setTimeout(() => setUpdated(false), 3000);
} catch (error) {
setErrorMessage(`Failed to update team information: ${error.message}`);
}
}, [team, errorMessage, teams, teamName, setTeams]);

const onNameChange = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
if (!team) {
return;
}
const newName = event.target.value || "";
setTeamName(newName);
if (newName.trim().length === 0) {
setErrorMessage("Team name can not be blank.");
return;
} else if (newName.trim().length > 32) {
setErrorMessage("Team name must not be longer than 32 characters.");
return;
} else {
setErrorMessage(undefined);
}
},
[team],
);

const deleteTeam = useCallback(async () => {
if (!team || !user) {
return;
}

await teamsService.deleteTeam({ teamId: team.id });

document.location.href = gitpodHostUrl.asDashboard().toString();
};
}, [team, user]);

if (!isUserOwner) {
return <Redirect to="/" />;
}

return (
<>
Expand All @@ -82,7 +122,39 @@ export default function TeamSettings() {
title="Settings"
subtitle="Manage general team settings."
>
<h3>Delete Team</h3>
<h3>Team Name</h3>
<p className="text-base text-gray-500 max-w-2xl">
This is your team's visible name within Gitpod. For example, the name of your company.
</p>
{errorMessage && (
<Alert type="error" closable={true} className="mb-2 max-w-xl rounded-md">
{errorMessage}
</Alert>
)}
{updated && (
<Alert type="message" closable={true} className="mb-2 max-w-xl rounded-md">
Team name has been updated.
</Alert>
)}
<div className="flex flex-col lg:flex-row">
<div>
<div className="mt-4 mb-3">
<h4>Name</h4>
<input type="text" value={teamName} onChange={onNameChange} />
</div>
</div>
</div>
<div className="flex flex-row">
<button
className="primary"
disabled={team?.name === teamName || !!errorMessage}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: currently, the user is able to change the team name to the same name just with whitespaces around it.

Suggested change
disabled={team?.name === teamName || !!errorMessage}
disabled={team?.name === teamName.trim() || !!errorMessage}

onClick={updateTeamInformation}
>
Update Team Name
</button>
</div>

<h3 className="pt-12">Delete Team</h3>
<p className="text-base text-gray-500 pb-4 max-w-2xl">
Deleting this team will also remove all associated data with this team, including projects and
workspaces. Deleted teams cannot be restored!
Expand All @@ -95,7 +167,7 @@ export default function TeamSettings() {
<ConfirmationModal
title="Delete Team"
buttonText="Delete Team"
buttonDisabled={teamSlug !== team!.slug}
buttonDisabled={teamNameToDelete !== team!.name}
visible={modal}
warningText="Warning: This action cannot be reversed."
onClose={close}
Expand All @@ -115,9 +187,14 @@ export default function TeamSettings() {
</li>
</ol>
<p className="pt-4 pb-2 text-gray-600 dark:text-gray-400 text-base font-semibold">
Type <code>{team?.slug}</code> to confirm
Type <code>{team?.name}</code> to confirm
</p>
<input autoFocus className="w-full" type="text" onChange={(e) => setTeamSlug(e.target.value)}></input>
<input
autoFocus
className="w-full"
type="text"
onChange={(e) => setTeamNameToDelete(e.target.value)}
></input>
</ConfirmationModal>
</>
);
Expand Down
1 change: 1 addition & 0 deletions components/gitpod-db/src/team-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface TeamDB {
findTeamsByUser(userId: string): Promise<Team[]>;
findTeamsByUserAsSoleOwner(userId: string): Promise<Team[]>;
createTeam(userId: string, name: string): Promise<Team>;
updateTeam(teamId: string, team: Pick<Team, "name">): Promise<Team>;
addMemberToTeam(userId: string, teamId: string): Promise<"added" | "already_member">;
setTeamMemberRole(userId: string, teamId: string, role: TeamMemberRole): Promise<void>;
setTeamMemberSubscription(userId: string, teamId: string, subscriptionId: string): Promise<void>;
Expand Down
45 changes: 45 additions & 0 deletions components/gitpod-db/src/typeorm/team-db-impl.spec.db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Copyright (c) 2022 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License.AGPL.txt in the project root for license information.
*/

import { suite, test, timeout } from "mocha-typescript";
import { testContainer } from "../test-container";
import { UserDB } from "../user-db";
import { TypeORM } from "./typeorm";
import { DBUser } from "./entity/db-user";
import * as chai from "chai";
import { TeamDB } from "../team-db";
import { DBTeam } from "./entity/db-team";
const expect = chai.expect;

@suite(timeout(10000))
export class TeamDBSpec {
private readonly teamDB = testContainer.get<TeamDB>(TeamDB);
private readonly userDB = testContainer.get<UserDB>(UserDB);

async before() {
await this.wipeRepo();
}

async after() {
await this.wipeRepo();
}

async wipeRepo() {
const typeorm = testContainer.get<TypeORM>(TypeORM);
const manager = await typeorm.getConnection();
await manager.getRepository(DBTeam).delete({});
await manager.getRepository(DBUser).delete({});
}

@test()
async testPersistAndUpdate(): Promise<void> {
const user = await this.userDB.newUser();
let team = await this.teamDB.createTeam(user.id, "Test Team");
team.name = "Test Team 2";
team = await this.teamDB.updateTeam(team.id, team);
expect(team.name).to.be.eq("Test Team 2");
}
}
14 changes: 14 additions & 0 deletions components/gitpod-db/src/typeorm/team-db-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,20 @@ export class TeamDBImpl implements TeamDB {
return soleOwnedTeams;
}

public async updateTeam(teamId: string, team: Pick<Team, "name">): Promise<Team> {
const teamRepo = await this.getTeamRepo();
const existingTeam = await teamRepo.findOne({ id: teamId, deleted: false, markedDeleted: false });
if (!existingTeam) {
throw new ResponseError(ErrorCodes.NOT_FOUND, "Team not found");
}
const name = team.name && team.name.trim();
if (!name || name.length === 0 || name.length > 32) {
throw new ResponseError(ErrorCodes.INVALID_VALUE, "A team's name must be between 1 and 32 characters long");
}
existingTeam.name = name;
return teamRepo.save(existingTeam);
}

public async createTeam(userId: string, name: string): Promise<Team> {
if (!name) {
throw new ResponseError(ErrorCodes.BAD_REQUEST, "Team name cannot be empty");
Expand Down
1 change: 1 addition & 0 deletions components/gitpod-protocol/src/gitpod-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ export interface GitpodServer extends JsonRpcServer<GitpodClient>, AdminServer,

// Teams
getTeam(teamId: string): Promise<Team>;
updateTeam(teamId: string, team: Pick<Team, "name">): Promise<Team>;
getTeams(): Promise<Team[]>;
getTeamMembers(teamId: string): Promise<TeamMemberInfo[]>;
createTeam(name: string): Promise<Team>;
Expand Down
1 change: 1 addition & 0 deletions components/server/src/auth/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ const defaultFunctions: FunctionsConfig = {
getProjectEnvironmentVariables: { group: "default", points: 1 },
deleteProjectEnvironmentVariable: { group: "default", points: 1 },
getTeam: { group: "default", points: 1 },
updateTeam: { group: "default", points: 1 },
getTeams: { group: "default", points: 1 },
getTeamMembers: { group: "default", points: 1 },
createTeam: { group: "default", points: 1 },
Expand Down
18 changes: 18 additions & 0 deletions components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2061,6 +2061,24 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
return team;
}

public async updateTeam(ctx: TraceContext, teamId: string, team: Pick<Team, "name">): Promise<Team> {
traceAPIParams(ctx, { teamId });

if (!teamId || !uuidValidate(teamId)) {
throw new ResponseError(ErrorCodes.BAD_REQUEST, "team ID must be a valid UUID");
}
this.checkUser("updateTeam");
const existingTeam = await this.teamDB.findTeamById(teamId);
if (!existingTeam) {
throw new ResponseError(ErrorCodes.NOT_FOUND, `Team ${teamId} does not exist`);
}
const members = await this.teamDB.findMembersByTeam(teamId);
await this.guardAccess({ kind: "team", subject: existingTeam, members }, "update");

const updatedTeam = await this.teamDB.updateTeam(teamId, team);
return updatedTeam;
}

public async getTeamMembers(ctx: TraceContext, teamId: string): Promise<TeamMemberInfo[]> {
traceAPIParams(ctx, { teamId });

Expand Down