Add scouthub-home-be
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { creaInvito, getInvitoPubblico, accettaInvito } from '../services/inviti.service';
|
||||
import { HttpError } from '../errors';
|
||||
|
||||
interface PostInvitoBody {
|
||||
email?: unknown;
|
||||
ruolo?: unknown;
|
||||
}
|
||||
|
||||
function parseCreaInvitoBody(body: PostInvitoBody): { email: string; ruolo: string } {
|
||||
if (typeof body.email !== 'string' || body.email.trim().length === 0) {
|
||||
throw new HttpError(400, "Il campo 'email' è obbligatorio ed è una stringa non vuota");
|
||||
}
|
||||
if (typeof body.ruolo !== 'string' || body.ruolo.trim().length === 0) {
|
||||
throw new HttpError(400, "Il campo 'ruolo' è obbligatorio ed è una stringa non vuota");
|
||||
}
|
||||
return { email: body.email, ruolo: body.ruolo };
|
||||
}
|
||||
|
||||
export async function postInvito(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
try {
|
||||
const { orgId } = req.params;
|
||||
|
||||
// Un capo gruppo può invitare solo all'interno della propria organization.
|
||||
if (req.auth?.organizationId !== orgId) {
|
||||
throw new HttpError(403, "Non puoi invitare persone in un'organizzazione diversa dalla tua");
|
||||
}
|
||||
|
||||
const { email, ruolo } = parseCreaInvitoBody(req.body ?? {});
|
||||
const result = await creaInvito({ orgId, email, ruolo });
|
||||
|
||||
res.status(201).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getInvito(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
try {
|
||||
const { token } = req.params;
|
||||
const invito = await getInvitoPubblico(token);
|
||||
|
||||
if (!invito) {
|
||||
throw new HttpError(404, 'Invito non trovato');
|
||||
}
|
||||
|
||||
res.json(invito);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function postAccettaInvito(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
try {
|
||||
const { token } = req.params;
|
||||
const result = await accettaInvito(token, {
|
||||
userId: req.auth!.userId,
|
||||
email: req.auth!.email,
|
||||
});
|
||||
|
||||
res.status(200).json(result);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user