Skip to content

Commit 45a8fcb

Browse files
Allow memorable, custom Quick-Upload codes (admin-chosen, case-insensitive)
Admins can now set a memorable Quick-Upload code (letters, digits and dashes) instead of relying on the random one, so it can be typed from any device. The code is normalised to uppercase and matched case-insensitively at redeem time. - shared: optional, validated `code` field on createQuickCodeSchema - api/admin: use the chosen code with a 409 uniqueness check, else random - api/quick: uppercase the incoming code in the guest probe and upload paths - web/admin: inline form to enter a custom code and usage limit - test: custom code normalisation, case-insensitive probe, duplicate, bad shape
1 parent 7c866ec commit 45a8fcb

5 files changed

Lines changed: 96 additions & 15 deletions

File tree

‎apps/api/src/routes/admin.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,9 +183,17 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
183183
}
184184
}
185185

186+
// Use the admin's chosen memorable code (already uppercased by the schema), or a
187+
// random one. Reject a custom code that's already taken.
188+
const codeValue = body.code ?? randomCode();
189+
if (body.code) {
190+
const clash = await prisma.quickUploadCode.findUnique({ where: { code: codeValue } });
191+
if (clash) return reply.code(409).send({ error: 'This code is already in use' });
192+
}
193+
186194
const code = await prisma.quickUploadCode.create({
187195
data: {
188-
code: randomCode(),
196+
code: codeValue,
189197
createdById: req.user!.id,
190198
targetFolderId: body.targetFolderId ?? null,
191199
maxBytes: body.maxBytes == null ? null : BigInt(body.maxBytes),

‎apps/api/src/routes/quick.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ function isUsedUp(usageLimit: number | null, usageCount: number): boolean {
3333
export const quickRoutes: FastifyPluginAsync = async (app) => {
3434
// GET /quick/:code — lightweight validity probe for the guest UI.
3535
app.get('/:code', async (req, reply) => {
36-
const { code } = req.params as { code: string };
36+
const code = String((req.params as { code: string }).code).toUpperCase();
3737
const entry = await prisma.quickUploadCode.findUnique({ where: { code } });
3838
if (!entry || isExpired(entry.expiresAt) || isUsedUp(entry.usageLimit, entry.usageCount)) {
3939
return reply.code(404).send({ error: 'Code not found or no longer active' });
@@ -47,7 +47,7 @@ export const quickRoutes: FastifyPluginAsync = async (app) => {
4747
? { config: { rateLimit: { max: 60, timeWindow: '1 minute' } } }
4848
: {};
4949
app.post('/:code', quickOpts, async (req, reply) => {
50-
const { code } = req.params as { code: string };
50+
const code = String((req.params as { code: string }).code).toUpperCase();
5151
const entry = await prisma.quickUploadCode.findUnique({ where: { code } });
5252
if (!entry || isExpired(entry.expiresAt) || isUsedUp(entry.usageLimit, entry.usageCount)) {
5353
return reply.code(404).send({ error: 'Code not found or no longer active' });

‎apps/api/test/integration.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,45 @@ runIf('API integration', () => {
252252
});
253253
});
254254

255+
describe('quick-upload codes', () => {
256+
it('accepts a memorable custom code, matched case-insensitively, and rejects duplicates', async () => {
257+
await createUser({ email: 'qc@test.local', password: 'correct-horse-battery', role: 'ADMIN' });
258+
const auth = await login(app, 'qc@test.local', 'correct-horse-battery');
259+
260+
const created = await app.inject({
261+
method: 'POST',
262+
url: '/admin/quick-codes',
263+
headers: authHeaders(auth),
264+
payload: { code: 'night-2024', usageLimit: 5 },
265+
});
266+
expect(created.statusCode).toBe(201);
267+
expect(created.json().code.code).toBe('NIGHT-2024'); // normalised to uppercase
268+
269+
// A guest can probe it regardless of the case they type.
270+
const probe = await app.inject({ method: 'GET', url: '/quick/Night-2024' });
271+
expect(probe.statusCode).toBe(200);
272+
expect(probe.json().valid).toBe(true);
273+
274+
// The same code can't be created twice.
275+
const dup = await app.inject({
276+
method: 'POST',
277+
url: '/admin/quick-codes',
278+
headers: authHeaders(auth),
279+
payload: { code: 'NIGHT-2024' },
280+
});
281+
expect(dup.statusCode).toBe(409);
282+
283+
// An invalid code shape is rejected by validation.
284+
const bad = await app.inject({
285+
method: 'POST',
286+
url: '/admin/quick-codes',
287+
headers: authHeaders(auth),
288+
payload: { code: 'no spaces!' },
289+
});
290+
expect(bad.statusCode).toBe(400);
291+
});
292+
});
293+
255294
describe('share links', () => {
256295
async function setupFileShare(extra: Record<string, unknown>) {
257296
await createUser({ email: 's@test.local', password: 'correct-horse-battery' });

‎apps/web/src/app/(app)/admin/page.tsx‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ export default function AdminPage() {
3232

3333
// new-user form
3434
const [nu, setNu] = useState({ email: '', password: '', role: 'USER' });
35+
// new quick-code form (optional memorable code)
36+
const [nc, setNc] = useState({ code: '', usageLimit: '' });
3537

3638
const [alerts, setAlerts] = useState<string[]>([]);
3739

@@ -200,18 +202,40 @@ export default function AdminPage() {
200202
{/* Quick codes */}
201203
<section className="card space-y-3">
202204
<h2 className="font-semibold">Quick-Upload codes</h2>
203-
<button
204-
className="btn-primary"
205-
onClick={() =>
206-
wrap(() =>
207-
api.post('/admin/quick-codes', {
208-
usageLimit: Number(window.prompt('Usage limit (empty = unlimited)') || '') || null,
209-
}),
210-
)
211-
}
212-
>
213-
Generate code
214-
</button>
205+
<p className="text-sm text-neutral-500">
206+
Leave the code blank for a random one, or set a memorable code you can type from any
207+
device (letters, digits and dashes).
208+
</p>
209+
<div className="flex flex-wrap items-center gap-2">
210+
<input
211+
className="input max-w-xs font-mono uppercase tracking-wide"
212+
placeholder="Custom code (optional)"
213+
value={nc.code}
214+
onChange={(e) => setNc({ ...nc, code: e.target.value.toUpperCase() })}
215+
/>
216+
<input
217+
className="input max-w-[10rem]"
218+
type="number"
219+
min={1}
220+
placeholder="Usage limit (∞)"
221+
value={nc.usageLimit}
222+
onChange={(e) => setNc({ ...nc, usageLimit: e.target.value })}
223+
/>
224+
<button
225+
className="btn-primary"
226+
onClick={() =>
227+
wrap(async () => {
228+
await api.post('/admin/quick-codes', {
229+
code: nc.code.trim() || undefined,
230+
usageLimit: Number(nc.usageLimit) || null,
231+
});
232+
setNc({ code: '', usageLimit: '' });
233+
})
234+
}
235+
>
236+
Create code
237+
</button>
238+
</div>
215239
<div className="divide-y divide-neutral-100 dark:divide-neutral-800">
216240
{codes.map((c) => (
217241
<div key={c.id} className="flex items-center justify-between gap-2 py-2 text-sm">

‎packages/shared/src/schemas.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,16 @@ export type RemoteUploadInput = z.infer<typeof remoteUploadSchema>;
108108

109109
export const createQuickCodeSchema = z.object({
110110
targetFolderId: cuidSchema.nullable().optional(),
111+
// Optional custom, memorable code (letters/digits/dashes). Blank => a random code is
112+
// generated. Normalised to uppercase so it's case-insensitive to type.
113+
code: z
114+
.string()
115+
.trim()
116+
.toUpperCase()
117+
.min(4)
118+
.max(32)
119+
.regex(/^[A-Z0-9][A-Z0-9-]*$/, 'Use letters, digits and dashes only')
120+
.optional(),
111121
// null/undefined => no per-upload size limit beyond the user's quota.
112122
maxBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).nullable().optional(),
113123
expiresAt: z.coerce.date().nullable().optional(),

0 commit comments

Comments
 (0)