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

テナント一覧機能作成 #2

Merged
merged 1 commit into from
Jun 23, 2024
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
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
import Auth from "./components/Auth";
import Callback from "./pages/Callback";
import UserPage from "./pages/UserPage";
import TenantList from "./pages/TenantList";

function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/callback" element={<Callback />} />
<Route path="/" element={<Auth />}>
<Route path="/tenants" element={<TenantList />} />
<Route path="/user/toppage" element={<UserPage />} />
<Route path="/admin/toppage" element={<UserPage />} />
<Route path="/sadmin/toppage" element={<UserPage />} />
Expand Down
30 changes: 26 additions & 4 deletions src/pages/Callback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,43 @@ const Callback = () => {
// ロールによって遷移先振り分け
switch (role) {
case "sadmin":
navigate("/sadmin/toppage");
navigate(`/sadmin/toppage?tenant_id=${res.data.tenants[0].id}`);
break;
case "admin":
navigate("/admin/toppage");
navigate(`/admin/toppage?tenant_id=${res.data.tenants[0].id}`);
break;
default:
navigate("/user/toppage");
navigate(`/user/toppage?tenant_id=${res.data.tenants[0].id}`);

}
};

// テナント一覧orユーザー一覧への遷移を判定
const navigateIsMultiTenant = async () => {
// userInfoの取得
const jwtToken = window.localStorage.getItem("SaaSusIdToken");
const res = await axios.get(`${API_ENDPOINT}/userinfo`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Authorization: `Bearer ${jwtToken}`,
},
withCredentials: true,
});

const hasTenantLen = res.data.tenants.length;
if (hasTenantLen > 1) {
navigate('/tenants');
} else {
// シングルテナントであれば、ロールで遷移先を振り分け
navigateByRole();
}
};

useEffect(() => {
const startCallback = async () => {
if (code) {
await getToken();
navigateByRole();
navigateIsMultiTenant();
} else {
window.location.href = LOGIN_URL;
}
Expand Down
169 changes: 169 additions & 0 deletions src/pages/TenantList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import axios from "axios";
import { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import { useNavigate } from 'react-router-dom';

const LOGIN_URL = process.env.REACT_APP_LOGIN_URL ?? "";
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT ?? "";
const sleep = (second: number) =>
new Promise((resolve) => setTimeout(resolve, second * 1000));

const TenantList = () => {
const [tenants, setTenants] = useState<any>();
const [tenantInfo, setTenantInfo] = useState<any>();
let jwtToken = window.localStorage.getItem("SaaSusIdToken") as string;
const [cookies] = useCookies(["SaaSusRefreshToken"]);
const navigate = useNavigate();

type Jwt = {
[name: string]: string | number | boolean;
};

const idTokenCheck = async () => {
const base64Url = jwtToken.split(".")[1];
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const decoded = JSON.parse(
decodeURIComponent(escape(window.atob(base64)))
) as Jwt;

const expireDate = decoded["exp"] as number;
const timestamp = parseInt(Date.now().toString().slice(0, 10));
if (expireDate <= timestamp) {
try {
console.log("token expired");
const res = await axios.get(`${API_ENDPOINT}/refresh`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
},
withCredentials: true,
});

jwtToken = res.data.id_token;
localStorage.setItem("SaaSusIdToken", jwtToken);

await sleep(1);
Copy link
Contributor

Choose a reason for hiding this comment

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

このsleepは必要な感じでしょうか

Copy link
Collaborator Author

@jFujiya jFujiya Jun 19, 2024

Choose a reason for hiding this comment

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

implementation-sample-front-react/src/pages/UserPage.tsx
上記を参考に作成した処理になります。

コメントで

// JWTを更新してすぐ使用すると、Token used before used エラーになるため。
// ref: dgrijalva/jwt-go#383

と記載されていたので、必要なsleepだと思っております。

return;
} catch (err) {
console.log(err);
window.location.href = LOGIN_URL;
}
}
};

// ログインユーザの情報と所属テナント情報を取得
const GetUserinfo = async () => {
const res = await axios.get(`${API_ENDPOINT}/userinfo`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Authorization: `Bearer ${jwtToken}`,
},
withCredentials: true,
});

const tenantInfo = await Promise.all(res.data.tenants.map(async (tenant:any) => {
const res = await axios.get(`${API_ENDPOINT}/tenant_attributes`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Authorization: `Bearer ${jwtToken}`,
},
withCredentials: true,
params: {
tenant_id: tenant.id,
},
});

return res.data;
}));

console.log(tenantInfo);
setTenants(res.data.tenants);
setTenantInfo(tenantInfo);
};

const handleUserListClick = async (tenantId:any) => {
try {
// ロールの取得
const jwtToken = window.localStorage.getItem("SaaSusIdToken");
const res = await axios.get(`${API_ENDPOINT}/userinfo`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Authorization: `Bearer ${jwtToken}`,
},
withCredentials: true,
});
const role = res.data.tenants[0].envs[0].roles[0].role_name;

res.data.tenants.map((tenant:any, index:any) => {
if (tenant.id === tenantId) {
const role = tenant.envs[0].roles[0].role_name;
}
});

// リダイレクト
switch (role) {
case "sadmin":
navigate(`/sadmin/toppage?tenant_id=${tenantId}`);
break;
case "admin":
navigate(`/admin/toppage?tenant_id=${tenantId}`);
break;
default:
navigate(`/user/toppage?tenant_id=${tenantId}`);
break;
}
} catch (error) {
console.error('Error fetching user list:', error);
}
};

