All files / src/services groupInvitations.js

10% Statements 7/70
0% Branches 0/26
0% Functions 0/5
10.14% Lines 7/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280                                    1x 1x 1x 1x   1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1x            
/**
 * Service Invitations de groupe — Logique centralisee pour inviter,
 * accepter et lier les membres aux groupes.
 *
 * Utilise par :
 *   - POST /groups/:groupId/invitations (envoi invitation)
 *   - POST /groups/invitations/accept/:token (acceptation manuelle)
 *   - POST /auth/register (liaison post-inscription automatique)
 *
 * Securite :
 *   - Le token brut n'est jamais stocke en base
 *   - Seul le hash SHA-256 est persiste dans token_hash
 *   - Expiration 72h
 *   - Maximum 5 envois par couple (group_id, email)
 *
 * @module services/groupInvitations
 */
 
const crypto = require('node:crypto');
const { pool: db } = require('../db');
const { sendEmail } = require('./email');
const { invalidateGroupCache } = require('../helpers/groupAccess');
 
const INVITATION_TTL_HOURS = 72;
const MAX_SEND_COUNT = 5;
 
/**
 * Hache un token brut en SHA-256 hex.
 * @param {string} token
 * @returns {string}
 */
function hashToken(token) {
  return crypto.createHash('sha256').update(token).digest('hex');
}
 
/**
 * Cree ou renvoie une invitation pour un email dans un groupe.
 *
 * @param {object} params
 * @param {string} params.groupId
 * @param {string} params.invitedByUserId
 * @param {string} params.email
 * @param {object} params.permissions — JSON de permissions
 * @param {string} params.appUrl — URL du frontend (pour le lien email)
 * @returns {Promise<object>} — L'invitation creee/mise a jour
 */
