Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,8 @@ dist
.pnp.*

.vscode
.idea
.idea
# Ignore env backups and local config
.env
.env.*
index.backup.yaml
67 changes: 67 additions & 0 deletions index.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,56 @@ paths:
description: Upload failed due to size/type restriction
'429':
description: Too many uploads from this IP (rate limit exceeded)

/consents:
post:
tags: [Consent]
summary: Save a user consent
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [user_id, consent_type]
properties:
user_id: { type: string, format: uuid, example: "93aadd91-aada-4d4c-b064-b2da0a7dce66" }
user_email: { type: string, format: email, example: "user@example.com" }
consent_type: { type: string, example: "privacy_policy" }
granted: { type: boolean, default: true }
metadata: { type: object, additionalProperties: true }
responses:
'201': { description: Consent saved }
'400': { description: Bad request }
'500': { description: Internal server error }

/consents/{user_id}:
get:
tags: [Consent]
summary: List consents for a user
parameters:
- in: path
name: user_id
required: true
schema: { type: string, format: uuid }
responses:
'200': { description: Consents returned }
'500': { description: Internal server error }

/consents/{uuid}/revoke:
patch:
tags: [Consent]
summary: Revoke a consent by primary key
parameters:
- in: path
name: uuid
required: true
schema: { type: string, format: uuid }
responses:
'200': { description: Consent revoked }
'404': { description: Consent not found }
'500': { description: Internal server error }

/appointments:
post:
summary: Save appointment data
Expand Down Expand Up @@ -3025,6 +3075,7 @@ components:
format: float
description: Model confidence score for diabetes prediction.
example: 0.798
<<<<<<< HEAD

BarcodeAllergenDetection:
type: object
Expand All @@ -3049,3 +3100,19 @@ components:
items:
type: string

=======
components:
schemas:
ConsentInput:
type: object
required: [user_id, consent_type, granted]
properties:
user_id: { type: string, format: uuid, example: '93aadd91-aada-4d4c-b064-b2da0a7dcee6' }
user_email: { type: string, format: email, example: 'user@example.com' }
consent_type: { type: string, example: 'privacy_policy' }
granted: { type: boolean, default: true }
metadata:
type: object
additionalProperties: true

>>>>>>> 38b1413 (feat(consent): add POST /consents, GET /consents/{user_id}, PATCH /consents/{id}/revoke; wire route; update OpenAPI docs)
12 changes: 12 additions & 0 deletions new_utils/supabaseAdmin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// new_utils/supabaseAdmin.js
const { createClient } = require('@supabase/supabase-js');

const SUPABASE_URL = process.env.SUPABASE_URL;
const SERVICE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;

// Create a server-side (non-persisted) admin client
const supabaseAdmin = createClient(SUPABASE_URL, SERVICE_KEY, {
auth: { persistSession: false }
});

module.exports = supabaseAdmin; // <-- default export
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"multer": "^1.4.5-lts.1",
"mysql2": "^3.9.2",
"node-fetch": "^3.3.2",
"nodemailer": "^7.0.6",
"nutrihelp-api": "file:",
"sinon": "^18.0.0",
"swagger-ui-express": "^5.0.0",
Expand Down
127 changes: 127 additions & 0 deletions routes/consent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// routes/consent.js
const express = require('express');
const router = express.Router();
const supabase = require('../new_utils/supabaseAdmin'); // SERVICE_ROLE client

// ───────────────────────────────────────────────────────────────
// CREATE / UPSERT
// POST /api/consents
// Body: { user_id, user_email?, consent_type, granted:boolean, metadata? }
// Unique key: (user_id, consent_type)
// ───────────────────────────────────────────────────────────────
router.post('/consents', async (req, res) => {
try {
const { user_id, user_email, consent_type, granted, metadata } = req.body || {};
if (!user_id || !consent_type || typeof granted !== 'boolean') {
return res
.status(400)
.json({ error: 'user_id, consent_type and granted (boolean) are required' });
}

const now = new Date().toISOString();
const row = {
user_id,
user_email: user_email || null,
consent_type,
granted: !!granted,
revoked_at: granted ? null : now,
metadata: metadata || null,
};

const { data, error } = await supabase
.from('consents')
.upsert(row, { onConflict: 'user_id,consent_type' })
.select('*')
.single();

if (error) throw error;
return res.status(201).json({ message: 'Consent saved', row: data });
} catch (e) {
console.error('[consents POST] error:', e);
return res.status(500).json({ error: 'Internal server error' });
}
});

