1
0
forked from baron/baron-sso

개발자 권한 부여 페이지 추가

This commit is contained in:
2026-06-09 09:28:20 +09:00
parent 41e755b1c7
commit 0f11173739
11 changed files with 1050 additions and 3 deletions

View File

@@ -861,6 +861,9 @@ func main() {
dev.Post("/developer-request/:id/approve", devHandler.ApproveDeveloperRequest)
dev.Post("/developer-request/:id/reject", devHandler.RejectDeveloperRequest)
dev.Post("/developer-request/:id/cancel-approval", devHandler.CancelDeveloperRequestApproval)
dev.Get("/developer-grants", devHandler.ListDeveloperGrants)
dev.Post("/developer-grants", devHandler.CreateDeveloperGrant)
dev.Post("/developer-grants/:id/revoke", devHandler.RevokeDeveloperGrant)
// Webhook for Kratos courier (HTTP delivery)
auth.Post("/webhooks/kratos-courier", authHandler.HandleKratosCourierRelay)

View File

@@ -4049,7 +4049,7 @@ func (h *DevHandler) ListDeveloperRequests(c *fiber.Ctx) error {
userID = ""
}
requests, err := h.DeveloperSvc.ListRequests(c.Context(), userID, status)
requests, err := h.DeveloperSvc.ListRequests(c.Context(), userID, status, "")
if err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
@@ -4057,6 +4057,159 @@ func (h *DevHandler) ListDeveloperRequests(c *fiber.Ctx) error {
return c.JSON(requests)
}
func (h *DevHandler) ListDeveloperGrants(c *fiber.Ctx) error {
profile := h.getCurrentProfile(c)
if profile == nil {
return errorJSON(c, fiber.StatusUnauthorized, "unauthorized")
}
if normalizeUserRole(profile.Role) != domain.RoleSuperAdmin {
return errorJSON(c, fiber.StatusForbidden, "forbidden: super_admin only")
}
tenantID := strings.TrimSpace(c.Query("tenantId"))
grants, err := h.DeveloperSvc.ListRequests(c.Context(), "", domain.DeveloperRequestStatusApproved, tenantID)
if err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
return c.JSON(grants)
}
func (h *DevHandler) CreateDeveloperGrant(c *fiber.Ctx) error {
profile := h.getCurrentProfile(c)
if profile == nil {
return errorJSON(c, fiber.StatusUnauthorized, "unauthorized")
}
if normalizeUserRole(profile.Role) != domain.RoleSuperAdmin {
return errorJSON(c, fiber.StatusForbidden, "forbidden: super_admin only")
}
var reqBody struct {
UserID string `json:"userId"`
TenantID string `json:"tenantId"`
Reason string `json:"reason"`
AdminNotes string `json:"adminNotes"`
}
if err := c.BodyParser(&reqBody); err != nil {
return errorJSON(c, fiber.StatusBadRequest, "invalid request body")
}
userID := strings.TrimSpace(reqBody.UserID)
tenantID := strings.TrimSpace(reqBody.TenantID)
if userID == "" || tenantID == "" {
return errorJSON(c, fiber.StatusBadRequest, "userId and tenantId are required")
}
if h.KratosAdmin == nil || h.TenantSvc == nil {
return errorJSON(c, fiber.StatusServiceUnavailable, "required services are unavailable")
}
identity, err := h.KratosAdmin.GetIdentity(c.Context(), userID)
if err != nil || identity == nil {
return errorJSON(c, fiber.StatusNotFound, "user not found")
}
tenant, err := h.TenantSvc.GetTenant(c.Context(), tenantID)
if err != nil || tenant == nil {
return errorJSON(c, fiber.StatusNotFound, "tenant not found")
}
name := strings.TrimSpace(extractTraitString(identity.Traits, "name"))
if name == "" {
name = userID
}
organization := strings.TrimSpace(tenant.Name)
if organization == "" {
organization = tenantID
}
email := strings.TrimSpace(extractTraitString(identity.Traits, "email"))
phone := strings.TrimSpace(extractTraitString(identity.Traits, "phone"))
role := normalizeUserRole(extractTraitString(identity.Traits, "role"))
if role == "" {
role = domain.RoleUser
}
reason := strings.TrimSpace(reqBody.Reason)
if reason == "" {
reason = "직접 부여"
}
existing, err := h.DeveloperSvc.GetRequestStatus(c.Context(), userID, tenantID)
if err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
if existing != nil {
switch existing.Status {
case domain.DeveloperRequestStatusApproved:
h.ensureDeveloperGrantRelation(c, userID, tenantID)
return c.JSON(existing)
case domain.DeveloperRequestStatusPending:
if err := h.DeveloperSvc.ApproveRequest(c.Context(), existing.ID, reqBody.AdminNotes); err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
h.ensureDeveloperGrantRelation(c, userID, tenantID)
existing.Status = domain.DeveloperRequestStatusApproved
existing.AdminNotes = reqBody.AdminNotes
return c.JSON(existing)
}
}
grant := domain.DeveloperRequest{
UserID: userID,
TenantID: tenantID,
Name: name,
Organization: organization,
Email: email,
Phone: phone,
Role: role,
Reason: reason,
Status: domain.DeveloperRequestStatusApproved,
AdminNotes: strings.TrimSpace(reqBody.AdminNotes),
}
if err := h.DeveloperSvc.CreateGrant(c.Context(), grant); err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
h.ensureDeveloperGrantRelation(c, userID, tenantID)
return c.Status(fiber.StatusCreated).JSON(grant)
}
func (h *DevHandler) RevokeDeveloperGrant(c *fiber.Ctx) error {
profile := h.getCurrentProfile(c)
if profile == nil {
return errorJSON(c, fiber.StatusUnauthorized, "unauthorized")
}
if normalizeUserRole(profile.Role) != domain.RoleSuperAdmin {
return errorJSON(c, fiber.StatusForbidden, "forbidden: super_admin only")
}
idStr := c.Params("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
return errorJSON(c, fiber.StatusBadRequest, "invalid grant id")
}
var reqBody struct {
AdminNotes string `json:"adminNotes"`
}
if err := c.BodyParser(&reqBody); err != nil {
return errorJSON(c, fiber.StatusBadRequest, "invalid request body")
}
devReq, err := h.DeveloperSvc.GetRequestByID(c.Context(), uint(id))
if err != nil {
return errorJSON(c, fiber.StatusInternalServerError, "failed to fetch grant details")
}
if devReq.Status != domain.DeveloperRequestStatusApproved {
return errorJSON(c, fiber.StatusBadRequest, "only approved grants can be revoked")
}
if err := h.DeveloperSvc.CancelApprovedRequest(c.Context(), uint(id), reqBody.AdminNotes); err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
h.revokeDeveloperGrantRelation(c, devReq.UserID, devReq.TenantID)
return c.JSON(fiber.Map{"status": "ok"})
}
func (h *DevHandler) ApproveDeveloperRequest(c *fiber.Ctx) error {
profile := h.getCurrentProfile(c)
if profile == nil {

View File

@@ -30,6 +30,10 @@ func (s *DeveloperService) RequestAccess(ctx context.Context, req domain.Develop
return s.db.WithContext(ctx).Create(&req).Error
}
func (s *DeveloperService) CreateGrant(ctx context.Context, req domain.DeveloperRequest) error {
return s.db.WithContext(ctx).Create(&req).Error
}
func (s *DeveloperService) GetRequestStatus(ctx context.Context, userID, tenantID string) (*domain.DeveloperRequest, error) {
var req domain.DeveloperRequest
err := s.db.WithContext(ctx).Where("user_id = ? AND tenant_id = ?", userID, tenantID).Order("created_at DESC").First(&req).Error
@@ -51,7 +55,7 @@ func (s *DeveloperService) GetRequestByID(ctx context.Context, id uint) (*domain
return &req, nil
}
func (s *DeveloperService) ListRequests(ctx context.Context, userID, status string) ([]domain.DeveloperRequest, error) {
func (s *DeveloperService) ListRequests(ctx context.Context, userID, status, tenantID string) ([]domain.DeveloperRequest, error) {
var requests []domain.DeveloperRequest
query := s.db.WithContext(ctx)
if userID != "" {
@@ -60,6 +64,9 @@ func (s *DeveloperService) ListRequests(ctx context.Context, userID, status stri
if status != "" {
query = query.Where("status = ?", status)
}
if tenantID != "" {
query = query.Where("tenant_id = ?", tenantID)
}
err := query.Order("created_at DESC").Find(&requests).Error
return requests, err
}

View File

@@ -10,6 +10,7 @@ import ClientGeneralPage from "../features/clients/ClientGeneralPage";
import ClientRelationsPage from "../features/clients/ClientRelationsPage";
import ClientsPage from "../features/clients/ClientsPage";
import DeveloperRequestPage from "../features/developer-request/DeveloperRequestPage";
import DeveloperGrantsPage from "../features/developer-grants/DeveloperGrantsPage";
import GlobalOverviewPage from "../features/overview/GlobalOverviewPage";
import ProfilePage from "../features/profile/ProfilePage";
import { DEVFRONT_AUTH_CALLBACK_PATH } from "../lib/authConfig";
@@ -26,6 +27,7 @@ const devFrontAppChildren: RouteObject[] = [
element: <ClientRelationsPage />,
},
{ path: "developer-requests", element: <DeveloperRequestPage /> },
{ path: "developer-grants", element: <DeveloperGrantsPage /> },
{ path: "audit-logs", element: <AuditLogsPage /> },
{ path: "profile", element: <ProfilePage /> },
];

View File

@@ -4,6 +4,7 @@ import {
ClipboardCheck,
LayoutDashboard,
LogOut,
KeyRound,
Moon,
NotebookTabs,
ShieldHalf,
@@ -39,7 +40,7 @@ import { Toaster } from "../ui/toaster";
const LOCALE_CHANGED_EVENT = "baron_locale_changed";
const navItems: ShellSidebarNavItem[] = [
const baseNavItems: ShellSidebarNavItem[] = [
{
labelKey: "ui.dev.nav.overview",
labelFallback: "Overview",
@@ -350,6 +351,17 @@ function AppLayout() {
auth.user?.profile as Record<string, unknown> | undefined,
);
const displayRoleKey = profile?.role || currentRole;
const navItems = displayRoleKey === "super_admin"
? [
...baseNavItems,
{
labelKey: "ui.dev.nav.developer_grants",
labelFallback: "Developer Access Grants",
to: "/developer-grants",
icon: KeyRound,
},
]
: baseNavItems;
const handleSessionExpiryToggle = () => {
setIsSessionExpiryEnabled((prev) => {
const next = !prev;

View File

@@ -11,12 +11,16 @@ import ClientRelationsPage from "../clients/ClientRelationsPage";
import ClientsPage from "../clients/ClientsPage";
import { ClientFederationPage } from "../clients/routes/ClientFederationPage";
import DeveloperRequestPage from "../developer-request/DeveloperRequestPage";
import DeveloperGrantsPage from "../developer-grants/DeveloperGrantsPage";
import GlobalOverviewPage from "../overview/GlobalOverviewPage";
import ProfilePage from "../profile/ProfilePage";
import {
approveDeveloperRequest,
cancelDeveloperRequestApproval,
createDeveloperGrant,
fetchDeveloperGrants,
rejectDeveloperRequest,
revokeDeveloperGrant,
} from "../../lib/devApi";
const authProfile = {
@@ -195,6 +199,29 @@ vi.mock("../../lib/devApi", () => ({
},
],
})),
fetchDevUser: vi.fn(async () => ({
id: "user-2",
email: "editor@example.com",
name: "Editor User",
phone: "010-1111-2222",
role: "user",
status: "active",
tenant: {
id: "tenant-1",
name: "Hanmac",
slug: "hanmac",
type: "COMPANY",
status: "active",
description: "",
memberCount: 10,
createdAt: "2026-05-01T00:00:00Z",
updatedAt: "2026-05-01T00:00:00Z",
},
tenantSlug: "hanmac",
companyCode: "HANMAC",
createdAt: "2026-05-01T00:00:00Z",
updatedAt: "2026-05-01T00:00:00Z",
})),
addClientRelation: vi.fn(async () => ({
relation: "admins",
subject: "User:user-2",
@@ -290,6 +317,24 @@ vi.mock("../../lib/devApi", () => ({
updatedAt: "2026-05-01T00:00:00Z",
},
]),
fetchTenants: vi.fn(async () => ({
items: [
{
id: "tenant-1",
name: "Hanmac",
slug: "hanmac",
type: "COMPANY",
status: "active",
description: "",
memberCount: 10,
createdAt: "2026-05-01T00:00:00Z",
updatedAt: "2026-05-01T00:00:00Z",
},
],
limit: 1000,
offset: 0,
total: 1,
})),
fetchDeveloperRequestStatus: vi.fn(async () => ({ status: "approved" })),
requestDeveloperAccess: vi.fn(async () => ({ status: "pending" })),
fetchDeveloperRequests: vi.fn(async () => [
@@ -319,9 +364,26 @@ vi.mock("../../lib/devApi", () => ({
updatedAt: "2026-05-02T00:00:00Z",
},
]),
fetchDeveloperGrants: vi.fn(async () => [
{
id: 3,
userId: "user-5",
tenantId: "tenant-1",
name: "Granted User",
organization: "Hanmac",
email: "granted@example.com",
reason: "Direct grant",
status: "approved",
adminNotes: "Manual grant",
createdAt: "2026-05-03T00:00:00Z",
updatedAt: "2026-05-03T00:00:00Z",
},
]),
approveDeveloperRequest: vi.fn(async () => ({ status: "approved" })),
rejectDeveloperRequest: vi.fn(async () => ({ status: "rejected" })),
cancelDeveloperRequestApproval: vi.fn(async () => ({ status: "cancelled" })),
createDeveloperGrant: vi.fn(async () => ({ status: "approved" })),
revokeDeveloperGrant: vi.fn(async () => ({ status: "ok" })),
}));
vi.mock("../auth/authApi", () => ({
@@ -408,6 +470,9 @@ describe("devfront coverage smoke pages", () => {
const requests = await renderPage(<DeveloperRequestPage />);
expect(requests.textContent).toContain("Requester");
const grants = await renderPage(<DeveloperGrantsPage />);
expect(grants.textContent).toContain("개발자 권한 부여");
const profile = await renderPage(<ProfilePage />);
expect(profile.textContent).toContain("Dev Admin");
});

View File

@@ -0,0 +1,618 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { KeyRound, Plus, Search, ShieldCheck, X } from "lucide-react";
import { useDeferredValue, useMemo, useState } from "react";
import { useAuth } from "react-oidc-context";
import { PageHeader } from "../../../../common/core/components/page";
import { Badge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "../../components/ui/card";
import { Input } from "../../components/ui/input";
import { Label } from "../../components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../../components/ui/table";
import { Textarea } from "../../components/ui/textarea";
import { toast } from "../../components/ui/use-toast";
import {
createDeveloperGrant,
fetchDeveloperGrants,
fetchDevUsers,
fetchDevUser,
revokeDeveloperGrant,
type DevAssignableUser,
} from "../../lib/devApi";
import { t } from "../../lib/i18n";
import { resolveProfileRole } from "../../lib/role";
import { fetchMe } from "../auth/authApi";
function formatUserLabel(user: DevAssignableUser) {
const primary = user.name.trim() || user.email.trim();
return `${primary} (${user.email.trim()})`;
}
export default function DeveloperGrantsPage() {
const auth = useAuth();
const queryClient = useQueryClient();
const hasAccessToken = Boolean(auth.user?.access_token);
const userProfile = auth.user?.profile as Record<string, unknown> | undefined;
const role = resolveProfileRole(userProfile);
const { data: me, isLoading: isLoadingMe } = useQuery({
queryKey: ["userMe"],
queryFn: fetchMe,
enabled: hasAccessToken,
});
const profileRole = me?.role?.trim() || role;
const isSuperAdmin = profileRole === "super_admin";
const [userSearch, setUserSearch] = useState("");
const deferredUserSearch = useDeferredValue(userSearch.trim());
const [selectedUser, setSelectedUser] = useState<DevAssignableUser | null>(
null,
);
const [grantNotes, setGrantNotes] = useState("");
const [adminNotes, setAdminNotes] = useState<Record<number, string>>({});
const {
data: userSearchData,
isFetching: isUserSearchLoading,
} = useQuery({
queryKey: ["developer-grant-users", deferredUserSearch],
queryFn: () => fetchDevUsers(deferredUserSearch, 10),
enabled:
hasAccessToken &&
isSuperAdmin &&
deferredUserSearch.length > 0 &&
selectedUser == null,
});
const {
data: selectedUserDetail,
isFetching: isSelectedUserDetailLoading,
} = useQuery({
queryKey: ["developer-grant-user", selectedUser?.id],
queryFn: () => fetchDevUser(selectedUser?.id || ""),
enabled: hasAccessToken && isSuperAdmin && selectedUser != null,
});
const {
data: grants,
isLoading: isLoadingGrants,
error: grantsError,
} = useQuery({
queryKey: ["developer-grants"],
queryFn: () => fetchDeveloperGrants(),
enabled: hasAccessToken && isSuperAdmin,
});
const grantList = grants ?? [];
const filteredGrantedUsers = useMemo(() => {
return [...grantList].sort((a, b) => {
const tenantCompare = a.organization.localeCompare(b.organization);
if (tenantCompare !== 0) {
return tenantCompare;
}
return a.name.localeCompare(b.name);
});
}, [grantList]);
const createGrantMutation = useMutation({
mutationFn: createDeveloperGrant,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["developer-grants"] });
toast(
t(
"msg.dev.grants.create_success",
"개발자 권한이 직접 부여되었습니다.",
),
"success",
);
setSelectedUser(null);
setUserSearch("");
setGrantNotes("");
},
onError: (err: AxiosError<{ error?: string }> | Error) => {
toast(
(err as AxiosError<{ error?: string }>).response?.data?.error ||
(err as Error).message ||
t("msg.common.error", "오류가 발생했습니다."),
"error",
);
},
});
const revokeGrantMutation = useMutation({
mutationFn: ({
id,
adminNotes,
}: {
id: number;
adminNotes: string;
}) => revokeDeveloperGrant(id, adminNotes),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["developer-grants"] });
toast(
t("msg.dev.grants.revoke_success", "개발자 권한이 회수되었습니다."),
"success",
);
},
onError: (err: AxiosError<{ error?: string }> | Error) => {
toast(
(err as AxiosError<{ error?: string }>).response?.data?.error ||
(err as Error).message ||
t("msg.common.error", "오류가 발생했습니다."),
"error",
);
},
});
if (isLoadingMe) {
return (
<div className="p-8 text-center">
{t("ui.common.loading", "Loading...")}
</div>
);
}
if (!isSuperAdmin) {
return (
<div className="space-y-6">
<PageHeader
icon={<ShieldCheck size={20} />}
title={t("ui.dev.nav.developer_grants", "개발자 권한 부여")}
description={t(
"msg.dev.grants.forbidden_desc",
"이 화면은 super admin만 사용할 수 있습니다.",
)}
/>
<Card className="border-amber-500/30 bg-amber-500/10">
<CardContent className="p-4 text-sm text-foreground">
{t(
"msg.dev.grants.forbidden",
"개발자 권한 직접 부여는 super admin만 사용할 수 있습니다.",
)}
</CardContent>
</Card>
</div>
);
}
const handleGrant = () => {
if (!selectedUser) {
toast(
t(
"msg.dev.grants.user_required",
"부여할 사용자를 선택해주세요.",
),
"error",
);
return;
}
const tenantId = selectedUserDetail?.tenant?.id?.trim() || "";
if (!tenantId) {
toast(
t(
"msg.dev.grants.tenant_required",
"선택한 사용자의 현재 테넌트 정보를 확인할 수 없습니다.",
),
"error",
);
return;
}
createGrantMutation.mutate({
userId: selectedUser.id,
tenantId,
reason: grantNotes.trim() || "직접 부여",
adminNotes: grantNotes.trim(),
});
};
const handleSelectUser = (user: DevAssignableUser) => {
setSelectedUser(user);
setUserSearch(formatUserLabel(user));
};
return (
<div className="space-y-8">
<PageHeader
icon={<KeyRound size={20} />}
title={t("ui.dev.nav.developer_grants", "개발자 권한 부여")}
description={t(
"msg.dev.grants.description",
"사용자에게 개발자 권한을 직접 부여하고, 부여된 권한을 회수할 수 있습니다.",
)}
actions={
<Badge variant="muted">
{t("msg.dev.grants.count", "총 {{count}}건", {
count: filteredGrantedUsers.length,
})}
</Badge>
}
/>
<Card className="glass-panel">
<CardHeader>
<CardTitle className="text-xl">
{t("ui.dev.grants.form.title", "직접 부여")}
</CardTitle>
<CardDescription>
{t(
"msg.dev.grants.form.description",
"사용자를 선택하면 현재 소속 정보가 표시되고, 그 사용자에게 개발자 권한을 즉시 부여합니다.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<div className="grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]">
<Card className="border-primary/10 bg-primary/5 shadow-sm">
<CardHeader className="space-y-1 pb-3">
<div className="flex items-center justify-between gap-2">
<CardTitle className="text-base">
{t("ui.dev.grants.user_section", "사용자 선택")}
</CardTitle>
<Badge variant="outline">
{t("ui.dev.grants.input_section", "입력")}
</Badge>
</div>
<CardDescription>
{t(
"msg.dev.grants.user_section_description",
"검색어를 입력해 사용자를 선택합니다. 선택 전에는 다음 단계 정보가 비어 있습니다.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-2 pt-0">
<div className="space-y-2">
<Label htmlFor="user-search">
{t("ui.dev.grants.user", "사용자")}{" "}
<span className="text-destructive">*</span>
</Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="user-search"
className="pl-10"
placeholder={t(
"ui.dev.grants.user_search_placeholder",
"이름 또는 이메일 검색...",
)}
value={userSearch}
onChange={(event) => {
setSelectedUser(null);
setUserSearch(event.target.value);
}}
/>
</div>
{selectedUser && (
<p className="text-xs text-muted-foreground">
{t(
"msg.dev.grants.selected_user",
"선택된 사용자: {{user}}",
{ user: formatUserLabel(selectedUser) },
)}
</p>
)}
</div>
{userSearch.trim() !== "" && selectedUser == null && (
<div className="mt-2 max-h-64 overflow-y-auto rounded-lg border border-border/70 bg-muted/20 shadow-sm">
{isUserSearchLoading ? (
<div className="px-3 py-3 text-sm text-muted-foreground">
{t(
"msg.dev.grants.search_loading",
"사용자를 찾는 중입니다...",
)}
</div>
) : (userSearchData?.items ?? []).length > 0 ? (
(userSearchData?.items ?? []).map((user) => (
<button
key={user.id}
type="button"
className="flex w-full flex-col gap-1 border-b border-border/40 px-3 py-2 text-left last:border-b-0 hover:bg-primary/5"
onMouseDown={(event) => {
event.preventDefault();
handleSelectUser(user);
}}
>
<span className="text-sm font-semibold">
{user.name || user.email}
</span>
<span className="text-xs text-muted-foreground">
{user.email}
{user.loginId ? ` · ${user.loginId}` : ""}
</span>
</button>
))
) : (
<div className="px-3 py-4 text-center text-sm text-muted-foreground">
{t(
"msg.dev.grants.search_empty",
"검색 결과가 없습니다.",
)}
</div>
)}
</div>
)}
</CardContent>
</Card>
<Card className="border-dashed bg-muted/20 shadow-none">
<CardHeader className="space-y-1 pb-3">
<div className="flex items-center justify-between gap-2">
<CardTitle className="text-base">
{t(
"ui.dev.grants.selected_info",
"선택된 사용자 정보",
)}
</CardTitle>
<Badge variant="secondary">
{t("ui.dev.grants.read_only", "읽기 전용")}
</Badge>
</div>
<CardDescription>
{t(
"msg.dev.grants.selected_info_description",
"선택된 사용자의 소속, 이메일, 전화번호를 확인합니다.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4 pt-0">
<div className="space-y-2">
<Label htmlFor="tenant-readonly">
{t("ui.dev.grants.tenant", "소속")}
</Label>
<Input
id="tenant-readonly"
className="border-dashed bg-background/70 text-foreground/90 shadow-none focus-visible:border-input focus-visible:ring-0 focus-visible:ring-offset-0"
value={
selectedUserDetail?.tenant?.name ||
selectedUserDetail?.tenantSlug ||
selectedUserDetail?.companyCode ||
""
}
readOnly
placeholder={
selectedUser
? isSelectedUserDetailLoading
? t("msg.common.loading", "Loading...")
: t(
"msg.dev.grants.tenant_missing",
"선택한 사용자의 테넌트 정보가 없습니다.",
)
: t(
"msg.dev.grants.user_required",
"부여할 사용자를 선택해주세요.",
)
}
/>
</div>
<div className="space-y-2">
<Label htmlFor="email-readonly">
{t("ui.dev.grants.email", "이메일")}
</Label>
<Input
id="email-readonly"
className="border-dashed bg-background/70 text-foreground/90 shadow-none focus-visible:border-input focus-visible:ring-0 focus-visible:ring-offset-0"
value={
selectedUserDetail?.email || selectedUser?.email || ""
}
readOnly
placeholder={t(
"msg.dev.grants.user_required",
"부여할 사용자를 선택해주세요.",
)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="phone-readonly">
{t("ui.dev.grants.phone", "전화번호")}
</Label>
<Input
id="phone-readonly"
className="border-dashed bg-background/70 text-foreground/90 shadow-none focus-visible:border-input focus-visible:ring-0 focus-visible:ring-offset-0"
value={selectedUserDetail?.phone || ""}
readOnly
placeholder={t(
"msg.dev.grants.phone_missing",
"등록된 전화번호가 없습니다.",
)}
/>
</div>
</CardContent>
</Card>
</div>
<Card className="border-border/70 bg-background/80 shadow-sm">
<CardHeader className="space-y-1 pb-3">
<div className="flex items-center justify-between gap-2">
<CardTitle className="text-base">
{t("ui.dev.grants.admin_notes", "부여 사유")}
</CardTitle>
</div>
<CardDescription>
{t(
"msg.dev.grants.admin_notes_description",
"직접 부여의 근거를 간단히 남겨 두면 추후 회수와 검토에 도움이 됩니다.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3 pt-0">
<Textarea
id="admin-notes"
value={grantNotes}
onChange={(event) => setGrantNotes(event.target.value)}
className="min-h-[132px] bg-background"
placeholder={t(
"msg.dev.grants.admin_notes_placeholder",
"예: 테스트 환경 확인 후 권한 부여",
)}
/>
<p className="text-xs text-muted-foreground">
{t(
"msg.dev.grants.admin_notes_hint",
"회수는 목록의 회수 버튼으로 처리합니다.",
)}
</p>
</CardContent>
</Card>
<div className="flex justify-end">
<Button
onClick={handleGrant}
disabled={createGrantMutation.isPending}
className="gap-2"
>
<Plus className="h-4 w-4" />
{createGrantMutation.isPending
? t("ui.common.submitting", "제출 중...")
: t("ui.dev.grants.grant", "직접 부여")}
</Button>
</div>
</CardContent>
</Card>
<Card className="glass-panel">
<CardHeader>
<CardTitle className="text-xl">
{t("ui.dev.grants.list.title", "부여된 권한")}
</CardTitle>
<CardDescription>
{t(
"msg.dev.grants.list.description",
"현재 부여된 개발자 권한 목록입니다.",
)}
</CardDescription>
</CardHeader>
<CardContent>
{isLoadingGrants ? (
<div className="py-8 text-center text-sm text-muted-foreground">
{t("msg.common.loading", "Loading...")}
</div>
) : grantsError ? (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
{t(
"msg.dev.grants.load_error",
"개발자 권한 목록을 불러오지 못했습니다.",
)}
</div>
) : filteredGrantedUsers.length === 0 ? (
<div className="py-8 text-center text-sm text-muted-foreground">
{t("msg.dev.grants.empty", "부여된 권한이 없습니다.")}
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("ui.dev.grants.user", "사용자")}</TableHead>
<TableHead>{t("ui.dev.grants.tenant", "테넌트")}</TableHead>
<TableHead>{t("ui.dev.grants.reason", "부여 사유")}</TableHead>
<TableHead>{t("ui.dev.grants.status", "상태")}</TableHead>
<TableHead>{t("ui.dev.grants.date", "부여일")}</TableHead>
<TableHead className="text-right">
{t("ui.dev.grants.actions", "관리")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredGrantedUsers.map((grant) => (
<TableRow key={grant.id}>
<TableCell>
<div className="space-y-1">
<div className="font-medium">
{grant.name || grant.email || grant.userId}
</div>
<div className="text-xs text-muted-foreground">
{grant.email || grant.userId}
</div>
<div className="font-mono text-xs text-muted-foreground">
{grant.userId}
</div>
</div>
</TableCell>
<TableCell>
<div className="space-y-1">
<div className="font-medium">
{grant.organization || grant.tenantId}
</div>
<div className="font-mono text-xs text-muted-foreground">
{grant.tenantId}
</div>
</div>
</TableCell>
<TableCell className="max-w-md">
<div className="truncate" title={grant.reason}>
{grant.reason}
</div>
{grant.adminNotes && (
<div className="mt-1 text-xs text-muted-foreground">
{grant.adminNotes}
</div>
)}
</TableCell>
<TableCell>
<Badge variant="success">
{t("ui.dev.grants.approved", "승인됨")}
</Badge>
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{new Date(grant.createdAt).toLocaleDateString()}
</TableCell>
<TableCell className="text-right">
<div className="ml-auto flex min-w-[220px] flex-col items-end gap-2">
<Input
placeholder={t(
"ui.dev.grants.revoke_notes_placeholder",
"회수 메모 (선택)...",
)}
className="h-8 text-xs"
value={adminNotes[grant.id] || ""}
onChange={(event) =>
setAdminNotes({
...adminNotes,
[grant.id]: event.target.value,
})
}
/>
<Button
size="sm"
variant="outline"
className="text-destructive hover:bg-destructive/10"
disabled={revokeGrantMutation.isPending}
onClick={() => {
revokeGrantMutation.mutate({
id: grant.id,
adminNotes: adminNotes[grant.id] || "",
});
}}
>
<X className="mr-1 h-3 w-3" />
{t("ui.dev.grants.revoke", "회수")}
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -536,6 +536,8 @@ export type DeveloperRequest = {
updatedAt: string;
};
export type DeveloperGrant = DeveloperRequest;
export async function fetchDeveloperRequestStatus(tenantId?: string) {
const { data } = await apiClient.get<DeveloperRequest | { status: "none" }>(
"/dev/developer-request/status",
@@ -595,3 +597,31 @@ export async function cancelDeveloperRequestApproval(
);
return data;
}
export async function fetchDeveloperGrants(tenantId?: string) {
const { data } = await apiClient.get<DeveloperGrant[]>("/dev/developer-grants", {
params: { tenantId },
});
return data;
}
export async function createDeveloperGrant(payload: {
userId: string;
tenantId: string;
reason?: string;
adminNotes?: string;
}) {
const { data } = await apiClient.post<DeveloperGrant>(
"/dev/developer-grants",
payload,
);
return data;
}
export async function revokeDeveloperGrant(id: number, adminNotes: string) {
const { data } = await apiClient.post<{ status: string }>(
`/dev/developer-grants/${id}/revoke`,
{ adminNotes },
);
return data;
}

View File

@@ -543,6 +543,7 @@ unavailable_with_reason = "RP usage statistics API is unavailable. {{reason}}"
audit = "Review RP configuration changes and operational history."
clients = "Browse registered RPs and manage their status and type."
description = "Jump directly to key operational screens."
developer_grants = "Directly grant or revoke developer access for users."
developer_request = "Review developer access requests or submit a new one."
new_client = "Configure redirect URIs, grant types, and authentication methods."
@@ -554,6 +555,33 @@ none = "No connected applications to display."
description = "Review trends for changed or deleted applications on the dashboard."
empty = "There are no recent change logs yet."
[msg.dev.grants]
approved = "Approved"
count = "Total {{count}}"
create_success = "Developer access has been granted directly."
description = "Directly grant developer access to users and revoke granted access."
admin_notes_hint = "Revocations are handled from the list below."
admin_notes_description = "Leaving a short note for the direct grant helps later reviews and revocations."
admin_notes_placeholder = "e.g. Grant access after verifying the test environment"
empty = "There are no granted permissions."
forbidden = "Only super admin can directly grant developer access."
forbidden_desc = "This screen is available only to super admin."
form.description = "Select a user to view their current tenant, email, and phone, then grant developer access immediately."
selected_info_description = "Review the selected user's tenant, email, and phone."
user_section_description = "Enter a search term to select a user. The next-step information stays empty until a user is chosen."
list.description = "Current developer access grants."
load_error = "Failed to load developer access grants."
reason = "Grant reason"
revoke = "Revoke"
revoke_success = "Developer access has been revoked."
search_empty = "No users found."
search_loading = "Searching users..."
selected_user = "Selected user: {{user}}"
tenant_required = "The selected user's tenant information is unavailable."
tenant_missing = "No tenant information is available for the selected user."
user_required = "Select a user before granting access."
phone_missing = "No phone number is registered."
[msg.dev.dashboard.notice]
consent_audit = "Consent Audit"
dev_scope = "Dev Scope"
@@ -1294,6 +1322,7 @@ scope_badge = "Scoped to /dev"
audit_logs = "Audit Logs"
clients = "Connected Application"
developer_request = "Developer Access Request"
developer_grants = "Developer Access Grants"
logout = "Logout"
overview = "Overview"
@@ -1309,6 +1338,29 @@ cancel_notes_placeholder = "Enter reason for approval cancellation..."
[ui.dev.request.list]
title = "Request History"
[ui.dev.grants]
actions = "Actions"
admin_notes = "Grant Reason"
all_tenants = "All Tenants"
approved = "Approved"
date = "Granted At"
form.title = "Direct Grant"
grant = "Grant Directly"
input_section = "Input"
list.title = "Granted Access"
read_only = "Read Only"
reason = "Grant Reason"
reason_placeholder = "e.g. Developer console access is required for operational support."
required = "Required"
selected_info = "Selected User Info"
revoke = "Revoke"
revoke_notes_placeholder = "Revoke note (optional)..."
status = "Status"
tenant = "Affiliation"
user_section = "User Selection"
user = "User"
user_search_placeholder = "Search by name or email..."
[ui.dev.request.modal]
email = "Email"
name = "Name"

View File

@@ -543,6 +543,7 @@ unavailable_with_reason = "RP 이용 통계 API 응답을 확인할 수 없습
audit = "RP 설정 변경과 운영 이력을 확인합니다."
clients = "등록된 RP를 조회하고 상태와 유형을 관리합니다."
description = "주요 운영 화면으로 바로 이동합니다."
developer_grants = "사용자에게 개발자 권한을 직접 부여하거나 회수합니다."
developer_request = "개발자 권한 신청 내역을 확인하거나 새 요청을 등록합니다."
new_client = "redirect URI, grant type, 인증 방식을 설정합니다."
@@ -554,6 +555,33 @@ none = "표시할 연동 앱이 없습니다."
description = "변경 또는 삭제된 애플리케이션을 대시보드에서 추이를 확인합니다."
empty = "최근 변경 로그가 아직 없습니다."
[msg.dev.grants]
approved = "승인됨"
count = "총 {{count}}건"
create_success = "개발자 권한을 직접 부여했습니다."
description = "사용자에게 개발자 권한을 직접 부여하고, 부여된 권한을 회수합니다."
admin_notes_hint = "회수는 목록의 회수 버튼으로 처리합니다."
admin_notes_description = "직접 부여의 근거를 간단히 남겨 두면 추후 회수와 검토에 도움이 됩니다."
admin_notes_placeholder = "예: 테스트 환경 확인 후 권한 부여"
empty = "부여된 권한이 없습니다."
forbidden = "개발자 권한 직접 부여는 super admin만 사용할 수 있습니다."
forbidden_desc = "이 화면은 super admin만 사용할 수 있습니다."
form.description = "사용자를 선택하면 현재 소속 테넌트, 이메일, 전화번호를 확인한 뒤 개발자 권한을 즉시 부여합니다."
selected_info_description = "선택된 사용자의 소속, 이메일, 전화번호를 확인합니다."
user_section_description = "검색어를 입력해 사용자를 선택합니다. 선택 전에는 다음 단계 정보가 비어 있습니다."
list.description = "현재 부여된 개발자 권한 목록입니다."
load_error = "개발자 권한 목록을 불러오지 못했습니다."
reason = "부여 사유"
revoke = "회수"
revoke_success = "개발자 권한을 회수했습니다."
search_empty = "검색 결과가 없습니다."
search_loading = "사용자를 찾는 중입니다..."
selected_user = "선택된 사용자: {{user}}"
tenant_required = "선택한 사용자의 테넌트 정보를 확인할 수 없습니다."
tenant_missing = "선택한 사용자의 테넌트 정보를 확인할 수 없습니다."
user_required = "부여할 사용자를 선택해주세요."
phone_missing = "등록된 전화번호가 없습니다."
[msg.dev.dashboard.notice]
consent_audit = "Consent 회수는 감사 로그와 연계"
dev_scope = "RP 정책은 dev scope에서만 적용"
@@ -1294,6 +1322,7 @@ scope_badge = "Scoped to /dev"
audit_logs = "감사 로그"
clients = "연동 앱"
developer_request = "개발자 권한 신청"
developer_grants = "개발자 권한 부여"
logout = "로그아웃"
overview = "개요"
@@ -1309,6 +1338,29 @@ cancel_notes_placeholder = "승인 취소 사유 입력..."
[ui.dev.request.list]
title = "신청 내역"
[ui.dev.grants]
actions = "관리"
admin_notes = "부여 사유"
all_tenants = "전체 테넌트"
approved = "승인됨"
date = "부여일"
form.title = "직접 부여"
grant = "직접 부여"
input_section = "입력"
list.title = "부여된 권한"
read_only = "읽기 전용"
reason = "부여 사유"
reason_placeholder = "예: 운영 지원을 위해 개발 콘솔 접근이 필요합니다."
required = "필수"
selected_info = "선택된 사용자 정보"
revoke = "회수"
revoke_notes_placeholder = "회수 메모 (선택)..."
status = "상태"
tenant = "소속"
user_section = "사용자 선택"
user = "사용자"
user_search_placeholder = "이름 또는 이메일 검색..."
[ui.dev.request.modal]
email = "이메일"
name = "성함"

View File

@@ -581,6 +581,7 @@ unavailable_with_reason = ""
audit = ""
clients = ""
description = ""
developer_grants = ""
developer_request = ""
new_client = ""
@@ -592,6 +593,34 @@ none = ""
description = ""
empty = ""
[msg.dev.grants]
approved = ""
count = ""
create_success = ""
description = ""
admin_notes_hint = ""
admin_notes_description = ""
admin_notes_placeholder = ""
empty = ""
forbidden = ""
forbidden_desc = ""
form.description = ""
selected_info_description = ""
user_section_description = ""
list.description = ""
load_error = ""
reason = ""
revoke = ""
revoke_success = ""
search_empty = ""
search_loading = ""
selected_user = ""
tenant_required = ""
tenant_missing = ""
user_required = ""
phone_missing = ""
required = ""
[msg.dev.dashboard.notice]
consent_audit = ""
dev_scope = ""
@@ -1347,6 +1376,7 @@ scope_badge = ""
audit_logs = ""
clients = ""
developer_request = ""
developer_grants = ""
logout = ""
overview = ""
@@ -1361,6 +1391,29 @@ cancel_notes_placeholder = ""
[ui.dev.request.list]
title = ""
[ui.dev.grants]
actions = ""
admin_notes = ""
all_tenants = ""
approved = ""
date = ""
form.title = ""
grant = ""
input_section = ""
list.title = ""
read_only = ""
reason = ""
reason_placeholder = ""
required = ""
selected_info = ""
revoke = ""
revoke_notes_placeholder = ""
status = ""
tenant = ""
user_section = ""
user = ""
user_search_placeholder = ""
[ui.dev.request.modal]
email = ""
name = ""