feat(auth): Add optional authentication system (#22)
Some checks failed
CI / style (push) Has been cancelled
CI / build-client (push) Has been cancelled
CI / build-amd64 (push) Has been cancelled
CI / build-tester (push) Has been cancelled
CI / test (cockroachdb) (push) Has been cancelled
CI / test (mariadb) (push) Has been cancelled
CI / test (postgres) (push) Has been cancelled
CI / test (sqlite) (push) Has been cancelled
CI / build-arm64 (push) Has been cancelled
CI / build-armv7 (push) Has been cancelled
CI / publish-images (push) Has been cancelled
CI / publish-release (push) Has been cancelled
Some checks failed
CI / style (push) Has been cancelled
CI / build-client (push) Has been cancelled
CI / build-amd64 (push) Has been cancelled
CI / build-tester (push) Has been cancelled
CI / test (cockroachdb) (push) Has been cancelled
CI / test (mariadb) (push) Has been cancelled
CI / test (postgres) (push) Has been cancelled
CI / test (sqlite) (push) Has been cancelled
CI / build-arm64 (push) Has been cancelled
CI / build-armv7 (push) Has been cancelled
CI / publish-images (push) Has been cancelled
CI / publish-release (push) Has been cancelled
Backend: - Add User model with username, hashed password, role, is_active - Add passlib[bcrypt] and python-jose[cryptography] dependencies - Create auth.py with JWT utilities, password hashing, role checking - Add /auth endpoints: status, setup, login, me, users CRUD - Add role-based permission system (viewer/operator/editor/admin) - Environment: SPOOLMAN_AUTH_ENABLED, SPOOLMAN_AUTH_SECRET_KEY - Migration for user table Frontend: - Add AuthProvider context with login/logout/setup - Add LoginPage component with setup mode for first user - Add ProtectedRoute wrapper for auth-required pages - Add axios interceptor to attach JWT token to requests - Add User Management tab in Settings (admin only) - Add translation keys for auth UI When SPOOLMAN_AUTH_ENABLED=true: - Users must login to access the app - First visit shows setup page to create admin account - Role-based access control for future endpoint protection Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -420,6 +420,39 @@
|
||||
"key_not_changed": "Please change the key to something else.",
|
||||
"delete_confirm": "Delete field {{name}}?",
|
||||
"delete_confirm_description": "This will delete the field and all associated data for all entities."
|
||||
},
|
||||
"users": {
|
||||
"tab": "Users",
|
||||
"title": "User Management",
|
||||
"add": "Add User",
|
||||
"edit": "Edit User",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"role": "Role",
|
||||
"status": "Status",
|
||||
"actions": "Actions",
|
||||
"active": "Active",
|
||||
"inactive": "Inactive",
|
||||
"you": "You",
|
||||
"created": "User created successfully",
|
||||
"updated": "User updated successfully",
|
||||
"deleted": "User deleted successfully",
|
||||
"delete_confirm": "Are you sure you want to delete this user?",
|
||||
"username_required": "Username is required",
|
||||
"username_min": "Username must be at least 3 characters",
|
||||
"password_required": "Password is required",
|
||||
"password_min": "Password must be at least 6 characters",
|
||||
"password_change_hint": "Leave blank to keep current password",
|
||||
"leave_blank": "Leave blank to keep current",
|
||||
"role_viewer": "Viewer - Can only view data",
|
||||
"role_operator": "Operator - Can view and record usage",
|
||||
"role_editor": "Editor - Can view, use, create, and edit",
|
||||
"role_admin": "Admin - Full access including user management",
|
||||
"auth_disabled": "Authentication is not enabled",
|
||||
"auth_disabled_hint": "Set SPOOLMAN_AUTH_ENABLED=true to enable user management",
|
||||
"admin_required": "Admin Access Required",
|
||||
"admin_required_hint": "Only administrators can manage users",
|
||||
"logout": "Log Out"
|
||||
}
|
||||
},
|
||||
"documentTitle": {
|
||||
|
||||
@@ -27,10 +27,16 @@ import { Favicon } from "./components/favicon";
|
||||
import { SpoolmanLayout } from "./components/layout";
|
||||
import liveProvider from "./components/liveProvider";
|
||||
import SpoolmanNotificationProvider from "./components/notificationProvider";
|
||||
import { ProtectedRoute } from "./components/protectedRoute";
|
||||
import { AuthProvider, useAuth } from "./contexts/auth";
|
||||
import { ColorModeContextProvider } from "./contexts/color-mode";
|
||||
import { languages } from "./i18n";
|
||||
import { setupAxiosAuth } from "./utils/axiosAuth";
|
||||
import { getAPIURL, getBasePath } from "./utils/url";
|
||||
|
||||
// Setup axios auth interceptors once at module load
|
||||
setupAxiosAuth();
|
||||
|
||||
interface ResourcePageProps {
|
||||
resource: "spools" | "filaments" | "vendors";
|
||||
page: "list" | "create" | "edit" | "show";
|
||||
@@ -54,6 +60,11 @@ const LoadablePage = loadable((props: LoadablePageProps) => import(`./pages/${pr
|
||||
cacheKey: (props: LoadablePageProps) => `page-${props.name}`,
|
||||
});
|
||||
|
||||
// Lazy load login page
|
||||
const LoginPage = loadable(() => import("./pages/login/index"), {
|
||||
fallback: <div>Loading...</div>,
|
||||
});
|
||||
|
||||
function App() {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
@@ -89,10 +100,11 @@ function App() {
|
||||
|
||||
return (
|
||||
<BrowserRouter basename={getBasePath() + "/"}>
|
||||
<RefineKbarProvider>
|
||||
<ColorModeContextProvider>
|
||||
<ConfigProvider locale={antdLocale}>
|
||||
<Refine
|
||||
<AuthProvider>
|
||||
<RefineKbarProvider>
|
||||
<ColorModeContextProvider>
|
||||
<ConfigProvider locale={antdLocale}>
|
||||
<Refine
|
||||
dataProvider={dataProvider(getAPIURL())}
|
||||
notificationProvider={SpoolmanNotificationProvider}
|
||||
i18nProvider={i18nProvider}
|
||||
@@ -183,11 +195,17 @@ function App() {
|
||||
}}
|
||||
>
|
||||
<Routes>
|
||||
{/* Login route - outside protected area */}
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
|
||||
{/* Protected routes */}
|
||||
<Route
|
||||
element={
|
||||
<SpoolmanLayout>
|
||||
<Outlet />
|
||||
</SpoolmanLayout>
|
||||
<ProtectedRoute>
|
||||
<SpoolmanLayout>
|
||||
<Outlet />
|
||||
</SpoolmanLayout>
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
<Route index element={<LoadablePage name="home" />} />
|
||||
@@ -245,9 +263,10 @@ function App() {
|
||||
<ReactQueryDevtools />
|
||||
<Favicon url={getBasePath() + "/favicon.svg"} />
|
||||
</Refine>
|
||||
</ConfigProvider>
|
||||
</ColorModeContextProvider>
|
||||
</RefineKbarProvider>
|
||||
</ConfigProvider>
|
||||
</ColorModeContextProvider>
|
||||
</RefineKbarProvider>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
28
client/src/components/protectedRoute.tsx
Normal file
28
client/src/components/protectedRoute.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Spin } from "antd";
|
||||
import React from "react";
|
||||
import { Navigate } from "react-router";
|
||||
import { useAuth } from "../contexts/auth";
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
|
||||
const { isAuthenticated, isLoading, authStatus } = useAuth();
|
||||
|
||||
// Show loading while checking auth
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh" }}>
|
||||
<Spin size="large" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// If auth is enabled but not authenticated, redirect to login
|
||||
if (authStatus?.enabled && !isAuthenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
174
client/src/contexts/auth/index.tsx
Normal file
174
client/src/contexts/auth/index.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
import React, { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { getAPIURL } from "../../utils/url";
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
role: "admin" | "editor" | "operator" | "viewer";
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AuthStatus {
|
||||
enabled: boolean;
|
||||
has_users: boolean;
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
authStatus: AuthStatus | null;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
setup: (username: string, password: string) => Promise<void>;
|
||||
refreshAuthStatus: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
const TOKEN_KEY = "spoolman_auth_token";
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [token, setToken] = useState<string | null>(() => localStorage.getItem(TOKEN_KEY));
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [authStatus, setAuthStatus] = useState<AuthStatus | null>(null);
|
||||
|
||||
const apiUrl = getAPIURL();
|
||||
|
||||
// Fetch auth status
|
||||
const refreshAuthStatus = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}/auth/status`);
|
||||
if (res.ok) {
|
||||
const status = await res.json();
|
||||
setAuthStatus(status);
|
||||
return status;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch auth status:", err);
|
||||
}
|
||||
return null;
|
||||
}, [apiUrl]);
|
||||
|
||||
// Fetch current user if we have a token
|
||||
const fetchUser = useCallback(async (authToken: string) => {
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
});
|
||||
if (res.ok) {
|
||||
const userData = await res.json();
|
||||
setUser(userData);
|
||||
return true;
|
||||
} else {
|
||||
// Token invalid, clear it
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch user:", err);
|
||||
return false;
|
||||
}
|
||||
}, [apiUrl]);
|
||||
|
||||
// Initialize auth state
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
setIsLoading(true);
|
||||
const status = await refreshAuthStatus();
|
||||
|
||||
if (status?.enabled && token) {
|
||||
await fetchUser(token);
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
};
|
||||
init();
|
||||
}, [refreshAuthStatus, fetchUser, token]);
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append("username", username);
|
||||
formData.append("password", password);
|
||||
|
||||
const res = await fetch(`${apiUrl}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Login failed");
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
localStorage.setItem(TOKEN_KEY, data.access_token);
|
||||
setToken(data.access_token);
|
||||
await fetchUser(data.access_token);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
const setup = async (username: string, password: string) => {
|
||||
const res = await fetch(`${apiUrl}/auth/setup`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Setup failed");
|
||||
}
|
||||
|
||||
// After setup, log in
|
||||
await login(username, password);
|
||||
await refreshAuthStatus();
|
||||
};
|
||||
|
||||
const isAuthenticated = !!user || !authStatus?.enabled;
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
token,
|
||||
isAuthenticated,
|
||||
isLoading,
|
||||
authStatus,
|
||||
login,
|
||||
logout,
|
||||
setup,
|
||||
refreshAuthStatus,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useAuth must be used within an AuthProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
// Helper to check if user has minimum role
|
||||
export const hasRole = (user: User | null, minRole: "viewer" | "operator" | "editor" | "admin"): boolean => {
|
||||
if (!user) return false;
|
||||
|
||||
const roleHierarchy = { viewer: 0, operator: 1, editor: 2, admin: 3 };
|
||||
return roleHierarchy[user.role] >= roleHierarchy[minRole];
|
||||
};
|
||||
98
client/src/pages/login/index.tsx
Normal file
98
client/src/pages/login/index.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import { LockOutlined, UserOutlined } from "@ant-design/icons";
|
||||
import { Button, Card, Form, Input, message, Typography } from "antd";
|
||||
import React, { useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useAuth } from "../../contexts/auth";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
interface LoginForm {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export const LoginPage: React.FC = () => {
|
||||
const { login, setup, authStatus, refreshAuthStatus } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSetupMode, setIsSetupMode] = useState(false);
|
||||
|
||||
const needsSetup = authStatus?.enabled && !authStatus?.has_users;
|
||||
|
||||
const handleSubmit = async (values: LoginForm) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (needsSetup || isSetupMode) {
|
||||
await setup(values.username, values.password);
|
||||
message.success("Admin account created successfully!");
|
||||
} else {
|
||||
await login(values.username, values.password);
|
||||
message.success("Logged in successfully!");
|
||||
}
|
||||
navigate("/");
|
||||
} catch (err) {
|
||||
message.error(err instanceof Error ? err.message : "Authentication failed");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
minHeight: "100vh",
|
||||
background: "#f0f2f5",
|
||||
}}
|
||||
>
|
||||
<Card style={{ width: 400, boxShadow: "0 4px 12px rgba(0,0,0,0.1)" }}>
|
||||
<div style={{ textAlign: "center", marginBottom: 24 }}>
|
||||
<Title level={2} style={{ marginBottom: 8 }}>
|
||||
Spoolman
|
||||
</Title>
|
||||
<Text type="secondary">
|
||||
{needsSetup || isSetupMode ? "Create Admin Account" : "Sign in to continue"}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Form<LoginForm> name="login" onFinish={handleSubmit} layout="vertical" requiredMark={false}>
|
||||
<Form.Item
|
||||
name="username"
|
||||
rules={[
|
||||
{ required: true, message: "Please enter your username" },
|
||||
{ min: 3, message: "Username must be at least 3 characters" },
|
||||
]}
|
||||
>
|
||||
<Input prefix={<UserOutlined />} placeholder="Username" size="large" autoFocus />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
rules={[
|
||||
{ required: true, message: "Please enter your password" },
|
||||
{ min: 6, message: "Password must be at least 6 characters" },
|
||||
]}
|
||||
>
|
||||
<Input.Password prefix={<LockOutlined />} placeholder="Password" size="large" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item style={{ marginBottom: 12 }}>
|
||||
<Button type="primary" htmlType="submit" size="large" block loading={isLoading}>
|
||||
{needsSetup || isSetupMode ? "Create Account" : "Sign In"}
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
{needsSetup && (
|
||||
<Text type="secondary" style={{ display: "block", textAlign: "center" }}>
|
||||
This is the first time setup. Create an admin account to get started.
|
||||
</Text>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileOutlined, HighlightOutlined, SolutionOutlined, ToolOutlined, UserOutlined } from "@ant-design/icons";
|
||||
import { FileOutlined, HighlightOutlined, SolutionOutlined, TeamOutlined, ToolOutlined, UserOutlined } from "@ant-design/icons";
|
||||
import { IResourceComponentsProps, useTranslate } from "@refinedev/core";
|
||||
import { Menu, theme } from "antd";
|
||||
import { Content } from "antd/es/layout/layout";
|
||||
@@ -8,6 +8,7 @@ import React from "react";
|
||||
import { Route, Routes, useNavigate } from "react-router";
|
||||
import { ExtraFieldsSettings } from "./extraFieldsSettings";
|
||||
import { GeneralSettings } from "./generalSettings";
|
||||
import { UserSettings } from "./userSettings";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
@@ -58,6 +59,7 @@ export const Settings: React.FC<IResourceComponentsProps> = () => {
|
||||
}}
|
||||
items={[
|
||||
{ key: "", label: t("settings.general.tab"), icon: <ToolOutlined /> },
|
||||
{ key: "users", label: t("settings.users.tab"), icon: <TeamOutlined /> },
|
||||
{
|
||||
key: "extra",
|
||||
label: t("settings.extra_fields.tab"),
|
||||
@@ -88,6 +90,7 @@ export const Settings: React.FC<IResourceComponentsProps> = () => {
|
||||
<main>
|
||||
<Routes>
|
||||
<Route index element={<GeneralSettings />} />
|
||||
<Route path="/users" element={<UserSettings />} />
|
||||
<Route path="/extra/:entityType" element={<ExtraFieldsSettings />} />
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
285
client/src/pages/settings/userSettings.tsx
Normal file
285
client/src/pages/settings/userSettings.tsx
Normal file
@@ -0,0 +1,285 @@
|
||||
import { DeleteOutlined, EditOutlined, PlusOutlined, UserOutlined } from "@ant-design/icons";
|
||||
import { useTranslate } from "@refinedev/core";
|
||||
import { Button, Form, Input, message, Modal, Popconfirm, Select, Space, Table, Tag, Typography } from "antd";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { hasRole, useAuth, User } from "../../contexts/auth";
|
||||
import { getAPIURL } from "../../utils/url";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
interface UserFormValues {
|
||||
username: string;
|
||||
password?: string;
|
||||
role: "admin" | "editor" | "operator" | "viewer";
|
||||
}
|
||||
|
||||
export const UserSettings: React.FC = () => {
|
||||
const t = useTranslate();
|
||||
const { user: currentUser, token, authStatus, logout } = useAuth();
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||
const [form] = Form.useForm<UserFormValues>();
|
||||
|
||||
const apiUrl = getAPIURL();
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}/auth/users`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (res.ok) {
|
||||
setUsers(await res.json());
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch users:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [apiUrl, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (authStatus?.enabled && hasRole(currentUser, "admin")) {
|
||||
fetchUsers();
|
||||
}
|
||||
}, [authStatus, currentUser, fetchUsers]);
|
||||
|
||||
const handleCreate = async (values: UserFormValues) => {
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}/auth/users`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Failed to create user");
|
||||
}
|
||||
message.success(t("settings.users.created"));
|
||||
setModalOpen(false);
|
||||
form.resetFields();
|
||||
fetchUsers();
|
||||
} catch (err) {
|
||||
message.error(err instanceof Error ? err.message : "Failed to create user");
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (values: UserFormValues) => {
|
||||
if (!editingUser) return;
|
||||
try {
|
||||
const body: Partial<UserFormValues> = { role: values.role };
|
||||
if (values.password) {
|
||||
body.password = values.password;
|
||||
}
|
||||
const res = await fetch(`${apiUrl}/auth/users/${editingUser.id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Failed to update user");
|
||||
}
|
||||
message.success(t("settings.users.updated"));
|
||||
setModalOpen(false);
|
||||
setEditingUser(null);
|
||||
form.resetFields();
|
||||
fetchUsers();
|
||||
} catch (err) {
|
||||
message.error(err instanceof Error ? err.message : "Failed to update user");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (userId: number) => {
|
||||
try {
|
||||
const res = await fetch(`${apiUrl}/auth/users/${userId}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Failed to delete user");
|
||||
}
|
||||
message.success(t("settings.users.deleted"));
|
||||
fetchUsers();
|
||||
} catch (err) {
|
||||
message.error(err instanceof Error ? err.message : "Failed to delete user");
|
||||
}
|
||||
};
|
||||
|
||||
const openCreateModal = () => {
|
||||
setEditingUser(null);
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ role: "viewer" });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const openEditModal = (user: User) => {
|
||||
setEditingUser(user);
|
||||
form.setFieldsValue({ username: user.username, role: user.role, password: undefined });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const roleColors: Record<string, string> = {
|
||||
admin: "red",
|
||||
editor: "blue",
|
||||
operator: "green",
|
||||
viewer: "default",
|
||||
};
|
||||
|
||||
// If auth is not enabled, show message
|
||||
if (!authStatus?.enabled) {
|
||||
return (
|
||||
<div style={{ textAlign: "center", padding: 40 }}>
|
||||
<UserOutlined style={{ fontSize: 48, color: "#999", marginBottom: 16 }} />
|
||||
<Title level={4}>{t("settings.users.auth_disabled")}</Title>
|
||||
<Text type="secondary">{t("settings.users.auth_disabled_hint")}</Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// If user is not admin, show access denied
|
||||
if (!hasRole(currentUser, "admin")) {
|
||||
return (
|
||||
<div style={{ textAlign: "center", padding: 40 }}>
|
||||
<UserOutlined style={{ fontSize: 48, color: "#999", marginBottom: 16 }} />
|
||||
<Title level={4}>{t("settings.users.admin_required")}</Title>
|
||||
<Text type="secondary">{t("settings.users.admin_required_hint")}</Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
{t("settings.users.title")}
|
||||
</Title>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreateModal}>
|
||||
{t("settings.users.add")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table<User>
|
||||
dataSource={users}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
columns={[
|
||||
{
|
||||
title: t("settings.users.username"),
|
||||
dataIndex: "username",
|
||||
key: "username",
|
||||
render: (username: string, record: User) => (
|
||||
<Space>
|
||||
<UserOutlined />
|
||||
{username}
|
||||
{record.id === currentUser?.id && <Tag>{t("settings.users.you")}</Tag>}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("settings.users.role"),
|
||||
dataIndex: "role",
|
||||
key: "role",
|
||||
render: (role: string) => <Tag color={roleColors[role]}>{role.toUpperCase()}</Tag>,
|
||||
},
|
||||
{
|
||||
title: t("settings.users.status"),
|
||||
dataIndex: "is_active",
|
||||
key: "is_active",
|
||||
render: (isActive: boolean) => (
|
||||
<Tag color={isActive ? "green" : "red"}>{isActive ? t("settings.users.active") : t("settings.users.inactive")}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("settings.users.actions"),
|
||||
key: "actions",
|
||||
width: 120,
|
||||
render: (_: unknown, record: User) => (
|
||||
<Space>
|
||||
<Button size="small" icon={<EditOutlined />} onClick={() => openEditModal(record)} />
|
||||
<Popconfirm
|
||||
title={t("settings.users.delete_confirm")}
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
disabled={record.id === currentUser?.id}
|
||||
>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} disabled={record.id === currentUser?.id} />
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title={editingUser ? t("settings.users.edit") : t("settings.users.add")}
|
||||
open={modalOpen}
|
||||
onCancel={() => {
|
||||
setModalOpen(false);
|
||||
setEditingUser(null);
|
||||
form.resetFields();
|
||||
}}
|
||||
onOk={() => form.submit()}
|
||||
okText={editingUser ? t("buttons.save") : t("buttons.create")}
|
||||
>
|
||||
<Form<UserFormValues>
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={editingUser ? handleUpdate : handleCreate}
|
||||
>
|
||||
<Form.Item
|
||||
name="username"
|
||||
label={t("settings.users.username")}
|
||||
rules={[
|
||||
{ required: !editingUser, message: t("settings.users.username_required") },
|
||||
{ min: 3, message: t("settings.users.username_min") },
|
||||
]}
|
||||
>
|
||||
<Input disabled={!!editingUser} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="password"
|
||||
label={t("settings.users.password")}
|
||||
rules={[
|
||||
{ required: !editingUser, message: t("settings.users.password_required") },
|
||||
{ min: 6, message: t("settings.users.password_min") },
|
||||
]}
|
||||
help={editingUser ? t("settings.users.password_change_hint") : undefined}
|
||||
>
|
||||
<Input.Password placeholder={editingUser ? t("settings.users.leave_blank") : undefined} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="role"
|
||||
label={t("settings.users.role")}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Select>
|
||||
<Select.Option value="viewer">{t("settings.users.role_viewer")}</Select.Option>
|
||||
<Select.Option value="operator">{t("settings.users.role_operator")}</Select.Option>
|
||||
<Select.Option value="editor">{t("settings.users.role_editor")}</Select.Option>
|
||||
<Select.Option value="admin">{t("settings.users.role_admin")}</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{currentUser && (
|
||||
<div style={{ marginTop: 24, textAlign: "center" }}>
|
||||
<Button onClick={logout}>{t("settings.users.logout")}</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserSettings;
|
||||
34
client/src/utils/axiosAuth.ts
Normal file
34
client/src/utils/axiosAuth.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { axiosInstance } from "@refinedev/simple-rest";
|
||||
|
||||
const TOKEN_KEY = "spoolman_auth_token";
|
||||
|
||||
/**
|
||||
* Setup axios interceptor to add auth token to requests.
|
||||
* Should be called once at app initialization.
|
||||
*/
|
||||
export function setupAxiosAuth() {
|
||||
axiosInstance.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = localStorage.getItem(TOKEN_KEY);
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// Handle 401 responses by clearing token
|
||||
axiosInstance.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
// Clear invalid token
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
// Optionally redirect to login
|
||||
// window.location.href = "/login";
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user