// ───────────────────────────────────────────────────────────────
// LIST
// GET /api/consents/:user_id
// ───────────────────────────────────────────────────────────────
router.get('/consents/:user_id', async (req, res) => {
try {
const { user_id } = req.params;
const { data, error } = await supabase
.from('consents')
.select('*')
.eq('user_id', user_id)
.order('created_at', { ascending: false });

if (error) throw error;
return res.status(200).json({ consents: data });
} catch (e) {
console.error('[consents GET] error:', e);
return res.status(500).json({ error: 'Internal server error' });
}
});

// ───────────────────────────────────────────────────────────────
// REVOKE by consent row PK
// PATCH /api/consents/:id/revoke
// Also supports /api/consents/:uuid/revoke (Swagger alias)
// ───────────────────────────────────────────────────────────────
async function revokeByIdHandler(req, res) {
try {
// Accept both param names
const id = req.params.id || req.params.uuid;
console.log('[revokeById] params =', req.params, 'resolved id =', id);
if (!id) return res.status(400).json({ error: 'Missing consent id' });

const now = new Date().toISOString();
const { data, error } = await supabase
.from('consents')
.update({ granted: false, revoked_at: now })
.eq('id', id)
.select('*');

// data can be [] if nothing matched
if (error) return res.status(500).json({ error: error.message });
if (!data || data.length === 0) return res.status(404).json({ error: 'Consent not found' });

// If somehow multiple rows matched (shouldn’t happen for PK), return the first
return res.status(200).json({ message: 'Consent revoked', row: data[0] });
} catch (e) {
console.error('[revokeById] error:', e);
return res.status(500).json({ error: 'Internal server error' });
}
}
router.patch('/consents/:id/revoke', revokeByIdHandler);
router.patch('/consents/:uuid/revoke', revokeByIdHandler); // Swagger still using {uuid}

// ───────────────────────────────────────────────────────────────
// REVOKE by (user_id, consent_type) unique pair
// PATCH /api/consents/by-user/:user_id/:consent_type/revoke
// ───────────────────────────────────────────────────────────────
router.patch('/consents/by-user/:user_id/:consent_type/revoke', async (req, res) => {
try {
const { user_id, consent_type } = req.params;
console.log('[revokeByUser] params =', req.params);
const now = new Date().toISOString();

const { data, error } = await supabase
.from('consents')
.update({ granted: false, revoked_at: now })
.eq('user_id', user_id)
.eq('consent_type', consent_type)
.select('*');

if (error) return res.status(500).json({ error: error.message });
if (!data || data.length === 0) return res.status(404).json({ error: 'Consent not found' });

// unique constraint should make this 1 row; handle array defensively
return res.status(200).json({ message: 'Consent revoked', row: data[0] });
} catch (e) {
console.error('[revokeByUser] error:', e);
return res.status(500).json({ error: 'Internal server error' });
}
});

module.exports = router;
17 changes: 17 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ const rateLimit = require('express-rate-limit');
const uploadRoutes = require('./routes/uploadRoutes');
const fs = require("fs");
const path = require("path");
<<<<<<< HEAD
const systemRoutes = require('./routes/systemRoutes');
const loginDashboard = require('./routes/loginDashboard.js');
=======
const consentRoutes = require('./routes/consent');
>>>>>>> 38b1413 (feat(consent): add POST /consents, GET /consents/{user_id}, PATCH /consents/{id}/revoke; wire route; update OpenAPI docs)

// Ensure uploads directory exists
const uploadsDir = path.join(__dirname, 'uploads');
Expand Down Expand Up @@ -126,7 +130,20 @@ app.use((err, req, res, next) => {
res.status(500).json({ error: "Internal server error" });
});

<<<<<<< HEAD
// Start
=======
// Global error handler
app.use((err, req, res, next) => {
console.error("Unhandled error:", err);
res.status(500).json({ error: "Internal server error" });
});

// Consents use
app.use('/api', consentRoutes);

// Start server
>>>>>>> 38b1413 (feat(consent): add POST /consents, GET /consents/{user_id}, PATCH /consents/{id}/revoke; wire route; update OpenAPI docs)
app.listen(port, async () => {
console.log('\n🎉 NutriHelp API launched successfully!');
console.log('='.repeat(50));
Expand Down