Create admin page

This commit is contained in:
Takeshi Kimata
2024-05-26 20:50:23 +09:00
parent 7d071303dd
commit a573358a85
19 changed files with 330 additions and 14 deletions

View File

@@ -1,4 +1,4 @@
const roles = [{ uid: 'admin' }, { uid: 'moderator' }, { uid: 'user' }];
const roles = [{ uid: 'administrator' }, { uid: 'user' }];
const categoricalPalette = ['#fba91e', '#6ea56c', '#3ac6e1', '#feda2f', '#f15f47', '#244470', '#9c80bb', '#f595a6'];

View File

@@ -23,6 +23,7 @@
"description": "Integrate and manage all your software testing",
"docs": "Docs",
"projects": "Projects",
"admin": "Administration",
"account": "Account",
"signup": "Sign up",
"signin": "Sign in",
@@ -50,6 +51,17 @@
"signin_error": "Sign in failed",
"your_projects": "Your Projects"
},
"Admin": {
"user_management": "User Management",
"avatar": "Avatar",
"id": "ID",
"email": "Email",
"username": "User name",
"role": "Role",
"administrator": "Administrator",
"user": "User",
"no_users_found": "No users found"
},
"Projects": {
"projectList": "Project List",
"project": "Project",

View File

@@ -23,6 +23,7 @@
"description": "ソフトウェア開発にかかわるすべてのテストを統合管理",
"docs": "ドキュメント",
"projects": "プロジェクト",
"admin": "管理",
"account": "アカウント",
"signup": "新規登録",
"signin": "サインイン",
@@ -49,6 +50,17 @@
"signin_error": "サインインに失敗しました",
"your_projects": "保有プロジェクト"
},
"Admin": {
"user_management": "ユーザー管理",
"avatar": "アバター",
"id": "ID",
"email": "メールアドレス",
"username": "ユーザー名",
"role": "ロール",
"administrator": "管理者",
"user": "ユーザー",
"no_users_found": "ユーザーがいません"
},
"Projects": {
"projectList": "プロジェクト一覧",
"project": "プロジェクト",

View File

@@ -6,6 +6,7 @@ export default function Header(params: { locale: string }) {
const messages = {
docs: t('docs'),
projects: t('projects'),
admin: t('admin'),
account: t('account'),
signUp: t('signup'),
signIn: t('signin'),

View File

@@ -1,5 +1,6 @@
'use client';
import { useState } from 'react';
import { useState, useContext } from 'react';
import { TokenContext } from './TokenProvider';
import { Link } from '@/src/navigation';
import Image from 'next/image';
import {
@@ -21,6 +22,7 @@ import DropdownLanguage from './DropdownLanguage';
type NabbarMenuMessages = {
projects: string;
admin: string;
docs: string;
account: string;
signUp: string;
@@ -35,6 +37,7 @@ type Props = {
export default function HeaderNavbarMenu({ messages, locale }: Props) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const context = useContext(TokenContext);
const commonLinks = [
{
@@ -92,6 +95,17 @@ export default function HeaderNavbarMenu({ messages, locale }: Props) {
</NavbarItem>
)
)}
{context.isAdmin() && (
<NavbarItem key="admin" className="hidden md:block">
<Link
className="data-[active=true]:text-primary data-[active=true]:font-medium"
href="/admin"
locale={locale}
>
{messages.admin}
</Link>
</NavbarItem>
)}
</NavbarContent>
<NavbarContent className="basis-1 pl-4" justify="end">

View File

@@ -3,6 +3,7 @@ import { createContext, useState, useEffect } from 'react';
import { TokenContextType, TokenType } from '@/types/user';
import { TokenProps } from '@/types/user';
import { useRouter, usePathname } from '@/src/navigation';
import { roles } from '@/config/selection';
const LOCAL_STORAGE_KEY = 'testplat-auth-token';
function storeTokenToLocalStorage(token: TokenType) {
@@ -19,6 +20,7 @@ const defaultContext = {
user: null,
},
isSignedIn: () => false,
isAdmin: () => false,
setToken: (token: TokenType) => {},
storeTokenToLocalStorage,
removeTokenFromLocalStorage,
@@ -50,9 +52,26 @@ const TokenProvider = ({ locale, children }: TokenProps) => {
return false;
};
const isAdmin = () => {
// check token
if (token && token.user && token.user.username) {
// check expire date
if (Date.now() < token.expires_at) {
// check role
const adminRoleIndex = roles.findIndex((entry) => entry.uid === 'administrator');
if (token.user.role === adminRoleIndex) {
return true;
}
}
}
return false;
};
const tokenContext = {
token,
isSignedIn,
isAdmin,
setToken,
storeTokenToLocalStorage,
removeTokenFromLocalStorage,

View File

@@ -12,7 +12,7 @@ async function signUp(newUser: UserType) {
body: JSON.stringify(newUser),
};
const url = `${apiServer}/auth/signup`;
const url = `${apiServer}/users/signup`;
try {
const response = await fetch(url, fetchOptions);
@@ -36,7 +36,7 @@ async function signIn(signInUser: UserType) {
body: JSON.stringify(signInUser),
};
const url = `${apiServer}/auth/signin`;
const url = `${apiServer}/users/signin`;
try {
const response = await fetch(url, fetchOptions);

View File

@@ -4,6 +4,7 @@ export default function Page(params: { locale: string }) {
const t = useTranslations('Auth');
const messages = {
yourProjects: t('your_projects'),
moveToAdmin: t('move_to_admin'),
};
return <AccountPage messages={messages} locale={params.locale} />;

View File

@@ -0,0 +1,68 @@
'use client';
import React from 'react';
import { useState, useEffect, useContext } from 'react';
import { UserType, AdminMessages } from '@/types/user';
import { TokenContext } from '../TokenProvider';
import UsersTable from './UsersTable';
import Config from '@/config/config';
const apiServer = Config.apiServer;
type Props = {
messages: AdminMessages;
locale: string;
};
async function fetchUsers(jwt: string) {
const fetchOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${jwt}`,
},
};
const url = `${apiServer}/users`;
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) {
console.error('Error fetching data:', error.message);
}
}
export default function AdminPage({ messages, locale }: Props) {
const context = useContext(TokenContext);
const [users, setUsers] = useState<UserType[]>([]);
useEffect(() => {
async function fetchDataEffect() {
if (!context.isSignedIn()) {
return;
}
try {
const data = await fetchUsers(context.token.access_token);
setUsers(data);
} catch (error: any) {
console.error('Error in effect:', error.message);
}
}
fetchDataEffect();
}, [context]);
return (
<div className="container mx-auto max-w-3xl pt-16 px-6 flex-grow">
<div className="w-full p-3 flex items-center justify-between">
<h3 className="font-bold">{messages.userManagement}</h3>
</div>
<UsersTable users={users} messages={messages} locale={locale} />
</div>
);
}

View File

@@ -0,0 +1,110 @@
import { useState, useMemo, useCallback } from 'react';
import { Table, TableHeader, TableColumn, TableBody, TableRow, TableCell, SortDescriptor } from '@nextui-org/react';
import { UserType, AdminMessages } from '@/types/user';
import { roles } from '@/config/selection';
import Avatar from 'boring-avatars';
type Props = {
users: UserType[];
messages: AdminMessages;
locale: string;
};
export default function UsersTable({ users, messages, locale }: Props) {
const headerColumns = [
{ name: messages.avatar, uid: 'avatar', sortable: false },
{ name: messages.id, uid: 'id', sortable: true },
{ name: messages.email, uid: 'email', sortable: true },
{ name: messages.username, uid: 'username', sortable: true },
{ name: messages.role, uid: 'role', sortable: true },
];
const [sortDescriptor, setSortDescriptor] = useState<SortDescriptor>({
column: 'id',
direction: 'ascending',
});
const sortedItems = useMemo(() => {
return [...users].sort((a: UserType, b: UserType) => {
const first = a[sortDescriptor.column as keyof UserType] as number;
const second = b[sortDescriptor.column as keyof UserType] as number;
const cmp = first < second ? -1 : first > second ? 1 : 0;
return sortDescriptor.direction === 'descending' ? -cmp : cmp;
});
}, [sortDescriptor, users]);
const renderCell = useCallback((user: UserType, columnKey: Key) => {
const cellValue = user[columnKey as keyof UserType];
switch (columnKey) {
case 'avatar':
return (
<Avatar
size={24}
name={user.username}
variant="beam"
colors={['#0A0310', '#49007E', '#FF005B', '#FF7D10', '#FFB238']}
/>
);
case 'id':
return <span>{cellValue}</span>;
case 'email':
return cellValue;
case 'name':
return cellValue;
case 'role':
return <span>{messages[roles[cellValue].uid]}</span>;
default:
return cellValue;
}
}, []);
const classNames = useMemo(
() => ({
wrapper: ['max-w-3xl'],
th: ['bg-transparent', 'text-default-500', 'border-b', 'border-divider'],
td: [
// changing the rows border radius
// first
'group-data-[first=true]:first:before:rounded-none',
'group-data-[first=true]:last:before:rounded-none',
// middle
'group-data-[middle=true]:before:rounded-none',
// last
'group-data-[last=true]:first:before:rounded-none',
'group-data-[last=true]:last:before:rounded-none',
],
}),
[]
);
return (
<>
<Table
isCompact
aria-label="Users table"
classNames={classNames}
sortDescriptor={sortDescriptor}
onSortChange={setSortDescriptor}
>
<TableHeader columns={headerColumns}>
{(column) => (
<TableColumn
key={column.uid}
align={column.uid === 'actions' ? 'center' : 'start'}
allowsSorting={column.sortable}
>
{column.name}
</TableColumn>
)}
</TableHeader>
<TableBody emptyContent={messages.noUsersFound} items={sortedItems}>
{(item) => (
<TableRow key={item.id}>{(columnKey) => <TableCell>{renderCell(item, columnKey)}</TableCell>}</TableRow>
)}
</TableBody>
</Table>
</>
);
}

View File

@@ -0,0 +1,24 @@
import { useTranslations } from 'next-intl';
import AdminPage from './AdminPage';
export default function Page(params: { locale: string }) {
const t = useTranslations('Admin');
const messages = {
admin: t('admin'),
userManagement: t('user_management'),
avatar: t('avatar'),
id: t('id'),
email: t('email'),
username: t('username'),
role: t('role'),
administrator: t('administrator'),
user: t('user'),
noUsersFound: t('no_users_found'),
};
return (
<div className="w-full flex items-center justify-center">
<AdminPage messages={messages} locale={params.locale} />
</div>
);
}

View File

@@ -24,6 +24,7 @@ export type TokenContextType = {
user: UserType;
};
isSignedIn: () => Boolean;
isAdmin: () => Boolean;
setToken: (token: TokenType) => {};
storeTokenToLocalStorage: (token: TokenType) => {};
removeTokenFromLocalStorage: () => {};
@@ -48,6 +49,16 @@ export type AuthMessages = {
signinError: string;
};
export type AdminMessages = {
userManagement: string;
avatar: string;
id: string;
email: string;
username: string;
role: string;
noUsersFound: string;
};
export type AccountDropDownMessages = {
account: string;
signUp: string;