fix: make github issue creation creator-restricted and easier for others

This commit is contained in:
2024-12-23 23:28:47 +01:00
parent 22d3437694
commit 5b24b0078d
8 changed files with 163 additions and 141 deletions

View File

@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "Project" ADD COLUMN "githubInstallationId" TEXT,
ALTER COLUMN "inviteCode" SET DEFAULT floor(random() * 90000000 + 10000000)::text;

View File

@@ -33,15 +33,16 @@ model Session {
}
model Project {
id String @id @default(cuid())
name String
description String
github String?
customData String[]
rateLimitReq Int @default(5)
rateLimitTime Int @default(60)
id String @id @default(cuid())
name String
description String
github String?
githubInstallationId String?
customData String[]
rateLimitReq Int @default(5)
rateLimitTime Int @default(60)
// 8 digit random number
inviteCode String @unique @default(dbgenerated("floor(random() * 90000000 + 10000000)::text"))
inviteCode String @unique @default(dbgenerated("floor(random() * 90000000 + 10000000)::text"))
users User[] @relation("UserProjects")
feedback Feedback[]

View File

@@ -20,7 +20,7 @@ import { getRepos } from './getRepos';
export default function GithubRepoChooser(props: Props) {
const [open, setOpen] = React.useState(false);
const [value, setValue] = React.useState('');
const [repos, setRepos] = React.useState<string[]>([]);
const [repos, setRepos] = React.useState<{ name: string, installationId: string }[]>([]);
const [isLoading, setIsLoading] = React.useState(true);
const [displayText, setDisplayText] = React.useState('Select a repository');
@@ -30,16 +30,22 @@ export default function GithubRepoChooser(props: Props) {
if (response.success) {
setRepos(response.repos!);
setIsLoading(false);
if (props.selected) {
setValue(props.selected);
}
}
});
setValue(props.selected ?? '');
}, []);
React.useEffect(() => {
props.onSelect(value);
}, [value]);
if (isLoading || !value) return;
const repo = repos.find((repo) => repo.name === value);
if (repo) {
props.onSelect(value, repo.installationId);
}
}, [value, repos, isLoading, props.onSelect]);
React.useEffect(() => {
if (value.length > 0) {
setDisplayText(repos.find((repo) => repo === value)!);
if (value.length > 0 && !isLoading) {
setDisplayText(repos.find((repo) => repo.name === value)!.name);
} else if (repos.length === 0) {
setDisplayText('No repositories found');
} else {
@@ -69,16 +75,15 @@ export default function GithubRepoChooser(props: Props) {
<CommandGroup>
{repos.map((repo) => (
<CommandItem
key={repo}
value={repo}
key={repo.name}
value={repo.name}
onSelect={(currentValue) => {
console.log(currentValue, value);
setValue(currentValue === value ? '' : currentValue);
setValue(currentValue);
setOpen(false);
}}
>
{repo}
<Check className={cn('ml-auto', value === repo ? 'opacity-100' : 'opacity-0')} />
{repo.name}
<Check className={cn('ml-auto', value === repo.name ? 'opacity-100' : 'opacity-0')} />
</CommandItem>
))}
</CommandGroup>
@@ -90,6 +95,6 @@ export default function GithubRepoChooser(props: Props) {
}
interface Props {
onSelect: (repo: string) => void;
onSelect: (repo: string, installationId: string) => void;
selected?: string;
}

View File

@@ -9,7 +9,7 @@ export async function getRepos() {
return { success: false, error: 'You must be logged in' };
}
const repoList: Array<{ name: string; pushed_at: string }> = [];
const repoList: Array<{ name: string; pushed_at: string; installationId: string }> = [];
for (const installation of user.installations) {
const octokit = await octokitApp.getInstallationOctokit(Number(installation));
@@ -28,6 +28,7 @@ export async function getRepos() {
const repoData = repos.repositories.map((repo) => ({
name: repo.full_name,
pushed_at: repo.pushed_at ?? '1970-01-01T00:00:00Z',
installationId: installation,
}));
repoList.push(...repoData);
@@ -35,7 +36,9 @@ export async function getRepos() {
const sortedRepos = repoList
.sort((a, b) => new Date(b.pushed_at).getTime() - new Date(a.pushed_at).getTime())
.map((repo) => repo.name);
.map((repo) => {
return { name: repo.name, installationId: repo.installationId };
});
return { success: true, repos: sortedRepos };
}

View File

@@ -25,9 +25,12 @@ import React from 'react';
import Link from 'next/link';
import InviteCodeViewer from '../InviteCodeViewer/InviteCodeViewer';
import ProjectTeamUsers from '../ProjectTeamUsers/ProjectTeamUsers';
import { useSession } from '@/lib/providers/SessionProvider';
export default function ProjectSettings(project: ProjectWithUsers) {
const { user } = useSession();
const [ghRepo, setGhRepo] = React.useState('');
const [ghInstallationId, setGhInstallationId] = React.useState('');
const [hasSubmitted, setHasSubmitted] = React.useState(false);
const apiUrl = `https://${window.location.hostname}/api/feedback/${project.id}`;
React.useEffect(() => {
@@ -59,7 +62,9 @@ export default function ProjectSettings(project: ProjectWithUsers) {
<Tabs defaultValue="project" className="w-full">
<TabsList className="mb-4">
<TabsTrigger value="project">Project</TabsTrigger>
<TabsTrigger value="github">Github</TabsTrigger>
{user?.id === project.UserProject.find((u) => u.isOwner)?.userId && (
<TabsTrigger value="github">Github</TabsTrigger>
)}
<TabsTrigger value="api">API</TabsTrigger>
</TabsList>
@@ -161,61 +166,46 @@ export default function ProjectSettings(project: ProjectWithUsers) {
</div>
</TabsContent>
<TabsContent value="github" className="grid gap-4">
<Card>
<CardHeader>
<CardTitle>Github Integration</CardTitle>
<CardDescription>Connect your project to Github</CardDescription>
</CardHeader>
<CardContent>
<GithubRepoChooser
onSelect={(repo) => {
setGhRepo(`https://github.com/${repo}`);
}}
selected={project.github ? project.github.replace('https://github.com/', '') : ''}
/>
<p className="text-muted-foreground text-xs mt-2">
Not the results you were expecting? You may have not allowed your user in the{' '}
<Link
href="https://github.com/apps/echospacedev/installations/new"
target="_blank"
className="text-primary"
>
installation settings
</Link>
.
</p>
<UniversalForm
fields={[
{
name: 'github',
label: 'GitHub Repository',
type: 'hidden',
value: ghRepo,
},
{
name: 'id',
label: 'ID',
type: 'hidden',
value: project.id,
},
]}
key={ghRepo}
schemaName={'githubSettings'}
action={githubSettings}
onActionComplete={() => setHasSubmitted(true)}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Issue submission testing</CardTitle>
<CardDescription>Make sure your setup works!</CardDescription>
</CardHeader>
<CardContent>
{hasSubmitted ? (
{user?.id === project.UserProject.find((u) => u.isOwner)?.userId && (
<TabsContent value="github" className="grid gap-4">
<Card>
<CardHeader>
<CardTitle>Github Integration</CardTitle>
<CardDescription>Connect your project to Github</CardDescription>
</CardHeader>
<CardContent>
<GithubRepoChooser
onSelect={(repo, id) => {
setGhRepo(`https://github.com/${repo}`);
setGhInstallationId(id);
}}
selected={project.github ? project.github.replace('https://github.com/', '') : ''}
/>
<p className="text-muted-foreground text-xs mt-2">
Not the results you were expecting? You may have not allowed your user in the{' '}
<Link
href="https://github.com/apps/echospacedev/installations/new"
target="_blank"
className="text-primary"
>
installation settings
</Link>
.
</p>
<UniversalForm
fields={[
{
name: 'github',
label: 'GitHub Repository',
type: 'hidden',
value: ghRepo,
},
{
name: 'installationId',
label: 'Installation ID',
type: 'hidden',
value: ghInstallationId,
},
{
name: 'id',
label: 'ID',
@@ -223,20 +213,44 @@ export default function ProjectSettings(project: ProjectWithUsers) {
value: project.id,
},
]}
schemaName={'githubTestIssue'}
action={githubTestIssue}
submitText="Create test issue"
submitClassname="!mt-0"
key={ghRepo}
schemaName={'githubSettings'}
action={githubSettings}
onActionComplete={() => setHasSubmitted(true)}
/>
) : (
<p className="text-muted-foreground text-sm">
You need to connect your project to a GitHub repository before you can test issue
submission.
</p>
)}
</CardContent>
</Card>
</TabsContent>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Issue submission testing</CardTitle>
<CardDescription>Make sure your setup works!</CardDescription>
</CardHeader>
<CardContent>
{hasSubmitted ? (
<UniversalForm
fields={[
{
name: 'id',
label: 'ID',
type: 'hidden',
value: project.id,
},
]}
schemaName={'githubTestIssue'}
action={githubTestIssue}
submitText="Create test issue"
submitClassname="!mt-0"
/>
) : (
<p className="text-muted-foreground text-sm">
You need to connect your project to a GitHub repository before you can test
issue submission.
</p>
)}
</CardContent>
</Card>
</TabsContent>
)}
<TabsContent value="api" className="space-y-5">
<Card>

View File

@@ -31,9 +31,10 @@ export default function ProjectTeamUsers(userProject: ProjectTeamUsersProps) {
});
};
// toReversed shows the owner at the top, then at join order
return (
<ul className="space-y-2 pt-5">
{users.map((user) => (
{users.toReversed().map((user) => (
<li
key={user.userId}
className="flex items-center justify-between p-3 rounded-lg shadow bg-accent"
@@ -46,7 +47,7 @@ export default function ProjectTeamUsers(userProject: ProjectTeamUsersProps) {
/>
<AvatarFallback>{user.user.username.toUpperCase()}</AvatarFallback>
</Avatar>
<span className="font-medium">{user.user.username}</span>
<span className="font-medium">{user.user.username}{user.isOwner && ' (owner)'}</span>
</div>
<Button
variant="destructive"

View File

@@ -32,6 +32,10 @@ export const githubSettingsSchema = z.object({
'Github URL must be "https://github.com/user/repo"'
)
.nonempty(),
installationId: z
.string()
.nonempty()
.transform((val) => parseInt(val, 10)),
});
export const githubTestIssueSchema = z.object({

View File

@@ -107,6 +107,7 @@ export async function customData(prev: any, formData: FormData) {
}
export async function githubSettings(prev: any, formData: FormData) {
// @ts-ignore transforming string to number makes the types go crazy
const zod = await zodVerify(githubSettingsSchema, formData);
const { user, session } = await validateRequest();
if (!user) {
@@ -122,6 +123,7 @@ export async function githubSettings(prev: any, formData: FormData) {
},
data: {
github: zod.data.github,
githubInstallationId: zod.data.installationId.toString(),
},
});
return { success: true, id: dbUpdate.id };
@@ -149,40 +151,34 @@ export async function githubTestIssue(prev: any, formData: FormData) {
include: {
user: true,
},
}
},
},
});
if (!project) {
return { success: false, error: 'Project not found' };
}
if (!project.github || !project.githubInstallationId) {
return { success: false, error: 'Github settings not found' };
}
try {
const [owner, repo] = project.github!.split('/').slice(-2);
let issueCreated = false;
for (const installationId of project.UserProject[0].user.installations) {
if (issueCreated) break;
const installation = await octokitApp.getInstallationOctokit(Number(installationId));
const getRepo = await installation
.request('GET /repos/{owner}/{repo}', {
owner,
repo,
})
.catch(() => ({ status: 404 }));
if (getRepo.status === 200) {
const createIssue = await installation.request('POST /repos/{owner}/{repo}/issues', {
owner,
repo,
title: 'Test issue',
body: "### You are all set! 🎉\n\nIf you're reading this, the test issue has been created successfully!",
});
if (createIssue.status === 201) {
issueCreated = true;
break;
}
}
const installation = await octokitApp.getInstallationOctokit(
parseInt(project.githubInstallationId!)
);
const getRepo = await installation
.request('GET /repos/{owner}/{repo}', {
owner,
repo,
})
.catch(() => ({ status: 404 }));
if (getRepo.status === 200) {
await installation.request('POST /repos/{owner}/{repo}/issues', {
owner,
repo,
title: 'Test issue',
body: "### You are all set! 🎉\n\nIf you're reading this, the test issue has been created successfully!",
});
}
} catch (e) {
console.error(e);
@@ -213,7 +209,7 @@ export async function githubCreateIssue(prev: any, formData: FormData) {
},
include: {
user: true,
}
},
},
},
});
@@ -223,27 +219,22 @@ export async function githubCreateIssue(prev: any, formData: FormData) {
try {
const [owner, repo] = project.github!.split('/').slice(-2);
for (const installationId of project.UserProject[0].user.installations) {
const installation = await octokitApp.getInstallationOctokit(Number(installationId));
const getRepo = await installation
.request('GET /repos/{owner}/{repo}', {
owner,
repo,
})
.catch(() => ({ status: 404 }));
if (getRepo.status === 200) {
const createIssue = await installation.request('POST /repos/{owner}/{repo}/issues', {
owner,
repo,
title: zod.data.title,
body: `### Feedback\n\nFeedback ID: ${zod.data.feedback}\n\n### Message\n\n${zod.data.message}`,
});
if (createIssue.status === 201) {
break;
}
}
const installation = await octokitApp.getInstallationOctokit(
Number(project.githubInstallationId)
);
const getRepo = await installation
.request('GET /repos/{owner}/{repo}', {
owner,
repo,
})
.catch(() => ({ status: 404 }));
if (getRepo.status === 200) {
await installation.request('POST /repos/{owner}/{repo}/issues', {
owner,
repo,
title: zod.data.title,
body: `### Feedback\n\nFeedback ID: ${zod.data.feedback}\n\n### Message\n\n${zod.data.message}`,
});
}
} catch (e) {
console.error(e);