Add user management features.

This commit is contained in:
2025-05-14 18:49:49 +08:00
parent 3b7d52a7a8
commit 703812d3df
10 changed files with 447 additions and 40 deletions

View File

@@ -0,0 +1,14 @@
import { ReactNode } from "react";
export default function Button({ children, onClick, className, disabled, isLoading }: { children: ReactNode, onClick?: () => void, className?: string, disabled?: boolean, isLoading?: boolean }) {
return <button
className={`btn ${className} ${disabled ? "btn-disabled" : ""} h-9`}
onClick={onClick}
disabled={disabled}
>
{isLoading && <span className="loading loading-spinner loading-sm mr-2"></span>}
<span className="text-sm">
{children}
</span>
</button>;
}

View File

@@ -1,19 +1,27 @@
import {app} from "../app.ts";
import {network} from "../network/network.ts";
import {useNavigate, useOutlet} from "react-router";
import {useEffect, useState} from "react";
import {MdOutlinePerson, MdSearch, MdSettings} from "react-icons/md";
import { app } from "../app.ts";
import { network } from "../network/network.ts";
import { useNavigate, useOutlet } from "react-router";
import { createContext, useContext, useEffect, useState } from "react";
import { MdOutlinePerson, MdSearch, MdSettings } from "react-icons/md";
import { useTranslation } from "react-i18next";
import UploadingSideBar from "./uploading_side_bar.tsx";
import {IoLogoGithub} from "react-icons/io";
import { IoLogoGithub } from "react-icons/io";
export default function Navigator() {
const outlet = useOutlet()
const navigate = useNavigate()
const [key, setKey] = useState(0);
const [naviContext, _] = useState<NavigatorContext>({
refresh: () => {
setKey(key + 1);
},
});
return <>
<div className="navbar bg-base-100 shadow-sm fixed top-0 z-1 lg:z-10">
<div className="navbar bg-base-100 shadow-sm fixed top-0 z-1 lg:z-10" key={key}>
<div className={"flex-1 max-w-7xl mx-auto flex"}>
<div className="flex-1">
<button className="btn btn-ghost text-xl" onClick={() => {
@@ -21,22 +29,22 @@ export default function Navigator() {
}}>{app.appName}</button>
</div>
<div className="flex gap-2">
<SearchBar/>
<UploadingSideBar/>
<SearchBar />
<UploadingSideBar />
{
app.isAdmin() && <button className={"btn btn-circle btn-ghost"} onClick={() => {
navigate("/manage");
}}>
<MdSettings size={24}/>
<MdSettings size={24} />
</button>
}
<button className={"btn btn-circle btn-ghost"} onClick={() => {
window.open("https://github.com/wgh136/nysoure", "_blank");
}}>
<IoLogoGithub size={24}/>
<IoLogoGithub size={24} />
</button>
{
app.isLoggedIn() ? <UserButton/> : <button className={"btn btn-primary btn-square btn-soft"} onClick={() => {
app.isLoggedIn() ? <UserButton /> : <button className={"btn btn-primary btn-square btn-soft"} onClick={() => {
navigate("/login");
}}>
<MdOutlinePerson size={24}></MdOutlinePerson>
@@ -45,12 +53,28 @@ export default function Navigator() {
</div>
</div>
</div>
<navigatorContext.Provider value={naviContext}>
<div className={"max-w-7xl mx-auto pt-16"}>
{outlet}
</div>
</navigatorContext.Provider>
</>
}
interface NavigatorContext {
refresh: () => void;
}
const navigatorContext = createContext<NavigatorContext>({
refresh: () => {
// do nothing
}
})
export function useNavigator() {
return useContext(navigatorContext);
}
function UserButton() {
let avatar = "./avatar.png";
if (app.user) {
@@ -59,7 +83,7 @@ function UserButton() {
const navigate = useNavigate()
const {t} = useTranslation()
const { t } = useTranslation()
return <>
<div className="dropdown dropdown-end">
@@ -67,7 +91,7 @@ function UserButton() {
<div className="w-10 rounded-full">
<img
alt="Avatar"
src={avatar}/>
src={avatar} />
</div>
</div>
<ul
@@ -101,7 +125,7 @@ function UserButton() {
app.user = null;
app.token = null;
app.saveData();
navigate(`/login`, {replace: true});
navigate(`/login`, { replace: true });
}}>{t('Confirm')}
</button>
</form>
@@ -118,7 +142,7 @@ function SearchBar() {
const [search, setSearch] = useState("");
const {t} = useTranslation();
const { t } = useTranslation();
useEffect(() => {
const handleResize = () => {
@@ -141,10 +165,10 @@ function SearchBar() {
return;
}
const replace = window.location.pathname === "/search";
navigate(`/search?keyword=${search}`, {replace: replace});
navigate(`/search?keyword=${search}`, { replace: replace });
}
const searchField = <label className={`input input-primary ${small ? "w-full": "w-64"}`}>
const searchField = <label className={`input input-primary ${small ? "w-full" : "w-64"}`}>
<svg className="h-[1em] opacity-50" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<g
stroke-linejoin="round"
@@ -161,7 +185,7 @@ function SearchBar() {
e.preventDefault();
doSearch();
}}>
<input type="search" className={"w-full"} required placeholder={t("Search")} value={search} onChange={(e) => setSearch(e.target.value)}/>
<input type="search" className={"w-full"} required placeholder={t("Search")} value={search} onChange={(e) => setSearch(e.target.value)} />
</form>
</label>
@@ -171,7 +195,7 @@ function SearchBar() {
const dialog = document.getElementById("search_dialog") as HTMLDialogElement;
dialog.showModal();
}}>
<MdSearch size={24}/>
<MdSearch size={24} />
</button>
<dialog id="search_dialog" className="modal">
<div className="modal-box">
@@ -179,9 +203,9 @@ function SearchBar() {
<button className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"></button>
</form>
<h3 className="text-lg font-bold">{t("Search")}</h3>
<div className={"h-4"}/>
<div className={"h-4"} />
{searchField}
<div className={"h-4"}/>
<div className={"h-4"} />
<div className={"flex flex-row-reverse"}>
<button className={"btn btn-primary"} onClick={() => {
if (search.length === 0) {

View File

@@ -141,6 +141,21 @@ class Network {
}
}
async changeUsername(username: string): Promise<Response<User>> {
try {
const response = await axios.postForm(`${this.apiBaseUrl}/user/username`, {
username
})
return response.data
} catch (e: any) {
console.error(e)
return {
success: false,
message: e.toString(),
}
}
}
getUserAvatar(user: User): string {
return this.baseUrl + user.avatar_path
}

View File

@@ -0,0 +1,296 @@
import { useTranslation } from "react-i18next";
import { app } from "../app";
import { ErrorAlert } from "../components/alert";
import { network } from "../network/network";
import { ReactNode, useState } from "react";
import { MdOutlineAccountCircle, MdLockOutline, MdOutlineEditNote } from "react-icons/md";
import Button from "../components/button";
import showToast from "../components/toast";
import { useNavigator } from "../components/navigator";
export function ManageMePage() {
const { t } = useTranslation();
if (!app.user) {
return <ErrorAlert className={"m-4"} message={t("You are not logged in. Please log in to access this page.")} />
}
return <div className="px-2">
<ChangeAvatarDialog />
<ChangeUsernameDialog />
<ChangePasswordDialog />
</div>;
}
function ListTile({ title, icon, onClick }: { title: string, icon: ReactNode, onClick: () => void }) {
return <div className="flex flex-row items-center h-12 px-2 bg-base-100 hover:bg-gray-200 cursor-pointer duration-200" onClick={onClick}>
<div className="flex flex-row items-center">
<span className="text-2xl">
{icon}
</span>
<span className="ml-2">{title}</span>
</div>
</div>
}
function ChangeAvatarDialog() {
const [avatar, setAvatar] = useState<File | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const navigator = useNavigator();
const selectAvatar = () => {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.onchange = (e) => {
const files = (e.target as HTMLInputElement).files;
if (files && files.length > 0) {
setAvatar(files[0]);
}
};
input.click();
};
const handleSubmit = async () => {
if (!avatar) {
return;
}
setIsLoading(true);
const res = await network.changeAvatar(avatar);
if (!res.success) {
setError(res.message);
} else {
app.user = res.data!;
navigator.refresh();
showToast({
message: "Avatar changed successfully",
type: "success",
})
const dialog = document.getElementById("change_avatar_dialog") as HTMLDialogElement;
if (dialog) {
dialog.close();
}
}
}
return <>
<ListTile icon={<MdOutlineAccountCircle />} title="Change Avatar" onClick={() => {
const dialog = document.getElementById("change_avatar_dialog") as HTMLDialogElement;
if (dialog) {
dialog.showModal();
}
}} />
<dialog id="change_avatar_dialog" className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">Change Avatar</h3>
<div className="h-48 flex items-center justify-center">
<div className="avatar">
<div className="w-28 rounded-full cursor-pointer" onClick={selectAvatar}>
<img src={avatar ? URL.createObjectURL(avatar) : network.getUserAvatar(app.user!)} />
</div>
</div>
</div>
{error && <ErrorAlert message={error} className={"m-4"} />}
<div className="modal-action">
<form method="dialog">
<Button>Close</Button>
</form>
<Button className="btn-primary" onClick={handleSubmit} isLoading={isLoading} disabled={avatar == null}>Save</Button>
</div>
</div>
</dialog>
</>
}
function ChangeUsernameDialog() {
const [newUsername, setNewUsername] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const navigator = useNavigator();
const handleSubmit = async () => {
if (!newUsername.trim()) {
setError("Username cannot be empty");
return;
}
setIsLoading(true);
const res = await network.changeUsername(newUsername);
setIsLoading(false);
if (!res.success) {
setError(res.message);
} else {
app.user = res.data!;
navigator.refresh();
showToast({
message: "Username changed successfully",
type: "success",
});
const dialog = document.getElementById("change_username_dialog") as HTMLDialogElement;
if (dialog) {
dialog.close();
}
setNewUsername("");
setError(null);
}
};
return <>
<ListTile icon={<MdOutlineEditNote />} title="Change Username" onClick={() => {
const dialog = document.getElementById("change_username_dialog") as HTMLDialogElement;
if (dialog) {
dialog.showModal();
}
}} />
<dialog id="change_username_dialog" className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">Change Username</h3>
<div className="input mt-4 w-full">
<label className="label">
New Username
</label>
<input
type="text"
placeholder="Enter new username"
value={newUsername}
onChange={(e) => setNewUsername(e.target.value)}
/>
</div>
{error && <ErrorAlert message={error} className={"mt-4"} />}
<div className="modal-action">
<form method="dialog">
<Button>Close</Button>
</form>
<Button
className="btn-primary"
onClick={handleSubmit}
isLoading={isLoading}
disabled={!newUsername.trim()}
>
Save
</Button>
</div>
</div>
</dialog>
</>;
}
function ChangePasswordDialog() {
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async () => {
// Validate input
if (!oldPassword || !newPassword || !confirmPassword) {
setError("All fields are required");
return;
}
if (newPassword !== confirmPassword) {
setError("New passwords don't match");
return;
}
if (newPassword.length < 6) {
setError("New password must be at least 6 characters long");
return;
}
setIsLoading(true);
const res = await network.changePassword(oldPassword, newPassword);
setIsLoading(false);
if (!res.success) {
setError(res.message);
} else {
// Update the token as it might have changed
app.token = res.data!.token;
app.user = res.data!;
showToast({
message: "Password changed successfully",
type: "success",
});
const dialog = document.getElementById("change_password_dialog") as HTMLDialogElement;
if (dialog) {
dialog.close();
}
// Reset form
setOldPassword("");
setNewPassword("");
setConfirmPassword("");
setError(null);
}
};
return <>
<ListTile icon={<MdLockOutline />} title="Change Password" onClick={() => {
const dialog = document.getElementById("change_password_dialog") as HTMLDialogElement;
if (dialog) {
dialog.showModal();
}
}} />
<dialog id="change_password_dialog" className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg mb-2">Change Password</h3>
<fieldset className="fieldset w-full">
<legend className="fieldset-legend">Current Password</legend>
<input
type="password"
placeholder="Enter current password"
value={oldPassword}
className="input w-full"
onChange={(e) => setOldPassword(e.target.value)}
/>
</fieldset>
<fieldset className="fieldset w-full">
<legend className="fieldset-legend">New Password</legend>
<input
type="password"
placeholder="Enter new password"
value={newPassword}
className="input w-full"
onChange={(e) => setNewPassword(e.target.value)}
/>
</fieldset>
<fieldset className="fieldset w-full">
<legend className="fieldset-legend">Confirm New Password</legend>
<input
type="password"
placeholder="Confirm new password"
value={confirmPassword}
className="input w-full"
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</fieldset>
{error && <ErrorAlert message={error} className={"mt-4"} />}
<div className="modal-action">
<form method="dialog">
<Button>Close</Button>
</form>
<Button
className="btn-primary"
onClick={handleSubmit}
isLoading={isLoading}
disabled={!oldPassword || !newPassword || !confirmPassword}
>
Save
</Button>
</div>
</div>
</dialog>
</>;
}

View File

@@ -1,10 +1,9 @@
import {app} from "../app.ts";
import {MdMenu, MdOutlinePerson, MdOutlineStorage} from "react-icons/md";
import {MdMenu, MdOutlineBadge, MdOutlinePerson, MdOutlineStorage} from "react-icons/md";
import {ReactNode, useEffect, useState} from "react";
import StorageView from "./manage_storage_page.tsx";
import UserView from "./manage_user_page.tsx";
import { useTranslation } from "react-i18next";
import {ErrorAlert} from "../components/alert.tsx";
import { ManageMePage } from "./manage_me_page.tsx";
export default function ManagePage() {
const { t } = useTranslation();
@@ -24,16 +23,14 @@ export default function ManagePage() {
};
}, []);
if (!app.user) {
return <ErrorAlert className={"m-4"} message={t("You are not logged in. Please log in to access this page.")}/>
}
if (!app.user?.is_admin) {
return <ErrorAlert className={"m-4"} message={t("You are not authorized to access this page.")}/>
}
const buildItem = (title: string, icon: ReactNode, p: number) => {
return <li key={title} onClick={() => setPage(p)} className={"my-1"}>
return <li key={title} onClick={() => {
setPage(p);
const checkbox = document.getElementById("my-drawer-2") as HTMLInputElement;
if (checkbox) {
checkbox.checked = false;
}
}} className={"my-1"}>
<a className={`flex items-center h-9 px-4 ${page == p && "bg-primary text-primary-content"}`}>
{icon}
<span className={"text"}>
@@ -44,11 +41,13 @@ export default function ManagePage() {
}
const pageNames = [
t("My Info"),
t("Storage"),
t("Users")
]
const pageComponents = [
<ManageMePage/>,
<StorageView/>,
<UserView/>
]
@@ -78,8 +77,9 @@ export default function ManagePage() {
<h2 className={"text-lg font-bold p-4"}>
{t("Manage")}
</h2>
{buildItem(t("Storage"), <MdOutlineStorage className={"text-xl"}/>, 0)}
{buildItem(t("Users"), <MdOutlinePerson className={"text-xl"}/>, 1)}
{buildItem(t("My Info"), <MdOutlineBadge className={"text-xl"}/>, 0)}
{buildItem(t("Storage"), <MdOutlineStorage className={"text-xl"}/>, 1)}
{buildItem(t("Users"), <MdOutlinePerson className={"text-xl"}/>, 2)}
</ul>
</div>
</div>

View File

@@ -6,6 +6,7 @@ import Loading from "../components/loading.tsx";
import {MdAdd, MdDelete} from "react-icons/md";
import {ErrorAlert} from "../components/alert.tsx";
import { useTranslation } from "react-i18next";
import { app } from "../app.ts";
export default function StorageView() {
const { t } = useTranslation();
@@ -13,6 +14,9 @@ export default function StorageView() {
const [loadingId, setLoadingId] = useState<number | null>(null);
useEffect(() => {
if (app.user == null || !app.user.is_admin) {
return;
}
network.listStorages().then((response) => {
if (response.success) {
setStorages(response.data!);
@@ -25,6 +29,14 @@ export default function StorageView() {
})
}, []);
if (!app.user) {
return <ErrorAlert className={"m-4"} message={t("You are not logged in. Please log in to access this page.")}/>
}
if (!app.user?.is_admin) {
return <ErrorAlert className={"m-4"} message={t("You are not authorized to access this page.")}/>
}
if (storages == null) {
return <Loading/>
}

View File

@@ -7,6 +7,8 @@ import { MdMoreHoriz, MdSearch } from "react-icons/md";
import Pagination from "../components/pagination";
import showPopup, { PopupMenuItem } from "../components/popup";
import { useTranslation } from "react-i18next";
import { app } from "../app";
import { ErrorAlert } from "../components/alert";
export default function UserView() {
const { t } = useTranslation();
@@ -16,6 +18,14 @@ export default function UserView() {
const [totalPages, setTotalPages] = useState(0);
if (!app.user) {
return <ErrorAlert className={"m-4"} message={t("You are not logged in. Please log in to access this page.")} />
}
if (!app.user?.is_admin) {
return <ErrorAlert className={"m-4"} message={t("You are not authorized to access this page.")} />
}
return <>
<div className={"flex flex-row justify-between items-center mx-4 my-4"}>
<form className={"flex flex-row gap-2 items-center w-64"} onSubmit={(e) => {

View File

@@ -6,7 +6,7 @@ import { useEffect, useState } from "react";
import ResourcesView from "../components/resources_view";
import Loading from "../components/loading";
import Pagination from "../components/pagination";
import { MdOutlineArrowForward, MdOutlineArrowRight } from "react-icons/md";
import { MdOutlineArrowRight } from "react-icons/md";
export default function UserPage() {
const [user, setUser] = useState<User | null>(null);

View File

@@ -277,6 +277,26 @@ func handleGetUserInfo(c fiber.Ctx) error {
})
}
func handleChangeUsername(c fiber.Ctx) error {
uid, ok := c.Locals("uid").(uint)
if !ok {
return model.NewUnAuthorizedError("Unauthorized")
}
newUsername := c.FormValue("username")
if newUsername == "" {
return model.NewRequestError("Username is required")
}
user, err := service.ChangeUsername(uid, newUsername)
if err != nil {
return err
}
return c.Status(fiber.StatusOK).JSON(model.Response[model.UserView]{
Success: true,
Data: user,
Message: "Username changed successfully",
})
}
func AddUserRoutes(r fiber.Router) {
u := r.Group("user")
u.Post("/register", handleUserRegister)
@@ -290,4 +310,5 @@ func AddUserRoutes(r fiber.Router) {
u.Get("/search", handleSearchUsers)
u.Post("/delete", handleDeleteUser)
u.Get("/info", handleGetUserInfo)
u.Post("/username", handleChangeUsername)
}

View File

@@ -264,3 +264,18 @@ func GetUserByUsername(username string) (model.UserView, error) {
}
return user.ToView(), nil
}
func ChangeUsername(uid uint, newUsername string) (model.UserView, error) {
if len(newUsername) < 3 || len(newUsername) > 20 {
return model.UserView{}, model.NewRequestError("Username must be between 3 and 20 characters")
}
user, err := dao.GetUserByID(uid)
if err != nil {
return model.UserView{}, err
}
user.Username = newUsername
if err := dao.UpdateUser(user); err != nil {
return model.UserView{}, err
}
return user.ToView(), nil
}