feat: inplement auth for runs and runCases

This commit is contained in:
Takeshi Kimata
2024-06-08 08:52:19 +09:00
parent 07259f6daf
commit 2b5a806aee
24 changed files with 293 additions and 67 deletions

View File

@@ -2,7 +2,7 @@
import { useState, useEffect, useContext } from 'react';
import { TokenContext } from '@/utils/TokenProvider';
import TestCaseTable from './TestCaseTable';
import { fetchCases, createCase, deleteCases } from './caseControl';
import { fetchCases, createCase, deleteCases } from '@/utils/caseControl';
import { CaseType, CasesMessages } from '@/types/case';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog';
import CaseDialog from './CaseDialog';
@@ -25,7 +25,7 @@ export default function CasesPane({ projectId, folderId, messages, locale }: Pro
return;
}
try {
const data = await fetchCases(context.token.access_token, folderId);
const data = await fetchCases(context.token.access_token, Number(folderId));
setCases(data);
} catch (error: any) {
console.error('Error in effect:', error.message);

View File

@@ -7,7 +7,7 @@ import { priorities, testTypes, templates } from '@/config/selection';
import CaseStepsEditor from './CaseStepsEditor';
import CaseAttachmentsEditor from './CaseAttachmentsEditor';
import { CaseType, AttachmentType, CaseMessages } from '@/types/case';
import { fetchCase, updateCase } from '../caseControl';
import { fetchCase, updateCase } from '../../../../../../../../../utils/caseControl';
import { fetchCreateStep, fetchDeleteStep } from './stepControl';
import { fetchCreateAttachments, fetchDownloadAttachment, fetchDeleteAttachment } from './attachmentControl';
import { TokenContext } from '@/utils/TokenProvider';

View File

@@ -1,5 +1,5 @@
'use client';
import { useEffect, useState } from 'react';
import { useEffect, useState, useContext } from 'react';
import { Button } from '@nextui-org/react';
import { Plus } from 'lucide-react';
import RunsTable from './RunsTable';
@@ -7,6 +7,7 @@ import { fetchRuns, createRun, updateRun, deleteRun } from './runsControl';
import { RunType, RunsMessages } from '@/types/run';
import RunDialog from './RunDialog';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog';
import { TokenContext } from '@/utils/TokenProvider';
type Props = {
projectId: string;
@@ -15,18 +16,19 @@ type Props = {
};
const defaultRun = {
id: null,
id: 0,
name: 'Untitled Run',
configurations: null,
description: null,
state: null,
projectId: null,
createdAt: null,
updatedAt: null,
configurations: 0,
description: '',
state: 0,
projectId: 0,
createdAt: '',
updatedAt: '',
};
export default function RunsPage({ projectId, locale, messages }: Props) {
const [runs, setRuns] = useState([]);
const context = useContext(TokenContext);
const [runs, setRuns] = useState<RunType[]>([]);
// run dialog
const [isRunDialogOpen, setIsRunDialogOpen] = useState(false);
@@ -51,8 +53,12 @@ export default function RunsPage({ projectId, locale, messages }: Props) {
useEffect(() => {
async function fetchDataEffect() {
if (!context.isSignedIn()) {
return;
}
try {
const data = await fetchRuns(projectId);
const data = await fetchRuns(context.token.access_token, Number(projectId));
setRuns(data);
} catch (error: any) {
console.error('Error in effect:', error.message);
@@ -60,15 +66,15 @@ export default function RunsPage({ projectId, locale, messages }: Props) {
}
fetchDataEffect();
}, []);
}, [context]);
const onSubmit = async (name: string, description: string) => {
if (editingRun && editingRun.createdAt) {
const updatedRun = await updateRun(editingRun);
const updatedRun: RunType = await updateRun(context.token.access_token, editingRun);
const updatedRuns = runs.map((run) => (run.id === updatedRun.id ? updatedRun : run));
setRuns(updatedRuns);
} else {
const newRun = await createRun(projectId, name, description);
const newRun = await createRun(context.token.access_token, Number(projectId), name, description);
setRuns([...runs, newRun]);
}
closeDialog();
@@ -81,7 +87,7 @@ export default function RunsPage({ projectId, locale, messages }: Props) {
const onConfirm = async () => {
if (deleteRunId) {
await deleteRun(deleteRunId);
await deleteRun(context.token.access_token, deleteRunId);
setRuns(runs.filter((run) => run.id !== deleteRunId));
closeDeleteConfirmDialog();
}
@@ -92,13 +98,26 @@ export default function RunsPage({ projectId, locale, messages }: Props) {
<div className="w-full p-3 flex items-center justify-between">
<h3 className="font-bold">{messages.runList}</h3>
<div>
<Button startContent={<Plus size={16} />} size="sm" color="primary" onClick={openDialogForCreate}>
<Button
startContent={<Plus size={16} />}
size="sm"
isDisabled={!context.isProjectReporter(Number(projectId))}
color="primary"
onClick={openDialogForCreate}
>
{messages.newRun}
</Button>
</div>
</div>
<RunsTable projectId={projectId} runs={runs} onDeleteRun={onDeleteClick} messages={messages} locale={locale} />
<RunsTable
projectId={projectId}
isDisabled={!context.isProjectReporter(Number(projectId))}
runs={runs}
onDeleteRun={onDeleteClick}
messages={messages}
locale={locale}
/>
<RunDialog
isOpen={isRunDialogOpen}

View File

@@ -20,13 +20,14 @@ import dayjs from 'dayjs';
type Props = {
projectId: string;
isDisabled: boolean;
runs: RunType[];
onDeleteRun: (runId: number) => void;
messages: RunsMessages;
locale: string;
};
export default function RunsTable({ projectId, runs, onDeleteRun, messages, locale }: Props) {
export default function RunsTable({ projectId, isDisabled, runs, onDeleteRun, messages, locale }: Props) {
const headerColumns = [
{ name: messages.id, uid: 'id', sortable: true },
{ name: messages.name, uid: 'name', sortable: true },
@@ -83,7 +84,7 @@ export default function RunsTable({ projectId, runs, onDeleteRun, messages, loca
</Button>
</DropdownTrigger>
<DropdownMenu aria-label="run actions">
<DropdownItem className="text-danger" onClick={() => onDeleteRun(run.id)}>
<DropdownItem className="text-danger" isDisabled={isDisabled} onClick={() => onDeleteRun(run.id)}>
{messages.deleteRun}
</DropdownItem>
</DropdownMenu>

View File

@@ -1,6 +1,6 @@
'use client';
import React from 'react';
import { useState, useEffect } from 'react';
import { useState, useEffect, useContext } from 'react';
import { useRouter } from '@/src/navigation';
import {
Button,
@@ -36,7 +36,8 @@ import {
bulkDeleteRunCases,
} from '../runsControl';
import { fetchFolders } from '../../folders/foldersControl';
import { fetchCases } from '../../folders/[folderId]/cases/caseControl';
import { fetchCases } from '@/utils/caseControl';
import { TokenContext } from '@/utils/TokenProvider';
import { useTheme } from 'next-themes';
const defaultTestRun = {
@@ -46,6 +47,8 @@ const defaultTestRun = {
description: '',
state: 0,
projectId: 0,
createdAt: '',
updatedAt: '',
};
type Props = {
@@ -56,29 +59,34 @@ type Props = {
};
export default function RunEditor({ projectId, runId, messages, locale }: Props) {
const context = useContext(TokenContext);
const { theme, setTheme } = useTheme();
const [testRun, setTestRun] = useState<RunType>(defaultTestRun);
const [folders, setFolders] = useState([]);
const [folders, setFolders] = useState<FolderType[]>([]);
const [runCases, setRunCases] = useState<RunCaseType[]>([]);
const [runStatusCounts, setRunStatusCounts] = useState<RunStatusCountType[]>();
const [selectedKeys, setSelectedKeys] = useState<Selection>(new Set([]));
const [selectedFolder, setSelectedFolder] = useState<FolderType>({});
const [selectedFolder, setSelectedFolder] = useState<FolderType | null>(null);
const [testcases, setTestCases] = useState<CaseType[]>([]);
const [isNameInvalid, setIsNameInvalid] = useState<boolean>(false);
const [isUpdating, setIsUpdating] = useState<boolean>(false);
const router = useRouter();
const fetchRunAndStatusCount = async () => {
const { run, statusCounts } = await fetchRun(runId);
const { run, statusCounts } = await fetchRun(context.token.access_token, Number(runId));
setTestRun(run);
setRunStatusCounts(statusCounts);
};
useEffect(() => {
async function fetchDataEffect() {
if (!context.isSignedIn()) {
return;
}
try {
await fetchRunAndStatusCount();
const foldersData = await fetchFolders(projectId);
const foldersData = await fetchFolders(context.token.access_token, projectId);
setFolders(foldersData);
setSelectedFolder(foldersData[0]);
} catch (error: any) {
@@ -87,16 +95,16 @@ export default function RunEditor({ projectId, runId, messages, locale }: Props)
}
fetchDataEffect();
}, []);
}, [context]);
useEffect(() => {
async function fetchCasesData() {
if (selectedFolder && selectedFolder.id) {
try {
const latestRunCases = await fetchRunCases(runId);
const latestRunCases: RunCaseType[] = await fetchRunCases(context.token.access_token, Number(runId));
setRunCases(latestRunCases);
const testCasesData = await fetchCases(selectedFolder.id);
const testCasesData: CaseType[] = await fetchCases(context.token.access_token, selectedFolder.id);
// Check if each testCase has an association with testRun
// and add "isIncluded" property
const updatedTestCasesData = testCasesData.map((testCase) => {
@@ -122,7 +130,7 @@ export default function RunEditor({ projectId, runId, messages, locale }: Props)
}, [selectedFolder]);
const handleChangeStatus = async (changeCaseId: number, status: number) => {
await updateRunCase(runId, changeCaseId, status);
await updateRunCase(context.token.access_token, Number(runId), changeCaseId, status);
setTestCases((prevTestCases) => {
return prevTestCases.map((testCase) => {
if (testCase.id === changeCaseId) {
@@ -135,12 +143,12 @@ export default function RunEditor({ projectId, runId, messages, locale }: Props)
const handleIncludeExcludeCase = async (isInclude: boolean, clickedTestCaseId: number) => {
if (isInclude) {
const createdRunCase = await createRunCase(runId, clickedTestCaseId);
const createdRunCase = await createRunCase(context.token.access_token, Number(runId), clickedTestCaseId);
setRunCases((prevRunCases) => {
return [...prevRunCases, createdRunCase];
});
} else {
await deleteRunCase(runId, clickedTestCaseId);
await deleteRunCase(context.token.access_token, Number(runId), clickedTestCaseId);
setRunCases((prevRunCases) => {
return prevRunCases.filter((runCase) => runCase.caseId !== clickedTestCaseId);
});
@@ -165,14 +173,14 @@ export default function RunEditor({ projectId, runId, messages, locale }: Props)
}
const runCaseInfo: RunCaseInfoType[] = keys.map((caseId) => ({
runId: runId,
runId: Number(runId),
caseId: caseId,
}));
if (isInclude) {
const createdRunCases = await bulkCreateRunCases(runCaseInfo);
const createdRunCases = await bulkCreateRunCases(context.token.access_token, Number(runId), runCaseInfo);
setRunCases((prevRunCases) => [...prevRunCases, ...createdRunCases]);
} else {
await bulkDeleteRunCases(runCaseInfo);
await bulkDeleteRunCases(context.token.access_token, Number(runId), runCaseInfo);
setRunCases((prevRunCases) => {
return prevRunCases.filter((runCase) => {
return !runCaseInfo.some((info) => info.caseId === runCase.caseId);
@@ -217,7 +225,7 @@ export default function RunEditor({ projectId, runId, messages, locale }: Props)
isLoading={isUpdating}
onPress={async () => {
setIsUpdating(true);
await updateRun(testRun);
await updateRun(context.token.access_token, testRun);
setIsUpdating(false);
}}
>

View File

@@ -8,7 +8,7 @@ const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
type Props = {
statusCounts: RunStatusCountType[];
messages: RunMessages;
theme: string;
theme: string | undefined;
};
export default function RunProgressDounut({ statusCounts, messages, theme }: Props) {

View File

@@ -2,7 +2,7 @@ import Config from '@/config/config';
const apiServer = Config.apiServer;
import { RunType, RunCaseInfoType } from '@/types/run';
async function fetchRun(runId: string) {
async function fetchRun(jwt: string, runId: number) {
const url = `${apiServer}/runs/${runId}`;
try {
@@ -10,6 +10,7 @@ async function fetchRun(runId: string) {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
});
@@ -24,7 +25,7 @@ async function fetchRun(runId: string) {
}
}
async function fetchRuns(projectId: string) {
async function fetchRuns(jwt: string, projectId: number) {
const url = `${apiServer}/runs?projectId=${projectId}`;
try {
@@ -32,6 +33,7 @@ async function fetchRuns(projectId: string) {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
});
@@ -46,24 +48,24 @@ async function fetchRuns(projectId: string) {
}
}
async function createRun(projectId: string, name: string, description: string) {
async function createRun(jwt: string, projectId: number, name: string, description: string) {
const newTestRun = {
name,
configurations: 0,
description,
state: 0,
projectId: projectId,
};
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify(newTestRun),
};
const url = `${apiServer}/runs`;
const url = `${apiServer}/runs?projectId=${projectId}`;
try {
const response = await fetch(url, fetchOptions);
@@ -78,11 +80,12 @@ async function createRun(projectId: string, name: string, description: string) {
}
}
async function updateRun(updateTestRun: RunType) {
async function updateRun(jwt: string, updateTestRun: RunType) {
const fetchOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify(updateTestRun),
};
@@ -102,11 +105,12 @@ async function updateRun(updateTestRun: RunType) {
}
}
async function deleteRun(runId: number) {
async function deleteRun(jwt: string, runId: number) {
const fetchOptions = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
};
@@ -123,7 +127,7 @@ async function deleteRun(runId: number) {
}
}
async function fetchRunCases(runId: string) {
async function fetchRunCases(jwt: string, runId: number) {
const url = `${apiServer}/runcases?runId=${runId}`;
try {
@@ -131,6 +135,7 @@ async function fetchRunCases(runId: string) {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
});
@@ -145,11 +150,12 @@ async function fetchRunCases(runId: string) {
}
}
async function createRunCase(runId: string, caseId: number) {
async function createRunCase(jwt: string, runId: number, caseId: number) {
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
};
@@ -168,11 +174,12 @@ async function createRunCase(runId: string, caseId: number) {
}
}
async function updateRunCase(runId: string, caseId: number, status: number) {
async function updateRunCase(jwt: string, runId: number, caseId: number, status: number) {
const fetchOptions = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
};
@@ -191,16 +198,17 @@ async function updateRunCase(runId: string, caseId: number, status: number) {
}
}
async function bulkCreateRunCases(runCaseInfo: RunCaseInfoType[]) {
async function bulkCreateRunCases(jwt: string, runId: number, runCaseInfo: RunCaseInfoType[]) {
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify(runCaseInfo),
};
const url = `${apiServer}/runcases/bulknew`;
const url = `${apiServer}/runcases/bulknew?runId=${runId}`;
try {
const response = await fetch(url, fetchOptions);
@@ -215,11 +223,12 @@ async function bulkCreateRunCases(runCaseInfo: RunCaseInfoType[]) {
}
}
async function deleteRunCase(runId: string, caseId: number) {
async function deleteRunCase(jwt: string, runId: number, caseId: number) {
const fetchOptions = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
};
@@ -236,16 +245,17 @@ async function deleteRunCase(runId: string, caseId: number) {
}
}
async function bulkDeleteRunCases(runCaseInfo: RunCaseInfoType[]) {
async function bulkDeleteRunCases(jwt: string, runId: number, runCaseInfo: RunCaseInfoType[]) {
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify(runCaseInfo),
};
const url = `${apiServer}/runcases/bulkdelete`;
const url = `${apiServer}/runcases/bulkdelete?runId=${runId}`;
try {
const response = await fetch(url, fetchOptions);

View File

@@ -30,6 +30,7 @@ export type TokenContextType = {
isAdmin: () => boolean;
isProjectManager: (projectId: number) => boolean;
isProjectDeveloper: (projectId: number) => boolean;
isProjectReporter: (projectId: number) => boolean;
setToken: (token: TokenType) => void;
storeTokenToLocalStorage: (token: TokenType) => void;
removeTokenFromLocalStorage: () => void;

View File

@@ -8,6 +8,7 @@ import {
isAdmin as tokenIsAdmin,
isProjectManager as tokenIsProjectManager,
isProjectDeveloper as tokenIsProjectDeveloper,
isProjectReporter as tokenIsProjectReporter,
checkSignInPage as tokenCheckSignInPage,
fetchMyRoles,
} from './token';
@@ -70,6 +71,10 @@ const TokenProvider = ({ toastMessages, locale, children }: TokenProps) => {
return tokenIsProjectDeveloper(projectRoles, projectId);
};
const isProjectReporter = (projectId: number) => {
return tokenIsProjectReporter(projectRoles, projectId);
};
const tokenContext = {
token,
projectRoles,
@@ -77,6 +82,7 @@ const TokenProvider = ({ toastMessages, locale, children }: TokenProps) => {
isAdmin,
isProjectManager,
isProjectDeveloper,
isProjectReporter,
setToken,
storeTokenToLocalStorage,
removeTokenFromLocalStorage,

View File

@@ -25,7 +25,7 @@ async function fetchCase(jwt: string, caseId: number) {
}
}
async function fetchCases(jwt: string, folderId: string) {
async function fetchCases(jwt: string, folderId: number) {
const url = `${apiServer}/cases?folderId=${folderId}`;
try {

View File

@@ -112,6 +112,33 @@ function isProjectDeveloper(projectRoles: ProjectRoleType[], projectId: number)
return false;
}
function isProjectReporter(projectRoles: ProjectRoleType[], projectId: number) {
if (!projectRoles) {
return false;
}
const found = projectRoles.find((role) => {
return role.projectId === projectId;
});
if (!found) {
return false;
}
if (found.isOwner === true) {
return true;
}
const managerRoleIndex = memberRoles.findIndex((entry) => entry.uid === 'manager');
const developerRoleIndex = memberRoles.findIndex((entry) => entry.uid === 'developer');
const reporterRoleIndex = memberRoles.findIndex((entry) => entry.uid === 'reporter');
if (found.role === managerRoleIndex || found.role === developerRoleIndex || found.role === reporterRoleIndex) {
return true;
}
return false;
}
// private paths are '/account', '/admin', '/projects/*'
const isPrivatePath = (pathname: string) => {
return /^\/account(\/)?$/.test(pathname) || /^\/admin(\/.*)?$/.test(pathname) || /^\/projects(\/.*)?$/.test(pathname);
@@ -142,4 +169,13 @@ function checkSignInPage(token: TokenType, pathname: string) {
return ret;
}
export { isSignedIn, isAdmin, isProjectManager, isProjectDeveloper, isPrivatePath, checkSignInPage, fetchMyRoles };
export {
isSignedIn,
isAdmin,
isProjectManager,
isProjectDeveloper,
isProjectReporter,
isPrivatePath,
checkSignInPage,
fetchMyRoles,
};