useEffect(() => {
const startTenantListPage = async () => {
await idTokenCheck();
GetUserinfo();
};

startTenantListPage();
}, []);

return (
<>
テナント一覧
<table border={1} style={{ borderCollapse: 'collapse' }}>
<thead>
<tr>
<td>テナントID</td>
<td>テナント名</td>
{tenantInfo && tenantInfo.length > 0 && Object.keys(tenantInfo[0]).map((key, index) => (
<td key={index}>{tenantInfo[0][key].display_name}</td>
))}
<td></td>
</tr>
</thead>
<tbody>
{tenants?.map((tenant: any, tenantIndex: number) => {
return (
<tr key={tenant.id}>
<td>{tenant.id}</td>
<td>{tenant.name}</td>
{tenantInfo[tenantIndex] && Object.keys(tenantInfo[tenantIndex]).map((key) => (
<td key={key}>
{tenantInfo[tenantIndex][key].attribute_type === 'bool'
? tenantInfo[tenantIndex][key].value === true ? '設定済み' : '未設定'
: tenantInfo[tenantIndex][key].value}
</td>
))}
<td>
<button onClick={() => handleUserListClick(tenant.id)}>
ユーザ一覧に移動
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
};

export default TenantList;
61 changes: 53 additions & 8 deletions src/pages/UserPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const sleep = (second: number) =>
const UserPage = () => {
const [users, setUsers] = useState<any>();
const [userinfo, setUserinfo] = useState<any>();
const [userAttributes, setUserAttributes] = useState<any>();
const [tenantId, setTenantId] = useState<any>();
const [tenantUserInfo, setTenantUserInfo] = useState<any>();
let jwtToken = window.localStorage.getItem("SaaSusIdToken") as string;
const [cookies] = useCookies(["SaaSusRefreshToken"]);

Expand Down Expand Up @@ -58,19 +61,22 @@ const UserPage = () => {
};

// ユーザ一覧取得
const getUsers = async () => {
const getUsers = async (tenantId:any) => {
const res = await axios.get(`${API_ENDPOINT}/users`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Authorization: `Bearer ${jwtToken}`,
},
withCredentials: true,
params: {
tenant_id: tenantId
}
});
setUsers(res.data);
};

// ログインユーザの情報を取得
const GetUserinfo = async () => {
const GetUserinfo = async (tenantId:any) => {
const res = await axios.get(`${API_ENDPOINT}/userinfo`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Expand All @@ -79,14 +85,40 @@ const UserPage = () => {
withCredentials: true,
});

res.data.tenants.map((tenant:any, index:any) => {
if (tenant.id === tenantId) {
setTenantUserInfo(tenant);
}
});

setUserinfo(res.data);
};

// ユーザー属性情報を取得
const GetuserAttributes = async () => {
const res = await axios.get(`${API_ENDPOINT}/user_attributes`, {
headers: {
"X-Requested-With": "XMLHttpRequest",
Authorization: `Bearer ${jwtToken}`,
},
withCredentials: true,
});

console.log(res.data.user_attributes)
setUserAttributes(res.data.user_attributes);
}

useEffect(() => {
const startUserPage = async () => {
// テナントIDをクエリパラメータから取得
const urlParams = new URLSearchParams(window.location.search);
const tenantIdFromQuery = urlParams.get('tenant_id');
setTenantId(tenantIdFromQuery);

await idTokenCheck();
getUsers();
GetUserinfo();
getUsers(tenantIdFromQuery);
GetUserinfo(tenantIdFromQuery);
GetuserAttributes();
};

startUserPage();
Expand All @@ -96,29 +128,35 @@ const UserPage = () => {
<>
ログインユーザの情報
<br />
テナント名:
{tenantUserInfo?.name}
<br />
名前:
{userinfo?.tenants[0].user_attribute.name}
{tenantUserInfo?.user_attribute.name}
<br />
メールアドレス:
{userinfo?.email}
<br />
ロール:
{userinfo?.tenants[0].envs[0].roles[0].display_name}
{tenantUserInfo?.envs[0].roles[0].display_name}
<br />
料金プラン:
{userinfo?.tenants[0].plan_id ? userinfo?.tenants[0].plan_id : "未設定"}
{tenantUserInfo?.plan_id ? tenantUserInfo.plan_id : "未設定"}
<br />
<br />
<br />
<br />
ユーザ一覧
<table>
<table border={1} style={{ borderCollapse: 'collapse' }}>
<thead>
<tr>
<td>テナントID</td>
<td>UUID</td>
<td>名前</td>
<td>メールアドレス</td>
{userAttributes && Object.keys(userAttributes).map((key) => (
<td key={key}> {userAttributes[key].display_name}</td>
))}
</tr>
</thead>
<tbody>
Expand All @@ -129,6 +167,13 @@ const UserPage = () => {
<td>{user.id}</td>
<td>{user.attributes.name}</td>
<td>{user.email}</td>
{user.attributes && Object.keys(user.attributes).map((key, index) => (
<td key={index}>
{typeof user.attributes[key] === "boolean"
? user.attributes[key] ? "True" : "False"
: user.attributes[key]}
</td>
))}
</tr>
);
})}
Expand Down