async function createOrResendInvitation({ groupId, invitedByUserId, email, permissions, appUrl }) {
  const normalizedEmail = email.toLowerCase().trim();
 
  // Verifier si l'email est deja membre actif du groupe
  const { rows: existingMembers } = await db.query(
    `SELECT agm.id FROM access_group_members agm
     JOIN users u ON u.id = agm.user_id
     WHERE agm.group_id = $1 AND u.email = $2 AND agm.status = 'active'`,
    [groupId, normalizedEmail],
  );
  if (existingMembers.length > 0) {
    throw Object.assign(new Error('Cet email est deja membre du groupe.'), { status: 409 });
  }
 
  // Verifier s'il existe deja une invitation pour ce couple (group_id, email)
  const { rows: existing } = await db.query(
    `SELECT id, send_count, accepted_at, revoked_at, expires_at
     FROM access_group_invitations
     WHERE group_id = $1 AND email = $2
     ORDER BY created_at DESC LIMIT 1`,
    [groupId, normalizedEmail],
  );
 
  if (existing.length > 0) {
    const inv = existing[0];
 
    // Deja acceptee
    if (inv.accepted_at) {
      throw Object.assign(new Error('Cette invitation a deja ete acceptee.'), { status: 409 });
    }
 
    // Blocage definitif apres 5 envois
    if (inv.send_count >= MAX_SEND_COUNT) {
      throw Object.assign(new Error('Limite de renvois atteinte pour cet email.'), { status: 429 });
    }
 
    // Non expiree et non revoquee — bloquer le renvoi
    if (!inv.revoked_at && inv.expires_at > new Date()) {
      throw Object.assign(new Error('Une invitation valide existe deja pour cet email.'), { status: 409 });
    }
 
    // Expirée ou revoquée — mettre a jour la ligne existante
    const tokenRaw = crypto.randomBytes(32).toString('hex');
    const tokenHash = hashToken(tokenRaw);
    const expiresAt = new Date(Date.now() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
 
    const { rows: updated } = await db.query(
      `UPDATE access_group_invitations
       SET token_hash = $1, expires_at = $2, revoked_at = NULL, accepted_at = NULL,
           permissions = $3, send_count = send_count + 1, invited_by_user_id = $4
       WHERE id = $5
       RETURNING id, group_id, email, permissions, send_count, expires_at, created_at`,
      [tokenHash, expiresAt, JSON.stringify(permissions), invitedByUserId, inv.id],
    );
 
    await sendInvitationEmail(normalizedEmail, tokenRaw, groupId, appUrl);
 
    return updated[0];
  }
 
  // Nouvelle invitation
  const tokenRaw = crypto.randomBytes(32).toString('hex');
  const tokenHash = hashToken(tokenRaw);
  const expiresAt = new Date(Date.now() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
 
  const { rows: created } = await db.query(
    `INSERT INTO access_group_invitations (group_id, invited_by_user_id, email, token_hash, permissions, expires_at)
     VALUES ($1, $2, $3, $4, $5, $6)
     RETURNING id, group_id, email, permissions, send_count, expires_at, created_at`,
    [groupId, invitedByUserId, normalizedEmail, tokenHash, JSON.stringify(permissions), expiresAt],
  );
 
  await sendInvitationEmail(normalizedEmail, tokenRaw, groupId, appUrl);
 
  return created[0];
}
 
/**
 * Accepte une invitation via le token brut.
 *
 * @param {string} tokenRaw — Token brut recu par email
 * @param {string} userId — UUID de l'utilisateur qui accepte
 * @returns {Promise<object>} — Le membership cree
 */
async function acceptInvitation(tokenRaw, userId) {
  const tokenHash = hashToken(tokenRaw);
 
  const { rows } = await db.query(
    `SELECT i.*, ag.owner_user_id
     FROM access_group_invitations i
     JOIN access_groups ag ON ag.id = i.group_id
     WHERE i.token_hash = $1`,
    [tokenHash],
  );
 
  if (rows.length === 0) {
    throw Object.assign(new Error('Invitation introuvable ou invalide.'), { status: 404 });
  }
 
  const invitation = rows[0];
 
  if (invitation.accepted_at) {
    throw Object.assign(new Error('Invitation deja acceptee.'), { status: 409 });
  }
  if (invitation.revoked_at) {
    throw Object.assign(new Error('Invitation revoquee.'), { status: 410 });
  }
  if (invitation.expires_at < new Date()) {
    throw Object.assign(new Error('Invitation expiree.'), { status: 410 });
  }
 
  // Verifier que l'utilisateur n'est pas deja membre actif
  const { rows: existingMember } = await db.query(
    `SELECT id FROM access_group_members WHERE group_id = $1 AND user_id = $2 AND status = 'active'`,
    [invitation.group_id, userId],
  );
  if (existingMember.length > 0) {
    // Marquer l'invitation comme acceptee quand meme
    await db.query(
      'UPDATE access_group_invitations SET accepted_at = NOW(), linked_user_id = $1 WHERE id = $2',
      [userId, invitation.id],
    );
    throw Object.assign(new Error('Vous etes deja membre de ce groupe.'), { status: 409 });
  }
 
  // Creer le membership (ou reactiver si revoque)
  const { rows: membership } = await db.query(
    `INSERT INTO access_group_members (group_id, user_id, invited_by_user_id, permissions, status, joined_at)
     VALUES ($1, $2, $3, $4, 'active', NOW())
     ON CONFLICT (group_id, user_id)
     DO UPDATE SET status = 'active', permissions = $4, joined_at = NOW(), updated_at = NOW()
     RETURNING id, group_id, user_id, permissions, status`,
    [invitation.group_id, userId, invitation.invited_by_user_id, JSON.stringify(invitation.permissions)],
  );
 
  // Marquer l'invitation comme acceptee
  await db.query(
    'UPDATE access_group_invitations SET accepted_at = NOW(), linked_user_id = $1 WHERE id = $2',
    [userId, invitation.id],
  );
 
  // Invalider le cache pour ce membre
  invalidateGroupCache(userId, invitation.group_id);
 
  return membership[0];
}
 
/**
 * Accepte automatiquement toutes les invitations en attente pour un email.
 * Appele apres la creation d'un compte (POST /auth/register).
 *
 * @param {string} email
 * @param {string} userId
 * @returns {Promise<number>} — Nombre d'invitations acceptees
 */
async function acceptPendingInvitationsForEmail(email, userId) {
  const normalizedEmail = email.toLowerCase().trim();
 
  const { rows: pending } = await db.query(
    `SELECT id, token_hash FROM access_group_invitations
     WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > NOW()`,
    [normalizedEmail],
  );
 
  let accepted = 0;
  for (const inv of pending) {
    try {
      // On passe par acceptInvitation avec le hash directement
      // Mais on ne peut pas car acceptInvitation attend le token brut.
      // On fait donc la liaison directement ici.
      const { rows: invDetails } = await db.query(
        `SELECT i.*, ag.owner_user_id
         FROM access_group_invitations i
         JOIN access_groups ag ON ag.id = i.group_id
         WHERE i.id = $1`,
        [inv.id],
      );
      if (invDetails.length === 0) continue;
 
      const invitation = invDetails[0];
 
      await db.query(
        `INSERT INTO access_group_members (group_id, user_id, invited_by_user_id, permissions, status, joined_at)
         VALUES ($1, $2, $3, $4, 'active', NOW())
         ON CONFLICT (group_id, user_id)
         DO UPDATE SET status = 'active', permissions = $4, joined_at = NOW(), updated_at = NOW()`,
        [invitation.group_id, userId, invitation.invited_by_user_id, JSON.stringify(invitation.permissions)],
      );
 
      await db.query(
        'UPDATE access_group_invitations SET accepted_at = NOW(), linked_user_id = $1 WHERE id = $2',
        [userId, inv.id],
      );
 
      invalidateGroupCache(userId, invitation.group_id);
      accepted++;
    } catch {
      // Ignorer les erreurs individuelles
    }
  }
 
  return accepted;
}
 
/**
 * Envoie l'email d'invitation.
 */
async function sendInvitationEmail(email, tokenRaw, groupId, appUrl) {
  const acceptUrl = `${appUrl || 'https://app.iliacloud.com'}/invite/accept?token=${tokenRaw}`;
 
  try {
    await sendEmail({
      to: email,
      subject: 'Invitation a rejoindre un groupe IliaCloud',
      html: `
        <h2>Vous avez ete invite sur IliaCloud</h2>
        <p>Cliquez sur le lien ci-dessous pour accepter l'invitation :</p>
        <p><a href="${acceptUrl}" style="display:inline-block;padding:12px 24px;background:#6366f1;color:#fff;border-radius:8px;text-decoration:none;">Accepter l'invitation</a></p>
        <p style="color:#888;font-size:13px;">Ce lien expire dans 72 heures.</p>
      `,
      text: `Vous avez ete invite sur IliaCloud. Acceptez l'invitation ici : ${acceptUrl}`,
    });
  } catch (err) {
    console.error('[group-invitations] Erreur envoi email:', err.message);
  }
}
 
module.exports = {
  createOrResendInvitation,
  acceptInvitation,
  acceptPendingInvitationsForEmail,
  hashToken,
};