Check user auth in api request

This commit is contained in:
Takeshi Kimata
2024-05-25 23:34:38 +09:00
parent 4092b14f3c
commit 3984373025
16 changed files with 149 additions and 64 deletions

View File

@@ -65,6 +65,7 @@
"project_name": "Project Name",
"project_detail": "Project Detail",
"public": "Public",
"private": "Private",
"if_you_make_public": "If you make project public, everyone who has access to this site will be able to view it.",
"close": "Close",
"create": "Create",

View File

@@ -64,6 +64,7 @@
"project_name": "プロジェクト名",
"project_detail": "プロジェクト詳細",
"public": "パブリック",
"private": "プライベート",
"if_you_make_public": "プロジェクトをパブリックにすると、このサイトにアクセスできるすべてのユーザーがプロジェクトを見ることができます。",
"close": "閉じる",
"create": "作成",

View File

@@ -4,7 +4,6 @@ import { TokenContextType, TokenType } from '@/types/user';
import { TokenProps } from '@/types/user';
import { useRouter, usePathname } from '@/src/navigation';
const LOCAL_STORAGE_KEY = 'testplat-auth-token';
const privatePaths = ['/account', '/projects'];
function storeTokenToLocalStorage(token: TokenType) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(token));
@@ -43,6 +42,8 @@ const TokenProvider = ({ locale, children }: TokenProps) => {
// check expire date
if (Date.now() < token.expires_at) {
return true;
} else {
console.error('session expired');
}
}
@@ -71,17 +72,16 @@ const TokenProvider = ({ locale, children }: TokenProps) => {
}, []);
useEffect(() => {
const isPrivatePath = () => {
return privatePaths.some((path) => {
return path === pathname;
});
// check current path is private. pravate path is '/account/*' or '/projects/*'
const isPrivatePath = (pathname: string) => {
return /^\/(account|projects)\/.*/.test(pathname);
};
const checkSignInPage = () => {
if (!hasRestoreFinished) {
return;
}
if (isPrivatePath() && !isSignedIn()) {
if (isPrivatePath(pathname) && !isSignedIn()) {
router.push(`/account/signin`, { locale: locale });
}
};

View File

@@ -48,11 +48,11 @@ export default function ProjectsPage({ messages, locale }: Props) {
const onSubmit = async (name: string, detail: string, isPublic: boolean) => {
if (editingProject) {
const updatedProject = await updateProject(editingProject.id, name, detail, isPublic);
const updatedProject = await updateProject(context.token.access_token, editingProject.id, name, detail, isPublic);
const updatedProjects = projects.map((project) => (project.id === updatedProject.id ? updatedProject : project));
setProjects(updatedProjects);
} else {
const newProject = await createProject(name, detail, isPublic, context.token.user.id);
const newProject = await createProject(context.token.access_token, name, detail, isPublic);
setProjects([...projects, newProject]);
}
closeDialog();
@@ -64,12 +64,11 @@ export default function ProjectsPage({ messages, locale }: Props) {
};
const onDeleteClick = async (projectId: number) => {
try {
await deleteProject(projectId);
setProjects(projects.filter((project) => project.id !== projectId));
} catch (error: any) {
console.error('Error deleting project:', error);
}
// TODO cannot refer context
console.log(context);
console.log(context.token.access_token);
await deleteProject(context.token.access_token, projectId);
setProjects(projects.filter((project) => project.id !== projectId));
};
return (

View File

@@ -62,7 +62,15 @@ export default function ProjectsTable({ projects, onEditProject, onDeleteProject
case 'id':
return <span>{cellValue}</span>;
case 'isPublic':
return cellValue ? <Chip size="sm">{messages.public}</Chip> : <></>;
return cellValue ? (
<Chip size="sm" variant="bordered">
{messages.public}
</Chip>
) : (
<Chip size="sm" variant="bordered">
{messages.private}
</Chip>
);
case 'name':
const maxLength = 30;
const truncatedDetail = truncateText(project.detail, maxLength);

View File

@@ -1,12 +1,12 @@
'use client';
import { useState, useEffect } from 'react';
import { Divider } from '@nextui-org/react';
import { useState, useEffect, useContext } from 'react';
import { title, subtitle } from '@/components/primitives';
import { Card, CardBody, Chip } from '@nextui-org/react';
import { Card, CardBody, Chip, Divider } from '@nextui-org/react';
import { Folder, Clipboard, FlaskConical } from 'lucide-react';
import { CaseTypeCountType, CasePriorityCountType } from '@/types/case';
import { ProgressSeriesType } from '@/types/run';
import { HomeMessages } from './page';
import { TokenContext } from '@/src/app/[locale]/TokenProvider';
import { aggregateBasicInfo, aggregateTestPriority, aggregateTestType, aggregateProgress } from './aggregate';
import TestTypesChart from './TestTypesDonutChart';
import TestPriorityChart from './TestPriorityDonutChart';
@@ -15,19 +15,22 @@ import Config from '@/config/config';
import { useTheme } from 'next-themes';
const apiServer = Config.apiServer;
async function fetchProject(url) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
async function fetchProject(jwt: string, projectId: number) {
const fetchOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: jwt,
},
};
const url = `${apiServer}/home/${projectId}`;
try {
const response = await fetch(url, fetchOptions);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error: any) {
@@ -41,6 +44,7 @@ type Props = {
};
export function Home({ projectId, messages }: Props) {
const context = useContext(TokenContext);
const { theme, setTheme } = useTheme();
const [project, setProject] = useState({
name: '',
@@ -55,12 +59,15 @@ export function Home({ projectId, messages }: Props) {
const [priorityCounts, setPriorityCounts] = useState<CasePriorityCountType[]>();
const [progressCategories, setProgressCategories] = useState<string[]>();
const [progressSeries, setProgressSeries] = useState<ProgressSeriesType[]>();
const url = `${apiServer}/home/${projectId}`;
useEffect(() => {
async function fetchDataEffect() {
if (!context.isSignedIn()) {
return;
}
try {
const data = await fetchProject(url);
const data = await fetchProject(context.token.access_token, projectId);
setProject(data);
} catch (error: any) {
console.error('Error in effect:', error.message);
@@ -68,7 +75,7 @@ export function Home({ projectId, messages }: Props) {
}
fetchDataEffect();
}, [url]);
}, [context]);
useEffect(() => {
async function aggregate() {

View File

@@ -18,6 +18,7 @@ export default function Page(params: { locale: string }) {
projectName: t('project_name'),
projectDetail: t('project_detail'),
public: t('public'),
private: t('private'),
ifYouMakePublic: t('if_you_make_public'),
close: t('close'),
create: t('create'),

View File

@@ -12,7 +12,7 @@ async function fetchProjects(jwt: string) {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: jwt,
Authorization: `Bearer ${jwt}`,
},
});
@@ -30,18 +30,18 @@ async function fetchProjects(jwt: string) {
/**
* Create project
*/
async function createProject(name: string, detail: string, isPublic: boolean, userId: number) {
async function createProject(jwt: string, name: string, detail: string, isPublic: boolean) {
const newProjectData = {
name,
detail,
isPublic,
userId,
};
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify(newProjectData),
};
@@ -64,7 +64,7 @@ async function createProject(name: string, detail: string, isPublic: boolean, us
/**
* Update project
*/
async function updateProject(projectId: number, name: string, detail: string, isPublic: boolean) {
async function updateProject(jwt: string, projectId: number, name: string, detail: string, isPublic: boolean) {
const updatedProjectData = {
name,
detail,
@@ -75,6 +75,7 @@ async function updateProject(projectId: number, name: string, detail: string, is
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
body: JSON.stringify(updatedProjectData),
};
@@ -97,13 +98,15 @@ async function updateProject(projectId: number, name: string, detail: string, is
/**
* Delete project
*/
async function deleteProject(projectId: number) {
async function deleteProject(jwt: string, projectId: number) {
const fetchOptions = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
};
console.log(jwt);
const url = `${apiServer}/projects/${projectId}`;

View File

@@ -27,6 +27,7 @@ export type ProjectsMessages = {
projectName: string;
projectDetail: string;
public: string;
private: string;
ifYouMakePublic: string;
close: string;
create: string;