V1.2.0: archive/delete campaigns and encounters, encounter sorting, change password, fuller seed
- Campaigns: DM can archive/restore; owner can delete. Archived campaigns move off the main list and stop accepting invite codes. - Encounters: DM can archive/restore and delete, and arrange the campaign's own order; the list can also be sorted by name, status, type or date. Archived encounters are hidden from players' lists. - Account page with change password (POST /auth/password). - Seed is now additive (safe on a live database; --reset for the old wipe) and builds a fuller Aldenfell: earned weapons, item pool, spells, NPCs, and 28 battle/quest scenes with descriptions, DM notes and rewards. - Vite preview host config for the deployed site. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1521,3 +1521,133 @@ describe('encounter combat info', () => {
|
||||
expect(typeof participant.characterCombatInfo.weapons[0].attackBonus).toBe('number');
|
||||
});
|
||||
});
|
||||
|
||||
describe('changing a password', () => {
|
||||
itIfDb('needs the current password, then only the new one logs in', async () => {
|
||||
const email = uniqueEmail('pw');
|
||||
const registerRes = await request(app).post('/auth/register').send({ email, password: 'password123', displayName: 'Pw' });
|
||||
cleanupUserIds.push(registerRes.body.user.id);
|
||||
const auth = { Authorization: `Bearer ${registerRes.body.token}` };
|
||||
|
||||
expect((await request(app).post('/auth/password').send({ currentPassword: 'password123', newPassword: 'new-password1' })).status).toBe(401);
|
||||
const wrong = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'nope', newPassword: 'new-password1' });
|
||||
expect(wrong.status).toBe(400);
|
||||
const short = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'password123', newPassword: 'short' });
|
||||
expect(short.status).toBe(400);
|
||||
const same = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'password123', newPassword: 'password123' });
|
||||
expect(same.status).toBe(400);
|
||||
|
||||
const changed = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'password123', newPassword: 'new-password1' });
|
||||
expect(changed.status).toBe(204);
|
||||
|
||||
expect((await request(app).post('/auth/login').send({ email, password: 'password123' })).status).toBe(401);
|
||||
expect((await request(app).post('/auth/login').send({ email, password: 'new-password1' })).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('archiving and deleting a campaign', () => {
|
||||
itIfDb('the DM archives and restores; an archived campaign keeps its contents but takes no new members', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('archive');
|
||||
const c = `/campaigns/${campaign.id}`;
|
||||
expect(campaign.archivedAt).toBeNull();
|
||||
|
||||
expect((await request(app).patch(c).set(playerAuth).send({ archived: true })).status).toBe(403);
|
||||
|
||||
const archived = await request(app).patch(c).set(dmAuth).send({ archived: true });
|
||||
expect(archived.status).toBe(200);
|
||||
expect(archived.body.campaign.archivedAt).toBeTruthy();
|
||||
|
||||
// Still there for its members, and flagged in their lists.
|
||||
const playerList = await request(app).get('/campaigns').set(playerAuth);
|
||||
expect(playerList.body.campaigns.find((x) => x.id === campaign.id).archivedAt).toBeTruthy();
|
||||
expect((await request(app).get(c).set(playerAuth)).status).toBe(200);
|
||||
|
||||
const outsider = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email: uniqueEmail('archive-outsider'), password: 'password123', displayName: 'Outsider' });
|
||||
cleanupUserIds.push(outsider.body.user.id);
|
||||
const outsiderAuth = { Authorization: `Bearer ${outsider.body.token}` };
|
||||
expect((await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(outsiderAuth)).status).toBe(403);
|
||||
|
||||
// Other settings can change without un-archiving it.
|
||||
const renamed = await request(app).patch(c).set(dmAuth).send({ startingGold: 7 });
|
||||
expect(renamed.body.campaign.archivedAt).toBeTruthy();
|
||||
|
||||
const restored = await request(app).patch(c).set(dmAuth).send({ archived: false });
|
||||
expect(restored.body.campaign.archivedAt).toBeNull();
|
||||
expect(restored.body.campaign.startingGold).toBe(7);
|
||||
expect((await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(outsiderAuth)).status).toBe(201);
|
||||
});
|
||||
|
||||
itIfDb('only the owner deletes, and everything in the campaign goes with it', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('delete');
|
||||
const c = `/campaigns/${campaign.id}`;
|
||||
const heroId = await buildCharacter(campaign.id, playerAuth, 'Doomed');
|
||||
const encounterRes = await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Last Stand' });
|
||||
const encounterId = encounterRes.body.encounter.id;
|
||||
await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId: heroId });
|
||||
await request(app).post('/notes').set(dmAuth).send({ campaignId: campaign.id, body: 'Secret', visibility: 'DM_ONLY' });
|
||||
|
||||
expect((await request(app).delete(c).set(playerAuth)).status).toBe(403);
|
||||
expect((await request(app).get(c).set(dmAuth)).status).toBe(200);
|
||||
|
||||
expect((await request(app).delete(c).set(dmAuth)).status).toBe(204);
|
||||
|
||||
expect((await request(app).get(c).set(dmAuth)).status).toBe(404);
|
||||
expect((await request(app).get(`/characters/${heroId}`).set(playerAuth)).status).toBe(404);
|
||||
expect((await request(app).get(`/encounters/${encounterId}`).set(dmAuth)).status).toBe(404);
|
||||
expect(await prisma.note.count({ where: { campaignId: campaign.id } })).toBe(0);
|
||||
const dmList = await request(app).get('/campaigns').set(dmAuth);
|
||||
expect(dmList.body.campaigns.find((x) => x.id === campaign.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ordering, archiving and deleting encounters', () => {
|
||||
itIfDb('the DM arranges the list, archives out of players\' sight, and deletes without undoing rewards', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('encorder');
|
||||
const c = `/campaigns/${campaign.id}`;
|
||||
const heroId = await buildCharacter(campaign.id, playerAuth, 'Keeper');
|
||||
|
||||
const ids = {};
|
||||
for (const name of ['One', 'Two', 'Three']) {
|
||||
ids[name] = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name })).body.encounter.id;
|
||||
}
|
||||
const names = async (auth) => (await request(app).get(`${c}/encounters`).set(auth)).body.encounters.map((e) => e.name);
|
||||
|
||||
// New encounters go to the top.
|
||||
expect(await names(dmAuth)).toEqual(['Three', 'Two', 'One']);
|
||||
|
||||
const order = (encounterIds, auth = dmAuth) => request(app).put(`${c}/encounters/order`).set(auth).send({ encounterIds });
|
||||
expect((await order([ids.One, ids.Two, ids.Three], playerAuth)).status).toBe(403);
|
||||
expect((await order([ids.One, ids.One])).status).toBe(400);
|
||||
expect((await order([ids.One, 'not-an-encounter'])).status).toBe(400);
|
||||
expect((await order([ids.One, ids.Two, ids.Three])).status).toBe(204);
|
||||
expect(await names(playerAuth)).toEqual(['One', 'Two', 'Three']);
|
||||
|
||||
// Archived: the DM still lists it, players don't, and it can still be opened.
|
||||
expect((await request(app).patch(`/encounters/${ids.Two}`).set(playerAuth).send({ archived: true })).status).toBe(403);
|
||||
const archived = await request(app).patch(`/encounters/${ids.Two}`).set(dmAuth).send({ archived: true });
|
||||
expect(archived.body.encounter.archivedAt).toBeTruthy();
|
||||
expect(await names(playerAuth)).toEqual(['One', 'Three']);
|
||||
expect(await names(dmAuth)).toEqual(['One', 'Two', 'Three']);
|
||||
expect((await request(app).get(`/encounters/${ids.Two}`).set(playerAuth)).status).toBe(200);
|
||||
|
||||
const restored = await request(app).patch(`/encounters/${ids.Two}`).set(dmAuth).send({ archived: false });
|
||||
expect(restored.body.encounter.archivedAt).toBeNull();
|
||||
expect(await names(playerAuth)).toEqual(['One', 'Two', 'Three']);
|
||||
|
||||
// Deleting takes the scene but leaves what it already gave out.
|
||||
await request(app).post(`/encounters/${ids.One}/participants`).set(dmAuth).send({ characterId: heroId });
|
||||
const rewardRes = await request(app).post(`/encounters/${ids.One}/rewards`).set(dmAuth).send({ type: 'GOLD', gold: 12 });
|
||||
await request(app).post(`/encounters/${ids.One}/rewards/${rewardRes.body.reward.id}/award`).set(dmAuth).send({ characterId: heroId });
|
||||
const goldBefore = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character.gold;
|
||||
|
||||
expect((await request(app).delete(`/encounters/${ids.One}`).set(playerAuth)).status).toBe(403);
|
||||
expect((await request(app).delete(`/encounters/${ids.One}`).set(dmAuth)).status).toBe(204);
|
||||
expect((await request(app).get(`/encounters/${ids.One}`).set(dmAuth)).status).toBe(404);
|
||||
expect(await names(dmAuth)).toEqual(['Two', 'Three']);
|
||||
const after = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character;
|
||||
expect(after.gold).toBe(goldBefore);
|
||||
expect(goldBefore).toBeGreaterThanOrEqual(12);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,11 @@ const loginSchema = z.object({
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
const changePasswordSchema = z.object({
|
||||
currentPassword: z.string().min(1),
|
||||
newPassword: z.string().min(8, 'Password must be at least 8 characters'),
|
||||
});
|
||||
|
||||
function issueToken(user) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, email: user.email, displayName: user.displayName },
|
||||
@@ -76,4 +81,28 @@ router.get('/me', requireAuth, async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Tokens already issued stay valid until they expire; this only changes what
|
||||
// the next login needs.
|
||||
router.post('/password', requireAuth, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = changePasswordSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { currentPassword, newPassword } = parsed.data;
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
|
||||
if (!user) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
const valid = await bcrypt.compare(currentPassword, user.passwordHash);
|
||||
if (!valid) return res.status(400).json({ error: 'Your current password is incorrect' });
|
||||
if (newPassword === currentPassword) {
|
||||
return res.status(400).json({ error: 'Your new password must be different from the current one' });
|
||||
}
|
||||
|
||||
await prisma.user.update({ where: { id: user.id }, data: { passwordHash: await bcrypt.hash(newPassword, 12) } });
|
||||
return res.status(204).end();
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -22,6 +22,7 @@ function campaignSummary(campaign, role) {
|
||||
startingSpellCount: campaign.startingSpellCount,
|
||||
skipMotivationRoll: campaign.skipMotivationRoll,
|
||||
ownerId: campaign.ownerId,
|
||||
archivedAt: campaign.archivedAt,
|
||||
role,
|
||||
createdAt: campaign.createdAt,
|
||||
};
|
||||
@@ -84,6 +85,7 @@ router.post('/join/:inviteCode', async (req, res, next) => {
|
||||
try {
|
||||
const campaign = await prisma.campaign.findUnique({ where: { inviteCode: req.params.inviteCode } });
|
||||
if (!campaign) return res.status(404).json({ error: 'Invalid invite code' });
|
||||
if (campaign.archivedAt) return res.status(403).json({ error: 'That campaign is archived and is not taking new members' });
|
||||
|
||||
const existing = await prisma.campaignMember.findUnique({
|
||||
where: { campaignId_userId: { campaignId: campaign.id, userId: req.user.id } },
|
||||
@@ -112,20 +114,41 @@ router.get('/:id', requireCampaignMember(), async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
const updateCampaignSchema = createCampaignSchema.partial();
|
||||
// `archived` puts the campaign away (true) or brings it back (false).
|
||||
const updateCampaignSchema = createCampaignSchema.partial().extend({ archived: z.boolean().optional() });
|
||||
|
||||
router.patch('/:id', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = updateCampaignSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const campaign = await prisma.campaign.update({ where: { id: req.campaign.id }, data: parsed.data });
|
||||
const { archived, ...data } = parsed.data;
|
||||
// Re-archiving keeps the original date.
|
||||
if (archived === true && !req.campaign.archivedAt) data.archivedAt = new Date();
|
||||
if (archived === false) data.archivedAt = null;
|
||||
|
||||
const campaign = await prisma.campaign.update({ where: { id: req.campaign.id }, data });
|
||||
res.json({ campaign: campaignSummary(campaign, 'DM') });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// Deleting takes everything in the campaign with it — characters, pools,
|
||||
// encounters, notes — so it is the owner's call alone, not any DM's.
|
||||
router.delete('/:id', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
if (req.campaign.ownerId !== req.user.id) {
|
||||
return res.status(403).json({ error: 'Only the campaign owner can delete it' });
|
||||
}
|
||||
await prisma.campaign.delete({ where: { id: req.campaign.id } });
|
||||
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('campaign:deleted', { campaignId: req.campaign.id });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/invite', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const regenerate = req.body && req.body.regenerate === true;
|
||||
@@ -510,9 +533,10 @@ router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(),
|
||||
router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const isDM = req.membership.role === 'DM';
|
||||
// Archived encounters are the DM's to see; players only get the live list.
|
||||
const encounters = await prisma.encounter.findMany({
|
||||
where: { campaignId: req.campaign.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
where: { campaignId: req.campaign.id, ...(isDM ? {} : { archivedAt: null }) },
|
||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
||||
});
|
||||
// dmNotes never leaves the server for a player.
|
||||
res.json({ encounters: isDM ? encounters : encounters.map(({ dmNotes, ...encounter }) => encounter) });
|
||||
@@ -531,13 +555,41 @@ router.post('/:id/encounters', requireCampaignMember(), requireDM(), async (req,
|
||||
try {
|
||||
const parsed = createEncounterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const encounter = await prisma.encounter.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
|
||||
// A new encounter goes to the top of the campaign's order.
|
||||
const first = await prisma.encounter.aggregate({ where: { campaignId: req.campaign.id }, _min: { sortOrder: true } });
|
||||
const encounter = await prisma.encounter.create({
|
||||
data: { ...parsed.data, campaignId: req.campaign.id, sortOrder: (first._min.sortOrder ?? 1) - 1 },
|
||||
});
|
||||
res.status(201).json({ encounter });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const encounterOrderSchema = z.object({ encounterIds: z.array(z.string()).min(1).max(1000) });
|
||||
|
||||
// Sets the campaign's own encounter order: the ids given take positions
|
||||
// 0, 1, 2... in the order sent.
|
||||
router.put('/:id/encounters/order', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = encounterOrderSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { encounterIds } = parsed.data;
|
||||
|
||||
const owned = await prisma.encounter.count({ where: { id: { in: encounterIds }, campaignId: req.campaign.id } });
|
||||
if (new Set(encounterIds).size !== encounterIds.length || owned !== encounterIds.length) {
|
||||
return res.status(400).json({ error: 'Send each encounter of this campaign once.' });
|
||||
}
|
||||
|
||||
await prisma.$transaction(
|
||||
encounterIds.map((id, sortOrder) => prisma.encounter.update({ where: { id }, data: { sortOrder } }))
|
||||
);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NPCs (DM only — players meet them through encounters, without the DM's
|
||||
// notes or stats)
|
||||
|
||||
@@ -174,13 +174,16 @@ const patchEncounterSchema = z.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(4000).nullable().optional(),
|
||||
dmNotes: z.string().max(4000).nullable().optional(),
|
||||
archived: z.boolean().optional(), // put away (true) or bring back (false)
|
||||
});
|
||||
|
||||
router.patch('/:id', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = patchEncounterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const data = { ...parsed.data };
|
||||
const { archived, ...data } = parsed.data;
|
||||
if (archived === true && !req.encounter.archivedAt) data.archivedAt = new Date();
|
||||
if (archived === false) data.archivedAt = null;
|
||||
|
||||
// Starting a battle puts the first combatant in the initiative order on turn.
|
||||
const mode = data.mode ?? req.encounter.mode;
|
||||
@@ -196,6 +199,18 @@ router.patch('/:id', requireEncounterAccess, requireDM, async (req, res, next) =
|
||||
}
|
||||
});
|
||||
|
||||
// Deleting removes the scene, its combatant rows and its reward list. What
|
||||
// was already handed out stays with the characters, as does their HP.
|
||||
router.delete('/:id', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
await prisma.encounter.delete({ where: { id: req.encounter.id } });
|
||||
emitEncounterUpdated(req);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combatants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user