mirror of
https://gitlab.com/PronounsPage/PronounsPage.git
synced 2025-10-01 00:57:23 -04:00

the #shared alias used by Nuxt cannot be easily disabled and to prevent breackage with jiti, we make use of it
53 lines
1.7 KiB
TypeScript
53 lines
1.7 KiB
TypeScript
import { Router } from 'express';
|
|
import { getH3Event } from 'h3-express';
|
|
import SQL from 'sql-template-strings';
|
|
import { ulid } from 'ulid';
|
|
|
|
import { auditLog } from '../audit.ts';
|
|
|
|
import { validateEmail } from './user.ts';
|
|
|
|
import { handleErrorAsync } from '#shared/helpers.ts';
|
|
import { getLocale } from '~~/server/data.ts';
|
|
|
|
const router = Router();
|
|
|
|
router.post('/subscription/subscribe', handleErrorAsync(async (req, res) => {
|
|
const email = (req.body.email || '').toLowerCase();
|
|
if (!email || !await validateEmail(email) || !['census'].includes(req.body.type)) {
|
|
return res.status(400).json({ error: 'Bad request' });
|
|
}
|
|
|
|
const locale = getLocale(getH3Event(req));
|
|
|
|
const existing = await req.db.get<{ c: number }>(SQL`
|
|
SELECT COUNT(*) as c FROM subscriptions WHERE email = ${email}
|
|
`);
|
|
|
|
if (existing!.c === 0) {
|
|
await req.db.get(SQL`INSERT INTO subscriptions (id, locale, type, email) VALUES
|
|
(${ulid()}, ${locale}, ${req.body.type}, ${email})`);
|
|
await auditLog(req, 'subscription/subscribed', { locale, type: req.body.type, email });
|
|
}
|
|
|
|
return res.json('Subscribed');
|
|
}));
|
|
|
|
// TODO /api/subscription/unsubscribe?email=andrea@avris.it&type=census
|
|
router.get('/subscription/unsubscribe', handleErrorAsync(async (req, res) => {
|
|
if (!req.query.email) {
|
|
return res.status(400).json({ error: 'Bad request' });
|
|
}
|
|
|
|
await req.db.get(SQL`DELETE FROM subscriptions WHERE email = ${req.query.email} AND type = ${req.query.type}`);
|
|
|
|
await auditLog(req, 'subscription/unsubscribed', {
|
|
type: req.query.type,
|
|
email: req.query.email,
|
|
});
|
|
|
|
return res.json('Unsubscribed');
|
|
}));
|
|
|
|
export default router;
|