mirror of
https://github.com/fosrl/pangolin.git
synced 2025-08-18 16:28:26 +02:00
removed admin password reset and user name field
This commit is contained in:
parent
97b267e7ae
commit
eb4da25d4e
23 changed files with 15 additions and 554 deletions
|
@ -975,7 +975,6 @@
|
|||
"actionUpdateOrg": "Update Organization",
|
||||
"actionUpdateUser": "Update User",
|
||||
"actionGetUser": "Get User",
|
||||
"actionResetUserPassword": "Reset User Password",
|
||||
"actionGetOrgUser": "Get Organization User",
|
||||
"actionListOrgDomains": "List Organization Domains",
|
||||
"actionCreateSite": "Create Site",
|
||||
|
@ -1155,25 +1154,9 @@
|
|||
"initialSetupDescription": "Create the intial server admin account. Only one server admin can exist. You can always change these credentials later.",
|
||||
"createAdminAccount": "Create Admin Account",
|
||||
"setupErrorCreateAdmin": "An error occurred while creating the server admin account.",
|
||||
"passwordReset": "Password Reset",
|
||||
"passwordResetAdminInstructions": "Clicking the button below will send a password reset email to the user. They will be able to set a new password using the link provided.",
|
||||
"passwordResetSent": "Password Reset Sent",
|
||||
"passwordResetSentDescription": "A password reset email has been sent to {email}.",
|
||||
"passwordResetError": "Failed to Send Reset",
|
||||
"passwordResetErrorDescription": "Unable to send password reset email. Please try again.",
|
||||
"passwordResetSending": "Sending...",
|
||||
"passwordResetSendEmail": "Send Reset Email",
|
||||
"passwordResetUnavailable": "Password Reset Unavailable",
|
||||
"passwordResetExternalUserDescription": "Password reset is only available for internal users. External users authenticate through their identity provider.",
|
||||
|
||||
"adminSettings": "Admin Settings",
|
||||
"adminSettingsDescription": "Configure server-wide administration settings",
|
||||
"security": "Security",
|
||||
"tokenExpiration": "Token Expiration",
|
||||
"tokenExpirationDescription": "Configure how long password reset tokens remain valid before expiring",
|
||||
"passwordResetExpireLimit": "Password Reset Token Expiry",
|
||||
"passwordResetExpireLimitDescription": "Set how many hours password reset tokens remain valid. Default is 1 hour.",
|
||||
"hours": "hours",
|
||||
"securitySettingsSaved": "Security Settings Saved",
|
||||
"securitySettingsSavedDescription": "Your security settings have been updated successfully",
|
||||
"securitySettingsUpdated": "Security Settings Updated",
|
||||
"securitySettingsUpdatedDescription": "Your security settings have been updated successfully",
|
||||
|
|
|
@ -93,7 +93,6 @@ export enum ActionsEnum {
|
|||
listApiKeyActions = "listApiKeyActions",
|
||||
listApiKeys = "listApiKeys",
|
||||
getApiKey = "getApiKey",
|
||||
resetUserPassword = "resetUserPassword",
|
||||
createOrgDomain = "createOrgDomain",
|
||||
deleteOrgDomain = "deleteOrgDomain",
|
||||
restartOrgDomain = "restartOrgDomain"
|
||||
|
|
|
@ -23,7 +23,6 @@ import { passwordSchema } from "@server/auth/passwordSchema";
|
|||
import { UserType } from "@server/types/UserTypes";
|
||||
|
||||
export const signupBodySchema = z.object({
|
||||
name: z.string().optional(),
|
||||
email: z
|
||||
.string()
|
||||
.toLowerCase()
|
||||
|
@ -55,7 +54,7 @@ export async function signup(
|
|||
);
|
||||
}
|
||||
|
||||
const { name, email, password, inviteToken, inviteId } = parsedBody.data;
|
||||
const { email, password, inviteToken, inviteId } = parsedBody.data;
|
||||
const passwordHash = await hashPassword(password);
|
||||
const userId = generateId(15);
|
||||
|
||||
|
@ -165,7 +164,6 @@ export async function signup(
|
|||
userId: userId,
|
||||
type: UserType.Internal,
|
||||
username: email,
|
||||
name: name,
|
||||
email: email,
|
||||
passwordHash,
|
||||
dateCreated: moment().toISOString()
|
||||
|
|
|
@ -552,11 +552,6 @@ authenticated.delete(
|
|||
verifyUserIsServerAdmin,
|
||||
user.adminRemoveUser
|
||||
);
|
||||
authenticated.post(
|
||||
"/admin/user/:userId/password",
|
||||
verifyUserIsServerAdmin,
|
||||
user.adminResetUserPassword
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/admin/user/:userId",
|
||||
|
|
|
@ -388,13 +388,6 @@ authenticated.post(
|
|||
user.updateUser2FA
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/user/:userId/password",
|
||||
verifyApiKeyIsRoot,
|
||||
verifyApiKeyHasAction(ActionsEnum.resetUserPassword),
|
||||
user.adminResetUserPassword
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/user/:userId",
|
||||
verifyApiKeyIsRoot,
|
||||
|
|
|
@ -32,7 +32,6 @@ async function queryUser(userId: string) {
|
|||
userId: users.userId,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
name: users.name,
|
||||
type: users.type,
|
||||
twoFactorEnabled: users.twoFactorEnabled,
|
||||
twoFactorSetupRequested: users.twoFactorSetupRequested,
|
||||
|
|
|
@ -32,7 +32,6 @@ async function queryUsers(limit: number, offset: number) {
|
|||
id: users.userId,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
name: users.name,
|
||||
dateCreated: users.dateCreated,
|
||||
serverAdmin: users.serverAdmin,
|
||||
type: users.type,
|
||||
|
|
|
@ -1,212 +0,0 @@
|
|||
import { NextFunction, Request, Response } from "express";
|
||||
import { z } from "zod";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import createHttpError from "http-errors";
|
||||
import { db } from "@server/db";
|
||||
import { passwordResetTokens, users } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { alphabet, generateRandomString } from "oslo/crypto";
|
||||
import { createDate, TimeSpan } from "oslo";
|
||||
import { hashPassword } from "@server/auth/password";
|
||||
import { sendEmail } from "@server/emails";
|
||||
import ResetPasswordCode from "@server/emails/templates/ResetPasswordCode";
|
||||
import config from "@server/lib/config";
|
||||
import logger from "@server/logger";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { UserType } from "@server/types/UserTypes";
|
||||
|
||||
const adminResetUserPasswordParamsSchema = z
|
||||
.object({
|
||||
userId: z.string()
|
||||
})
|
||||
.strict();
|
||||
|
||||
const adminResetUserPasswordBodySchema = z
|
||||
.object({
|
||||
sendEmail: z.boolean().optional().default(true),
|
||||
expirationHours: z.number().int().positive().optional().default(24)
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type AdminResetUserPasswordBody = z.infer<typeof adminResetUserPasswordBodySchema>;
|
||||
export type AdminResetUserPasswordResponse = {
|
||||
resetLink?: string;
|
||||
emailSent: boolean;
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/admin/user/{userId}/password",
|
||||
description: "Generate a password reset link for a user (server admin only).",
|
||||
tags: [OpenAPITags.User],
|
||||
request: {
|
||||
params: adminResetUserPasswordParamsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: adminResetUserPasswordBodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function adminResetUserPassword(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
const parsedParams = adminResetUserPasswordParamsSchema.safeParse(req.params);
|
||||
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedBody = adminResetUserPasswordBodySchema.safeParse(req.body);
|
||||
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { userId } = parsedParams.data;
|
||||
const { sendEmail: shouldSendEmail, expirationHours } = parsedBody.data;
|
||||
|
||||
try {
|
||||
// Get the target user
|
||||
const targetUser = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.userId, userId));
|
||||
|
||||
if (!targetUser || !targetUser.length) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"User not found"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const user = targetUser[0];
|
||||
|
||||
// Only allow resetting passwords for internal users
|
||||
if (user.type !== UserType.Internal) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Password reset is only available for internal users"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!user.email) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"User does not have an email address"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Generate reset token
|
||||
const token = generateRandomString(16, alphabet("0-9", "A-Z", "a-z"));
|
||||
const tokenHash = await hashPassword(token);
|
||||
|
||||
// Store reset token in database
|
||||
await db.transaction(async (trx) => {
|
||||
// Delete any existing reset tokens for this user
|
||||
await trx
|
||||
.delete(passwordResetTokens)
|
||||
.where(eq(passwordResetTokens.userId, userId));
|
||||
|
||||
// Insert new reset token
|
||||
await trx.insert(passwordResetTokens).values({
|
||||
userId: userId,
|
||||
email: user.email!,
|
||||
tokenHash,
|
||||
expiresAt: createDate(new TimeSpan(expirationHours, "h")).getTime()
|
||||
});
|
||||
});
|
||||
|
||||
const resetUrl = `${config.getRawConfig().app.dashboard_url}/auth/reset-password?email=${encodeURIComponent(user.email!)}&token=${token}`;
|
||||
|
||||
let emailSent = false;
|
||||
|
||||
// Get the admin identifier (either user ID or API key ID)
|
||||
const adminId = req.user?.userId || req.apiKey?.apiKeyId || 'unknown';
|
||||
|
||||
// Send email if requested
|
||||
if (shouldSendEmail) {
|
||||
// Check if email is configured
|
||||
if (!config.getRawConfig().email) {
|
||||
logger.info(
|
||||
`Server admin ${adminId} generated password reset link for user ${userId}. Email not configured, no email sent. Token expires in ${expirationHours} hours.`
|
||||
);
|
||||
emailSent = false;
|
||||
} else {
|
||||
try {
|
||||
await sendEmail(
|
||||
ResetPasswordCode({
|
||||
email: user.email!,
|
||||
code: token,
|
||||
link: resetUrl
|
||||
}),
|
||||
{
|
||||
from: config.getNoReplyEmail(),
|
||||
to: user.email!,
|
||||
subject: "Password Reset - Initiated by Server Administrator"
|
||||
}
|
||||
);
|
||||
emailSent = true;
|
||||
|
||||
logger.info(
|
||||
`Server admin ${adminId} initiated password reset for user ${userId}. Email sent to ${user.email}. Token expires in ${expirationHours} hours.`
|
||||
);
|
||||
} catch (e) {
|
||||
logger.error("Failed to send server admin-initiated password reset email", e);
|
||||
// Don't fail the request if email fails, just log it
|
||||
emailSent = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.info(
|
||||
`Server admin ${adminId} generated password reset link for user ${userId}. No email sent. Token expires in ${expirationHours} hours.`
|
||||
);
|
||||
}
|
||||
|
||||
return response<AdminResetUserPasswordResponse>(res, {
|
||||
data: {
|
||||
resetLink: resetUrl,
|
||||
emailSent
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: emailSent
|
||||
? `Password reset email sent to ${user.email}`
|
||||
: "Password reset link generated successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
logger.error("Failed to generate server admin password reset", e);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate password reset"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -18,7 +18,6 @@ async function queryUser(orgId: string, userId: string) {
|
|||
userId: users.userId,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
name: users.name,
|
||||
type: users.type,
|
||||
roleId: userOrgs.roleId,
|
||||
roleName: roles.name,
|
||||
|
|
|
@ -14,7 +14,6 @@ async function queryUser(userId: string) {
|
|||
userId: users.userId,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
name: users.name,
|
||||
type: users.type,
|
||||
twoFactorEnabled: users.twoFactorEnabled,
|
||||
emailVerified: users.emailVerified,
|
||||
|
|
|
@ -13,6 +13,4 @@ export * from "./removeInvitation";
|
|||
export * from "./createOrgUser";
|
||||
export { updateUser } from "./updateUser";
|
||||
export { adminUpdateUser } from "./adminUpdateUser";
|
||||
export { adminResetUserPassword } from "./adminResetUserPassword";
|
||||
export type { AdminResetUserPasswordBody, AdminResetUserPasswordResponse } from "./adminResetUserPassword";
|
||||
export * from "./adminUpdateUser2FA";
|
|
@ -43,7 +43,6 @@ async function queryUsers(orgId: string, limit: number, offset: number) {
|
|||
dateCreated: users.dateCreated,
|
||||
orgId: userOrgs.orgId,
|
||||
username: users.username,
|
||||
name: users.name,
|
||||
type: users.type,
|
||||
roleId: userOrgs.roleId,
|
||||
roleName: roles.name,
|
||||
|
|
|
@ -20,7 +20,6 @@ const updateUserParamsSchema = z
|
|||
|
||||
const updateUserBodySchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(255).optional(),
|
||||
email: z.string().email().optional()
|
||||
})
|
||||
.strict()
|
||||
|
@ -30,7 +29,6 @@ const updateUserBodySchema = z
|
|||
|
||||
export type UpdateUserResponse = {
|
||||
userId: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
username: string;
|
||||
};
|
||||
|
@ -129,7 +127,6 @@ export async function updateUser(
|
|||
.where(eq(users.userId, userId))
|
||||
.returning({
|
||||
userId: users.userId,
|
||||
name: users.name,
|
||||
email: users.email,
|
||||
username: users.username
|
||||
});
|
||||
|
|
|
@ -27,7 +27,6 @@ export type UserRow = {
|
|||
email: string | null;
|
||||
displayUsername: string | null;
|
||||
username: string;
|
||||
name: string | null;
|
||||
idpId: number | null;
|
||||
idpName: string;
|
||||
type: string;
|
||||
|
@ -248,7 +247,6 @@ export default function UsersTable({ users: u }: UsersTableProps) {
|
|||
{t("userQuestionOrgRemove", {
|
||||
email:
|
||||
selectedUser?.email ||
|
||||
selectedUser?.name ||
|
||||
selectedUser?.username ||
|
||||
""
|
||||
})}
|
||||
|
@ -263,7 +261,6 @@ export default function UsersTable({ users: u }: UsersTableProps) {
|
|||
onConfirm={removeUser}
|
||||
string={
|
||||
selectedUser?.email ||
|
||||
selectedUser?.name ||
|
||||
selectedUser?.username ||
|
||||
""
|
||||
}
|
||||
|
|
|
@ -74,7 +74,6 @@ export default async function UsersPage(props: UsersPageProps) {
|
|||
id: user.id,
|
||||
username: user.username,
|
||||
displayUsername: user.email || user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
type: user.type,
|
||||
idpId: user.idpId,
|
||||
|
|
|
@ -60,13 +60,13 @@ export default function AdminUserManagement({
|
|||
|
||||
// Form schema for user details
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(1, { message: t('nameRequired') }).max(255)
|
||||
// Name field removed - no longer needed
|
||||
});
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
name: userName || ""
|
||||
// No default values needed
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -74,16 +74,11 @@ export default function AdminUserManagement({
|
|||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await api.post(`/admin/user/${userId}`, {
|
||||
name: values.name
|
||||
});
|
||||
|
||||
if (res.status === 200) {
|
||||
// No update needed since name field is removed
|
||||
toast({
|
||||
title: t('userUpdated'),
|
||||
description: t('userUpdatedDescription'),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
|
@ -124,24 +119,8 @@ export default function AdminUserManagement({
|
|||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleUpdateUser)} className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Update user information. Email addresses cannot be changed via the UI.
|
||||
User information display. Email addresses cannot be changed via the UI.
|
||||
</p>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('name')}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder={t('namePlaceholder')}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p><strong>Email:</strong> {userEmail}</p>
|
||||
</div>
|
||||
|
|
|
@ -22,7 +22,6 @@ import {
|
|||
|
||||
export type GlobalUserRow = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
username: string;
|
||||
email: string | null;
|
||||
type: string;
|
||||
|
@ -242,7 +241,6 @@ export default function UsersTable({ users }: Props) {
|
|||
{t("userQuestionRemove", {
|
||||
selectedUser:
|
||||
selected?.email ||
|
||||
selected?.name ||
|
||||
selected?.username
|
||||
})}
|
||||
</p>
|
||||
|
@ -257,7 +255,7 @@ export default function UsersTable({ users }: Props) {
|
|||
buttonText={t("userDeleteConfirm")}
|
||||
onConfirm={async () => deleteUser(selected!.id)}
|
||||
string={
|
||||
selected.email || selected.name || selected.username
|
||||
selected.email || selected.username
|
||||
}
|
||||
title={t("userDeleteServer")}
|
||||
/>
|
||||
|
|
|
@ -19,7 +19,7 @@ import {
|
|||
SettingsSectionForm
|
||||
} from "@app/components/Settings";
|
||||
import { UserType } from "@server/types/UserTypes";
|
||||
import AdminPasswordReset from "@app/components/AdminPasswordReset";
|
||||
|
||||
|
||||
export default function GeneralPage() {
|
||||
const { userId } = useParams();
|
||||
|
@ -31,7 +31,6 @@ export default function GeneralPage() {
|
|||
const [twoFactorEnabled, setTwoFactorEnabled] = useState(false);
|
||||
const [userType, setUserType] = useState<UserType | null>(null);
|
||||
const [userEmail, setUserEmail] = useState<string>("");
|
||||
const [userName, setUserName] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
// Fetch current user 2FA status
|
||||
|
@ -47,7 +46,6 @@ export default function GeneralPage() {
|
|||
);
|
||||
setUserType(userData.type);
|
||||
setUserEmail(userData.email || "");
|
||||
setUserName(userData.name || userData.username || "");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user data:", error);
|
||||
|
@ -123,29 +121,7 @@ export default function GeneralPage() {
|
|||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>
|
||||
{t("passwordReset")}
|
||||
</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
{t("passwordResetAdminInstructions")}
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
|
||||
<SettingsSectionBody>
|
||||
<SettingsSectionForm>
|
||||
<div className="space-y-6">
|
||||
<AdminPasswordReset
|
||||
userId={userId as string}
|
||||
userEmail={userEmail}
|
||||
userName={userName}
|
||||
userType={userType || ""}
|
||||
/>
|
||||
</div>
|
||||
</SettingsSectionForm>
|
||||
</SettingsSectionBody>
|
||||
</SettingsSection>
|
||||
</SettingsContainer>
|
||||
|
||||
<div className="flex justify-end mt-6">
|
||||
|
|
|
@ -44,7 +44,7 @@ export default async function UserLayoutProps(props: UserLayoutProps) {
|
|||
return (
|
||||
<>
|
||||
<SettingsSectionTitle
|
||||
title={`${user?.email || user?.name || user?.username}`}
|
||||
title={`${user?.email || user?.username}`}
|
||||
description={t('userDescription2')}
|
||||
/>
|
||||
<HorizontalTabs items={navItems}>
|
||||
|
|
|
@ -32,7 +32,6 @@ export default async function UsersPage(props: PageProps) {
|
|||
return {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
name: row.name,
|
||||
username: row.username,
|
||||
type: row.type,
|
||||
idpId: row.idpId,
|
||||
|
|
|
@ -1,232 +0,0 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@app/components/ui/dialog";
|
||||
import { Input } from "@app/components/ui/input";
|
||||
import { Checkbox } from "@app/components/ui/checkbox";
|
||||
import { Label } from "@app/components/ui/label";
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { formatAxiosError } from "@app/lib/api";
|
||||
import { createApiClient } from "@app/lib/api";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Key, Mail, Copy, Link } from "lucide-react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@app/components/ui/alert";
|
||||
|
||||
type AdminPasswordResetProps = {
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
userName: string;
|
||||
userType: string;
|
||||
};
|
||||
|
||||
export default function AdminPasswordReset({
|
||||
userId,
|
||||
userEmail,
|
||||
userName,
|
||||
userType,
|
||||
}: AdminPasswordResetProps) {
|
||||
const api = createApiClient(useEnvContext());
|
||||
const { env } = useEnvContext();
|
||||
const t = useTranslations();
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [passwordLoading, setPasswordLoading] = useState(false);
|
||||
const [sendEmail, setSendEmail] = useState(env.email.emailEnabled);
|
||||
const [resetLink, setResetLink] = useState<string | undefined>();
|
||||
|
||||
const isExternalUser = userType !== "internal";
|
||||
|
||||
// Don't render the button for external users
|
||||
if (isExternalUser) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
setPasswordLoading(true);
|
||||
|
||||
try {
|
||||
const response = await api.post(`/admin/user/${userId}/password`, {
|
||||
sendEmail,
|
||||
expirationHours: 24
|
||||
});
|
||||
|
||||
const data = response.data.data;
|
||||
|
||||
if (data.resetLink) {
|
||||
setResetLink(data.resetLink);
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('passwordResetSuccess'),
|
||||
description: data.emailSent
|
||||
? `Password reset email sent to ${userEmail}`
|
||||
: data.message,
|
||||
});
|
||||
|
||||
if (env.email.emailEnabled && sendEmail && data.emailSent) {
|
||||
setOpen(false);
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t('passwordResetError'),
|
||||
description: formatAxiosError(error, t('passwordResetErrorDescription')),
|
||||
});
|
||||
} finally {
|
||||
setPasswordLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copyToClipboard = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast({
|
||||
title: t('linkCopied'),
|
||||
description: t('linkCopiedDescription'),
|
||||
});
|
||||
} catch (e) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Copy failed",
|
||||
description: "Failed to copy to clipboard. Please copy manually.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
setResetLink(undefined);
|
||||
setSendEmail(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
{t('passwordReset')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4" />
|
||||
{t('passwordReset')}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Reset password for <strong>{userName || userEmail}</strong>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 mt-4">
|
||||
{!env.email.emailEnabled && (
|
||||
<Alert variant="neutral">
|
||||
<AlertTitle className="font-semibold">
|
||||
{t('otpEmailSmtpRequired')}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
Email is not configured. A reset link will be generated for you to share manually.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{env.email.emailEnabled && (
|
||||
<div className="space-y-3 p-4 bg-blue-50 border border-blue-200 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-blue-600" />
|
||||
<h4 className="font-medium text-blue-900">Email Notification</h4>
|
||||
</div>
|
||||
<p className="text-sm text-blue-700">
|
||||
Send a password reset email to the user with a secure reset link.
|
||||
</p>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="sendEmail"
|
||||
checked={sendEmail}
|
||||
onCheckedChange={(checked) => setSendEmail(checked as boolean)}
|
||||
/>
|
||||
<Label htmlFor="sendEmail" className="text-sm font-medium text-blue-900">
|
||||
{t('sendEmailNotification')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{resetLink && (!sendEmail || !env.email.emailEnabled) && (
|
||||
<Alert className="border-green-200 bg-green-50">
|
||||
<Link className="h-4 w-4 text-green-600" />
|
||||
<AlertTitle className="text-green-800">Reset Link Generated</AlertTitle>
|
||||
<AlertDescription className="text-green-700">
|
||||
<div className="mt-2 space-y-2">
|
||||
<p className="text-sm">Share this link with the user:</p>
|
||||
<div className="flex items-center gap-2 p-2 bg-white border rounded border-green-200">
|
||||
<Input
|
||||
value={resetLink}
|
||||
readOnly
|
||||
className="text-xs"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => copyToClipboard(resetLink)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-green-600">
|
||||
This link expires in 24 hours.
|
||||
</p>
|
||||
</div>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
{resetLink ? 'Close' : t('cancel')}
|
||||
</Button>
|
||||
{!resetLink && (
|
||||
<Button
|
||||
onClick={handleResetPassword}
|
||||
disabled={passwordLoading}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{passwordLoading ? (
|
||||
<>
|
||||
<Key className="h-4 w-4 animate-spin" />
|
||||
{t('passwordResetSending')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{env.email.emailEnabled && sendEmail ? (
|
||||
<Mail className="h-4 w-4" />
|
||||
) : (
|
||||
<Link className="h-4 w-4" />
|
||||
)}
|
||||
{env.email.emailEnabled && sendEmail
|
||||
? t('passwordResetSendEmail')
|
||||
: "Generate Reset Link"
|
||||
}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
|
@ -113,8 +113,7 @@ function getActionsCategories(root: boolean) {
|
|||
|
||||
actionsByCategory["User"] = {
|
||||
[t('actionUpdateUser')]: "updateUser",
|
||||
[t('actionGetUser')]: "getUser",
|
||||
[t('actionResetUserPassword')]: "resetUserPassword"
|
||||
[t('actionGetUser')]: "getUser"
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ export default function ProfileIcon() {
|
|||
const t = useTranslations();
|
||||
|
||||
function getInitials() {
|
||||
return (user.name || user.email || user.username)
|
||||
return (user.email || user.username)
|
||||
.substring(0, 1)
|
||||
.toUpperCase();
|
||||
}
|
||||
|
@ -96,7 +96,7 @@ export default function ProfileIcon() {
|
|||
{t("signingAs")}
|
||||
</p>
|
||||
<p className="text-xs leading-none text-muted-foreground">
|
||||
{user.email || user.name || user.username}
|
||||
{user.email || user.username}
|
||||
</p>
|
||||
</div>
|
||||
{user.serverAdmin ? (
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue