Feat: Random password generator (V2) (#7272)

Added a secure password generator to admin customer user manager and
user account manager as shown below:

## Extra Details:
- Added a reusable password field component with:
  - 17-character random password generation
  - Uppercase and lowercase letters
  - Numbers
  - Symbols
  - Password visibility toggle button
  - Clipboard copy button after the new password is generated
- Integrated the feature into:
  - Admin customer user creation area
  - Admin customer user editing area
  - Customer User account settings

<img width="430" height="466"
alt="{2DD29137-22E3-4446-8DB5-4F37AD322DF2}"
src="https://github.com/user-attachments/assets/03ef614a-3f4e-4ba6-bdbc-1a99e07959c6"
/>

<img width="427" height="120"
alt="{A3073146-78CD-459C-A837-EBAB72E8ABA4}"
src="https://github.com/user-attachments/assets/5c9cf583-4941-4c0d-893a-fe85c4e46f3c"
/>

<img width="413" height="142"
alt="{2DB05B11-7781-403D-ABC1-CEF11D31E1E8}"
src="https://github.com/user-attachments/assets/0131b770-9120-4f14-8bbd-8dfc374e6263"
/>

<img width="457" height="249"
alt="{8AA4DACE-CBA4-41F1-A5FA-F1EEB3B72632}"
src="https://github.com/user-attachments/assets/2f3004fe-74b2-4060-82eb-ac3f12d5f00f"
/>
This commit is contained in:
ItzLinaton
2026-11-01 19:50:22 -05:00
committed by GitHub
parent 4257022c66
commit c900fc0ccc
7 changed files with 257 additions and 9 deletions
@@ -140,8 +140,7 @@ const PasswordCard = ({ form }: { form: UserForm }) => (
<TitledGreyBox title='Password'>
<form.AppField name='password' validators={{ onChange: validateUserPassword }}>
{(field) => (
<field.TextField
type='password'
<field.PasswordField
id='password'
label='Password'
description={
@@ -53,8 +53,7 @@ const AuthenticationFields = ({ form, languageOptions, languagesLoading }: Props
<div className='space-y-6'>
<form.AppField name='password' validators={{ onChange: validateUserPassword }}>
{(field) => (
<field.TextField
type='password'
<field.PasswordField
id='password'
label='Password'
description='Leave blank to email this user a setup link to choose their own.'
+111 -1
View File
@@ -1,4 +1,5 @@
import React, { useId } from 'react';
import React, { useId, useState } from 'react';
import { Clipboard, Eye, EyeOff, RotateCcwKey } from 'lucide-react';
import { useFieldContext } from './context';
import Label from '@/components/elements/Label';
import { TextInput, TextArea, NumberInput } from './controls';
@@ -7,6 +8,12 @@ import { capitalize } from '@/lib/strings';
import Select, { type SelectOption } from '@/components/ui/Select';
import Switch, { type SwitchProps } from '@/components/ui/Switch';
import Checkbox from '@/components/ui/Checkbox';
import Button from '@/components/elements/Button';
import CopyOnClick from '@/components/elements/CopyOnClick';
import Icon from '@/components/elements/Icon';
import Tooltip from '@/components/elements/tooltip/Tooltip';
import { cn } from '@/lib/cn';
import { generateSecurePassword } from '@/lib/passwords';
type BaseProps = {
label?: string;
@@ -93,6 +100,109 @@ export function TextField({
);
}
export type PasswordFieldProps = BaseProps &
Omit<React.InputHTMLAttributes<HTMLInputElement>, 'name' | 'value' | 'onChange' | 'defaultValue' | 'type'>;
export function PasswordField({
id,
label,
description,
light,
onBlur,
className,
'aria-describedby': ariaDescribedBy,
'aria-invalid': ariaInvalid,
...props
}: PasswordFieldProps) {
const { field, error, fieldId, helpId, describedById } = useFieldState<string>(id, description);
const [visible, setVisible] = useState(false);
const [generated, setGenerated] = useState(false);
const toggleLabel = `${visible ? 'Hide' : 'Show'} ${label?.toLowerCase() ?? 'password'}`;
const generate = () => {
field.handleChange(generateSecurePassword());
setGenerated(true);
};
return (
<div>
{label && (
<Label htmlFor={fieldId} isLight={light}>
{label}
</Label>
)}
<div className='relative'>
<TextInput
{...props}
id={fieldId}
type={visible ? 'text' : 'password'}
value={field.state.value ?? ''}
onValueChange={(value: string) => {
field.handleChange(value);
setGenerated(false);
}}
onBlur={(event) => {
field.handleBlur();
onBlur?.(event);
}}
aria-invalid={error ? true : ariaInvalid}
aria-describedby={describedBy(ariaDescribedBy, describedById)}
$hasError={!!error}
$isLight={light}
className={cn('pr-24', className)}
/>
<div className='absolute inset-y-0 right-2 flex items-center gap-1'>
<Tooltip content='Generate secure password'>
<span className='inline-flex'>
<Button.Text
type='button'
size='xsmall'
isSecondary
aria-label='Generate secure password'
onClick={generate}
>
<Icon icon={RotateCcwKey} className='h-3.5 w-3.5' />
</Button.Text>
</span>
</Tooltip>
<Tooltip content={toggleLabel}>
<span className='inline-flex'>
<Button.Text
type='button'
size='xsmall'
isSecondary
aria-label={toggleLabel}
aria-pressed={visible}
disabled={!field.state.value}
onClick={() => setVisible((current) => !current)}
>
<Icon icon={visible ? EyeOff : Eye} className='h-3.5 w-3.5' />
</Button.Text>
</span>
</Tooltip>
{generated && (
<Tooltip content='Copy password'>
<span className='inline-flex'>
<CopyOnClick text={field.state.value} showInNotification={false}>
<Button.Text
type='button'
size='xsmall'
isSecondary
aria-label='Copy password'
>
<Icon icon={Clipboard} className='h-3.5 w-3.5' />
</Button.Text>
</CopyOnClick>
</span>
</Tooltip>
)}
</div>
</div>
<HelpText id={helpId} error={error} description={description} />
</div>
);
}
export type TextAreaFieldProps = BaseProps &
Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'name' | 'value' | 'onChange' | 'defaultValue'>;
@@ -3,6 +3,7 @@ import type { FormAsyncValidateOrFn, FormValidateOrFn } from '@tanstack/form-cor
import { fieldContext, formContext } from './context';
import {
TextField,
PasswordField,
TextAreaField,
NumberField,
SelectField,
@@ -14,6 +15,7 @@ import { SubmitButton } from './SubmitButton';
const fieldComponents = {
TextField,
PasswordField,
TextAreaField,
NumberField,
SelectField,
+47
View File
@@ -0,0 +1,47 @@
const passwordCharacterSets = {
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
lowercase: 'abcdefghijklmnopqrstuvwxyz',
numbers: '0123456789',
symbols: '!@#$%^&*()_+=-[]{}',
} as const;
const secureRandomIndex = (length: number): number => {
if (length < 1) {
return 0;
}
const limit = 0x100000000 - (0x100000000 % length);
const values = new Uint32Array(1);
let value: number;
do {
crypto.getRandomValues(values);
value = values[0];
} while (value >= limit);
return value % length;
};
const randomCharacter = (characters: string): string => characters[secureRandomIndex(characters.length)];
/**
* Generates a secure password using the defined random character sets.
*
* @param length The requested password length.
*/
export const generateSecurePassword = (length = 17): string => {
const characterSets = Object.values(passwordCharacterSets);
const allCharacters = characterSets.join('');
const password = characterSets.map(randomCharacter);
while (password.length < length) {
password.push(randomCharacter(allCharacters));
}
for (let index = password.length - 1; index > 0; index--) {
const swapIndex = secureRandomIndex(index + 1);
[password[index], password[swapIndex]] = [password[swapIndex], password[index]];
}
return password.join('');
};
@@ -1,6 +1,6 @@
import { Button, ContentBox, Form, SpinnerOverlay } from '@/sdk';
import type { ViewProps } from '@/sdk/theme';
import { TextField } from '../shared/fields';
import { PasswordField, TextField } from '../shared/fields';
export default function PasswordCard({ model, className }: ViewProps<'account.password'>) {
const { fields } = model;
@@ -11,7 +11,7 @@ export default function PasswordCard({ model, className }: ViewProps<'account.pa
<Form form={{ handleSubmit: model.submit }} className='m-0'>
<TextField field={fields.current} id='current_password' label='Current Password' />
<div className='mt-6'>
<TextField
<PasswordField
field={fields.password}
id='new_password'
label='New Password'
@@ -1,5 +1,7 @@
import { useId } from 'react';
import { Input, Label, TextArea, type FieldModel } from '@/sdk';
import { useId, useState, type ChangeEvent } from 'react';
import { Clipboard, Eye, EyeOff, RotateCcwKey } from 'lucide-react';
import { Button, CopyOnClick, Icon, Input, Label, TextArea, Tooltip, type FieldModel } from '@/sdk';
import { generateSecurePassword } from '@/lib/passwords';
interface FieldProps {
field: FieldModel;
@@ -69,6 +71,95 @@ export function TextField({
);
}
export function PasswordField({ field, label, description, light, id, className }: FieldProps) {
const { fieldId, helpId, describedBy } = useFieldIds(field, id, description);
const [visible, setVisible] = useState(false);
const [generated, setGenerated] = useState(false);
const toggleLabel = (visible ? 'Hide' : 'Show') + ' ' + (label?.toLowerCase() ?? 'password');
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
field.fieldProps.onChange(event);
setGenerated(false);
};
const generate = () => {
const value = generateSecurePassword();
field.fieldProps.onChange({ currentTarget: { value } } as ChangeEvent<HTMLInputElement>);
setGenerated(true);
};
return (
<div>
{label && (
<Label htmlFor={fieldId} isLight={light}>
{label}
</Label>
)}
<div className='relative'>
<Input
{...field.fieldProps}
id={fieldId}
type={visible ? 'text' : 'password'}
onChange={handleChange}
className={['pr-24', className].filter(Boolean).join(' ')}
aria-invalid={field.error ? true : undefined}
aria-describedby={describedBy}
$hasError={!!field.error}
$isLight={light}
/>
<div className='absolute inset-y-0 right-2 flex items-center gap-1'>
<Tooltip content='Generate secure password'>
<span className='inline-flex'>
<Button.Text
type='button'
size='xsmall'
isSecondary
aria-label='Generate secure password'
onClick={generate}
>
<Icon icon={RotateCcwKey} className='h-3.5 w-3.5' />
</Button.Text>
</span>
</Tooltip>
<Tooltip content={toggleLabel}>
<span className='inline-flex'>
<Button.Text
type='button'
size='xsmall'
isSecondary
aria-label={toggleLabel}
aria-pressed={visible}
disabled={!field.fieldProps.value}
onClick={() => setVisible((current) => !current)}
>
<Icon icon={visible ? EyeOff : Eye} className='h-3.5 w-3.5' />
</Button.Text>
</span>
</Tooltip>
{generated && (
<Tooltip content='Copy password'>
<span className='inline-flex'>
<CopyOnClick text={field.fieldProps.value} showInNotification={false}>
<Button.Text
type='button'
size='xsmall'
isSecondary
aria-label='Copy password'
>
<Icon icon={Clipboard} className='h-3.5 w-3.5' />
</Button.Text>
</CopyOnClick>
</span>
</Tooltip>
)}
</div>
</div>
<HelpText id={helpId} error={field.error} description={description} />
</div>
);
}
export function TextAreaField({
field,
label,