From ada8ca312aa5dff57ce9b3094845c4bda614da50 Mon Sep 17 00:00:00 2001 From: LaurentiuSorinTENE Date: Sun, 24 Nov 2024 12:03:44 +0200 Subject: [PATCH 1/3] final --- models/contacts.js | 44 +++++++++++++--- models/contacts.json | 14 ++--- package-lock.json | 114 ++++++++++++++++++++++++++++++++++++++++- package.json | 4 +- routes/api/contacts.js | 87 ++++++++++++++++++++++++++----- 5 files changed, 234 insertions(+), 29 deletions(-) diff --git a/models/contacts.js b/models/contacts.js index 409d11c7c09..8652a19ccf0 100644 --- a/models/contacts.js +++ b/models/contacts.js @@ -1,14 +1,44 @@ -// const fs = require('fs/promises') +const fs = require('fs/promises'); +const path = require('path'); +const { v4: uuidv4 } = require('uuid'); -const listContacts = async () => {} +const contactsPath = path.join(__dirname, 'contacts.json'); -const getContactById = async (contactId) => {} +const listContacts = async () => { + const data = await fs.readFile(contactsPath, 'utf-8'); + return JSON.parse(data); +}; -const removeContact = async (contactId) => {} +const getContactById = async (contactId) => { + const contacts = await listContacts(); + return contacts.find((contact) => contact.id === contactId) || null; +}; -const addContact = async (body) => {} +const addContact = async ({ name, email, phone }) => { + const contacts = await listContacts(); + const newContact = { id: uuidv4(), name, email, phone }; + contacts.push(newContact); + await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); + return newContact; +}; -const updateContact = async (contactId, body) => {} +const removeContact = async (contactId) => { + const contacts = await listContacts(); + const index = contacts.findIndex((contact) => contact.id === contactId); + if (index === -1) return null; + const [removedContact] = contacts.splice(index, 1); + await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); + return removedContact; +}; + +const updateContact = async (contactId, body) => { + const contacts = await listContacts(); + const index = contacts.findIndex((contact) => contact.id === contactId); + if (index === -1) return null; + contacts[index] = { ...contacts[index], ...body }; + await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); + return contacts[index]; +}; module.exports = { listContacts, @@ -16,4 +46,4 @@ module.exports = { removeContact, addContact, updateContact, -} +}; diff --git a/models/contacts.json b/models/contacts.json index a21679132de..b3622f935c3 100644 --- a/models/contacts.json +++ b/models/contacts.json @@ -1,10 +1,4 @@ [ - { - "id": "AeHIrLTr6JkxGE6SN-0Rw", - "name": "Allen Raymond", - "email": "nulla.ante@vestibul.co.uk", - "phone": "(992) 914-3792" - }, { "id": "qdggE76Jtbfd9eWJHrssH", "name": "Chaim Lewis", @@ -58,5 +52,11 @@ "name": "Alec Howard", "email": "Donec.elementum@scelerisquescelerisquedui.net", "phone": "(748) 206-2688" + }, + { + "id": "716a8796-9754-44ba-8652-32039cde58ab", + "name": "John Doe", + "email": "john.doe@example.com", + "phone": "123-456-7890" } -] +] \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index e6d047044e5..12b701e1b59 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,9 @@ "cors": "2.8.5", "cross-env": "7.0.3", "express": "4.17.1", - "morgan": "1.10.0" + "joi": "^17.13.3", + "morgan": "1.10.0", + "uuid": "^11.0.3" }, "devDependencies": { "eslint": "7.19.0", @@ -141,6 +143,42 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/@hapi/hoek": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", + "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@hapi/topo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz", + "integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^9.0.0" + } + }, + "node_modules/@sideway/address": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz", + "integrity": "sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^9.0.0" + } + }, + "node_modules/@sideway/formula": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sideway/formula/-/formula-3.0.1.tgz", + "integrity": "sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg==", + "license": "BSD-3-Clause" + }, + "node_modules/@sideway/pinpoint": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sideway/pinpoint/-/pinpoint-2.0.0.tgz", + "integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==", + "license": "BSD-3-Clause" + }, "node_modules/@sindresorhus/is": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", @@ -2166,6 +2204,19 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, + "node_modules/joi": { + "version": "17.13.3", + "resolved": "https://registry.npmjs.org/joi/-/joi-17.13.3.tgz", + "integrity": "sha512-otDA4ldcIx+ZXsKHWmp0YizCweVRZG96J10b0FevjfuncLO1oX59THoAmHkNubYJ+9gWsYsp5k8v4ib6oDv1fA==", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^9.3.0", + "@hapi/topo": "^5.1.0", + "@sideway/address": "^4.1.5", + "@sideway/formula": "^3.0.1", + "@sideway/pinpoint": "^2.0.0" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -3544,6 +3595,19 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.3.tgz", + "integrity": "sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", @@ -3757,6 +3821,37 @@ "strip-json-comments": "^3.1.1" } }, + "@hapi/hoek": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", + "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==" + }, + "@hapi/topo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz", + "integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==", + "requires": { + "@hapi/hoek": "^9.0.0" + } + }, + "@sideway/address": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz", + "integrity": "sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==", + "requires": { + "@hapi/hoek": "^9.0.0" + } + }, + "@sideway/formula": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sideway/formula/-/formula-3.0.1.tgz", + "integrity": "sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg==" + }, + "@sideway/pinpoint": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sideway/pinpoint/-/pinpoint-2.0.0.tgz", + "integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==" + }, "@sindresorhus/is": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", @@ -5269,6 +5364,18 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, + "joi": { + "version": "17.13.3", + "resolved": "https://registry.npmjs.org/joi/-/joi-17.13.3.tgz", + "integrity": "sha512-otDA4ldcIx+ZXsKHWmp0YizCweVRZG96J10b0FevjfuncLO1oX59THoAmHkNubYJ+9gWsYsp5k8v4ib6oDv1fA==", + "requires": { + "@hapi/hoek": "^9.3.0", + "@hapi/topo": "^5.1.0", + "@sideway/address": "^4.1.5", + "@sideway/formula": "^3.0.1", + "@sideway/pinpoint": "^2.0.0" + } + }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -6326,6 +6433,11 @@ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" }, + "uuid": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.3.tgz", + "integrity": "sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg==" + }, "v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", diff --git a/package.json b/package.json index 5045e827160..b52f3d043d3 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,9 @@ "cors": "2.8.5", "cross-env": "7.0.3", "express": "4.17.1", - "morgan": "1.10.0" + "joi": "^17.13.3", + "morgan": "1.10.0", + "uuid": "^11.0.3" }, "devDependencies": { "eslint": "7.19.0", diff --git a/routes/api/contacts.js b/routes/api/contacts.js index a60ebd69231..a00eb5c96d5 100644 --- a/routes/api/contacts.js +++ b/routes/api/contacts.js @@ -1,25 +1,86 @@ -const express = require('express') +const express = require('express'); +const Joi = require('joi'); -const router = express.Router() +const { + listContacts, + getContactById, + addContact, + removeContact, + updateContact, +} = require('../../models/contacts'); + +const router = express.Router(); + +// Validation schema +const contactSchema = Joi.object({ + name: Joi.string().required(), + email: Joi.string().email().required(), + phone: Joi.string().required(), +}); router.get('/', async (req, res, next) => { - res.json({ message: 'template message' }) -}) + try { + const contacts = await listContacts(); + res.status(200).json(contacts); + } catch (error) { + next(error); + } +}); router.get('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) + try { + const { contactId } = req.params; + const contact = await getContactById(contactId); + if (!contact) { + return res.status(404).json({ message: 'Not found' }); + } + res.status(200).json(contact); + } catch (error) { + next(error); + } +}); router.post('/', async (req, res, next) => { - res.json({ message: 'template message' }) -}) + try { + const { error } = contactSchema.validate(req.body); + if (error) { + return res.status(400).json({ message: 'missing required name field' }); + } + const newContact = await addContact(req.body); + res.status(201).json(newContact); + } catch (error) { + next(error); + } +}); router.delete('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) + try { + const { contactId } = req.params; + const contact = await removeContact(contactId); + if (!contact) { + return res.status(404).json({ message: 'Not found' }); + } + res.status(200).json({ message: 'contact deleted' }); + } catch (error) { + next(error); + } +}); router.put('/:contactId', async (req, res, next) => { - res.json({ message: 'template message' }) -}) + try { + const { contactId } = req.params; + const { error } = contactSchema.validate(req.body); + if (error) { + return res.status(400).json({ message: 'missing fields' }); + } + const updatedContact = await updateContact(contactId, req.body); + if (!updatedContact) { + return res.status(404).json({ message: 'Not found' }); + } + res.status(200).json(updatedContact); + } catch (error) { + next(error); + } +}); -module.exports = router +module.exports = router; From 15161cc90eb078e5438636c5d54786d04d586a3c Mon Sep 17 00:00:00 2001 From: LaurentiuSorinTENE Date: Sun, 1 Dec 2024 16:34:51 +0200 Subject: [PATCH 2/3] final code Tema3 --- app.js | 13 ++ models/contacts.js | 62 +++----- models/contacts.json | 62 -------- package-lock.json | 350 +++++++++++++++++++++++++++++++++++++++-- package.json | 1 + routes/api/contacts.js | 23 +++ testConnection.js | 12 ++ 7 files changed, 411 insertions(+), 112 deletions(-) delete mode 100644 models/contacts.json create mode 100644 testConnection.js diff --git a/app.js b/app.js index 40fd9bc167f..6fba01ffe0f 100644 --- a/app.js +++ b/app.js @@ -2,6 +2,19 @@ const express = require('express') const logger = require('morgan') const cors = require('cors') +const mongoose = require('mongoose'); + +// MongoDB connection +const DB_URI = 'mongodb+srv://sorintene:1234qwer@test-cluster.jnsni.mongodb.net/db-contacts?retryWrites=true&w=majority'; + +mongoose.connect(DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('Database connection successful')) + .catch(error => { + console.error('Database connection error:', error.message); + process.exit(1); + }); + + const contactsRouter = require('./routes/api/contacts') const app = express() diff --git a/models/contacts.js b/models/contacts.js index 8652a19ccf0..c129d664ea6 100644 --- a/models/contacts.js +++ b/models/contacts.js @@ -1,49 +1,39 @@ -const fs = require('fs/promises'); -const path = require('path'); -const { v4: uuidv4 } = require('uuid'); +const mongoose = require('mongoose'); -const contactsPath = path.join(__dirname, 'contacts.json'); +const contactSchema = new mongoose.Schema({ + name: { + type: String, + required: [true, 'Set name for contact'], + }, + email: String, + phone: String, + favorite: { + type: Boolean, + default: false, + }, +}); -const listContacts = async () => { - const data = await fs.readFile(contactsPath, 'utf-8'); - return JSON.parse(data); -}; +const Contact = mongoose.model('Contact', contactSchema); -const getContactById = async (contactId) => { - const contacts = await listContacts(); - return contacts.find((contact) => contact.id === contactId) || null; -}; +const listContacts = async () => Contact.find(); -const addContact = async ({ name, email, phone }) => { - const contacts = await listContacts(); - const newContact = { id: uuidv4(), name, email, phone }; - contacts.push(newContact); - await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); - return newContact; -}; +const getContactById = async (contactId) => Contact.findById(contactId); -const removeContact = async (contactId) => { - const contacts = await listContacts(); - const index = contacts.findIndex((contact) => contact.id === contactId); - if (index === -1) return null; - const [removedContact] = contacts.splice(index, 1); - await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); - return removedContact; -}; +const addContact = async (contactData) => Contact.create(contactData); -const updateContact = async (contactId, body) => { - const contacts = await listContacts(); - const index = contacts.findIndex((contact) => contact.id === contactId); - if (index === -1) return null; - contacts[index] = { ...contacts[index], ...body }; - await fs.writeFile(contactsPath, JSON.stringify(contacts, null, 2)); - return contacts[index]; -}; +const removeContact = async (contactId) => Contact.findByIdAndRemove(contactId); + +const updateContact = async (contactId, updateData) => + Contact.findByIdAndUpdate(contactId, updateData, { new: true }); + +const updateFavorite = async (contactId, favorite) => + Contact.findByIdAndUpdate(contactId, { favorite }, { new: true }); module.exports = { listContacts, getContactById, - removeContact, addContact, + removeContact, updateContact, + updateFavorite, }; diff --git a/models/contacts.json b/models/contacts.json deleted file mode 100644 index b3622f935c3..00000000000 --- a/models/contacts.json +++ /dev/null @@ -1,62 +0,0 @@ -[ - { - "id": "qdggE76Jtbfd9eWJHrssH", - "name": "Chaim Lewis", - "email": "dui.in@egetlacus.ca", - "phone": "(294) 840-6685" - }, - { - "id": "drsAJ4SHPYqZeG-83QTVW", - "name": "Kennedy Lane", - "email": "mattis.Cras@nonenimMauris.net", - "phone": "(542) 451-7038" - }, - { - "id": "vza2RIzNGIwutCVCs4mCL", - "name": "Wylie Pope", - "email": "est@utquamvel.net", - "phone": "(692) 802-2949" - }, - { - "id": "05olLMgyVQdWRwgKfg5J6", - "name": "Cyrus Jackson", - "email": "nibh@semsempererat.com", - "phone": "(501) 472-5218" - }, - { - "id": "1DEXoP8AuCGYc1YgoQ6hw", - "name": "Abbot Franks", - "email": "scelerisque@magnis.org", - "phone": "(186) 568-3720" - }, - { - "id": "Z5sbDlS7pCzNsnAHLtDJd", - "name": "Reuben Henry", - "email": "pharetra.ut@dictum.co.uk", - "phone": "(715) 598-5792" - }, - { - "id": "C9sjBfCo4UJCWjzBnOtxl", - "name": "Simon Morton", - "email": "dui.Fusce.diam@Donec.com", - "phone": "(233) 738-2360" - }, - { - "id": "e6ywwRe4jcqxXfCZOj_1e", - "name": "Thomas Lucas", - "email": "nec@Nulla.com", - "phone": "(704) 398-7993" - }, - { - "id": "rsKkOQUi80UsgVPCcLZZW", - "name": "Alec Howard", - "email": "Donec.elementum@scelerisquescelerisquedui.net", - "phone": "(748) 206-2688" - }, - { - "id": "716a8796-9754-44ba-8652-32039cde58ab", - "name": "John Doe", - "email": "john.doe@example.com", - "phone": "123-456-7890" - } -] \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 12b701e1b59..1c7ce3c95a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "cross-env": "7.0.3", "express": "4.17.1", "joi": "^17.13.3", + "mongoose": "^8.8.2", "morgan": "1.10.0", "uuid": "^11.0.3" }, @@ -158,6 +159,15 @@ "@hapi/hoek": "^9.0.0" } }, + "node_modules/@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "license": "MIT", + "dependencies": { + "sparse-bitfield": "^3.0.3" + } + }, "node_modules/@sideway/address": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz", @@ -206,6 +216,21 @@ "integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=", "dev": true }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", + "license": "MIT" + }, + "node_modules/@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, "node_modules/abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -490,6 +515,15 @@ "node": ">=8" } }, + "node_modules/bson": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.0.tgz", + "integrity": "sha512-ROchNosXMJD2cbQGm84KoP7vOGPO6/bOAW0veMMbzhXLqoZptcaYRVLitwvuhwhjjpU1qP4YZRWLhgETdgqUQw==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.20.1" + } + }, "node_modules/bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", @@ -766,7 +800,6 @@ "version": "4.3.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", - "dev": true, "dependencies": { "ms": "2.1.2" }, @@ -2266,6 +2299,15 @@ "json5": "lib/cli.js" } }, + "node_modules/kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/keyv": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", @@ -2378,6 +2420,12 @@ "node": ">= 0.6" } }, + "node_modules/memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "license": "MIT" + }, "node_modules/merge-descriptors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", @@ -2448,6 +2496,90 @@ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", "dev": true }, + "node_modules/mongodb": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.10.0.tgz", + "integrity": "sha512-gP9vduuYWb9ZkDM546M+MP2qKVk5ZG2wPF63OvSRuUbqCR+11ZCAE1mOfllhlAG0wcoJY5yDL/rV3OmYEwXIzg==", + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + }, + "engines": { + "node": ">=16.20.1" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.188.0", + "@mongodb-js/zstd": "^1.1.0", + "gcp-metadata": "^5.2.0", + "kerberos": "^2.0.1", + "mongodb-client-encryption": ">=6.0.0 <7", + "snappy": "^7.2.2", + "socks": "^2.7.1" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "node_modules/mongoose": { + "version": "8.8.2", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.8.2.tgz", + "integrity": "sha512-jCTSqDANfRzk909v4YoZQi7jlGRB2MTvgG+spVBc/BA4tOs1oWJr//V6yYujqNq9UybpOtsSfBqxI0dSOEFJHQ==", + "license": "MIT", + "dependencies": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "~6.10.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "engines": { + "node": ">=16.20.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mongoose" + } + }, + "node_modules/mongoose/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/morgan": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz", @@ -2484,11 +2616,31 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, + "node_modules/mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "license": "MIT", + "dependencies": { + "debug": "4.x" + }, + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/natural-compare": { "version": "1.4.0", @@ -2914,10 +3066,10 @@ } }, "node_modules/punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true, + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", "engines": { "node": ">=6" } @@ -3236,6 +3388,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==", + "license": "MIT" + }, "node_modules/signal-exit": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz", @@ -3259,6 +3417,15 @@ "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, + "node_modules/sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "license": "MIT", + "dependencies": { + "memory-pager": "^1.0.2" + } + }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -3443,6 +3610,18 @@ "nodetouch": "bin/nodetouch.js" } }, + "node_modules/tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.0" + }, + "engines": { + "node": ">=14" + } + }, "node_modules/tsconfig-paths": { "version": "3.12.0", "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.12.0.tgz", @@ -3622,6 +3801,28 @@ "node": ">= 0.8" } }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "license": "MIT", + "dependencies": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3834,6 +4035,14 @@ "@hapi/hoek": "^9.0.0" } }, + "@mongodb-js/saslprep": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz", + "integrity": "sha512-tVkljjeEaAhCqTzajSdgbQ6gE6f3oneVwa3iXR6csiEwXXOFsiC6Uh9iAjAhXPtqa/XMDHWjjeNH/77m/Yq2dw==", + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, "@sideway/address": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz", @@ -3873,6 +4082,19 @@ "integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=", "dev": true }, + "@types/webidl-conversions": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz", + "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==" + }, + "@types/whatwg-url": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", + "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", + "requires": { + "@types/webidl-conversions": "*" + } + }, "abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -4092,6 +4314,11 @@ "fill-range": "^7.0.1" } }, + "bson": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.0.tgz", + "integrity": "sha512-ROchNosXMJD2cbQGm84KoP7vOGPO6/bOAW0veMMbzhXLqoZptcaYRVLitwvuhwhjjpU1qP4YZRWLhgETdgqUQw==" + }, "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", @@ -4293,7 +4520,6 @@ "version": "4.3.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz", "integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==", - "dev": true, "requires": { "ms": "2.1.2" } @@ -5419,6 +5645,11 @@ "minimist": "^1.2.0" } }, + "kareem": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", + "integrity": "sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==" + }, "keyv": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", @@ -5506,6 +5737,11 @@ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" }, + "memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, "merge-descriptors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", @@ -5555,6 +5791,46 @@ "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", "dev": true }, + "mongodb": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.10.0.tgz", + "integrity": "sha512-gP9vduuYWb9ZkDM546M+MP2qKVk5ZG2wPF63OvSRuUbqCR+11ZCAE1mOfllhlAG0wcoJY5yDL/rV3OmYEwXIzg==", + "requires": { + "@mongodb-js/saslprep": "^1.1.5", + "bson": "^6.7.0", + "mongodb-connection-string-url": "^3.0.0" + } + }, + "mongodb-connection-string-url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.1.tgz", + "integrity": "sha512-XqMGwRX0Lgn05TDB4PyG2h2kKO/FfWJyCzYQbIhXUxz7ETt0I/FqHjUeqj37irJ+Dl1ZtU82uYyj14u2XsZKfg==", + "requires": { + "@types/whatwg-url": "^11.0.2", + "whatwg-url": "^13.0.0" + } + }, + "mongoose": { + "version": "8.8.2", + "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.8.2.tgz", + "integrity": "sha512-jCTSqDANfRzk909v4YoZQi7jlGRB2MTvgG+spVBc/BA4tOs1oWJr//V6yYujqNq9UybpOtsSfBqxI0dSOEFJHQ==", + "requires": { + "bson": "^6.7.0", + "kareem": "2.6.3", + "mongodb": "~6.10.0", + "mpath": "0.9.0", + "mquery": "5.0.0", + "ms": "2.1.3", + "sift": "17.1.3" + }, + "dependencies": { + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, "morgan": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz", @@ -5587,11 +5863,23 @@ } } }, + "mpath": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz", + "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==" + }, + "mquery": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-5.0.0.tgz", + "integrity": "sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==", + "requires": { + "debug": "4.x" + } + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "natural-compare": { "version": "1.4.0", @@ -5902,10 +6190,9 @@ } }, "punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==" }, "pupa": { "version": "2.1.1", @@ -6154,6 +6441,11 @@ "object-inspect": "^1.9.0" } }, + "sift": { + "version": "17.1.3", + "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz", + "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==" + }, "signal-exit": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.6.tgz", @@ -6171,6 +6463,14 @@ "is-fullwidth-code-point": "^3.0.0" } }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "requires": { + "memory-pager": "^1.0.2" + } + }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -6311,6 +6611,14 @@ "nopt": "~1.0.10" } }, + "tr46": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-4.1.1.tgz", + "integrity": "sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==", + "requires": { + "punycode": "^2.3.0" + } + }, "tsconfig-paths": { "version": "3.12.0", "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.12.0.tgz", @@ -6449,6 +6757,20 @@ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" }, + "webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==" + }, + "whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-9WWbymnqj57+XEuqADHrCJ2eSXzn8WXIW/YSGaZtb2WKAInQ6CHfaUUcTyyver0p8BDg5StLQq8h1vtZuwmOig==", + "requires": { + "tr46": "^4.1.1", + "webidl-conversions": "^7.0.0" + } + }, "which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index b52f3d043d3..9e936b1bf3c 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "cross-env": "7.0.3", "express": "4.17.1", "joi": "^17.13.3", + "mongoose": "^8.8.2", "morgan": "1.10.0", "uuid": "^11.0.3" }, diff --git a/routes/api/contacts.js b/routes/api/contacts.js index a00eb5c96d5..3a6648216fc 100644 --- a/routes/api/contacts.js +++ b/routes/api/contacts.js @@ -7,6 +7,7 @@ const { addContact, removeContact, updateContact, + updateFavorite, } = require('../../models/contacts'); const router = express.Router(); @@ -18,6 +19,10 @@ const contactSchema = Joi.object({ phone: Joi.string().required(), }); +const favoriteSchema = Joi.object({ + favorite: Joi.boolean().required(), +}); + router.get('/', async (req, res, next) => { try { const contacts = await listContacts(); @@ -83,4 +88,22 @@ router.put('/:contactId', async (req, res, next) => { } }); +// PATCH route for updating favorite status +router.patch('/:contactId/favorite', async (req, res, next) => { + try { + const { contactId } = req.params; + const { error } = favoriteSchema.validate(req.body); + if (error) { + return res.status(400).json({ message: 'missing field favorite' }); + } + const updatedContact = await updateFavorite(contactId, req.body.favorite); + if (!updatedContact) { + return res.status(404).json({ message: 'Not found' }); + } + res.status(200).json(updatedContact); + } catch (error) { + next(error); + } +}); + module.exports = router; diff --git a/testConnection.js b/testConnection.js new file mode 100644 index 00000000000..2ce278536b1 --- /dev/null +++ b/testConnection.js @@ -0,0 +1,12 @@ +const mongoose = require('mongoose'); + +const DB_URI = 'mongodb+srv://sorintene:1234qwer@test-cluster.jnsni.mongodb.net/db-contacts?retryWrites=true&w=majority'; + +mongoose.connect(DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => { + console.log('Database connection successful'); + mongoose.disconnect(); + }) + .catch(error => { + console.error('Database connection error:', error.message); + }); From d501d9147b8c15c47e2938717af73c09dce2ac69 Mon Sep 17 00:00:00 2001 From: LaurentiuSorinTENE Date: Mon, 16 Dec 2024 11:43:31 +0200 Subject: [PATCH 3/3] final Tema 4 --- app.js | 47 +++---- middlewares/auth.js | 27 ++++ models/contacts.js | 35 +----- models/user.js | 17 +++ package-lock.json | 272 +++++++++++++++++++++++++++++++++-------- package.json | 5 +- routes/api/contacts.js | 111 +++++------------ routes/api/users.js | 78 ++++++++++++ server.js | 9 +- testConnection.js | 2 +- verifytoken.js | 11 ++ 11 files changed, 424 insertions(+), 190 deletions(-) create mode 100644 middlewares/auth.js create mode 100644 models/user.js create mode 100644 routes/api/users.js create mode 100644 verifytoken.js diff --git a/app.js b/app.js index 6fba01ffe0f..bf4ac0e9c42 100644 --- a/app.js +++ b/app.js @@ -1,38 +1,25 @@ -const express = require('express') -const logger = require('morgan') -const cors = require('cors') - +const express = require('express'); +const contactsRouter = require('./routes/api/contacts'); +const usersRouter = require('./routes/api/users'); const mongoose = require('mongoose'); +const DB_URI = process.env.DB_URI || 'mongodb+srv://sorintene:1234qwer@test-cluster.jnsni.mongodb.net/db-contacts?retryWrites=true&w=majority'; -// MongoDB connection -const DB_URI = 'mongodb+srv://sorintene:1234qwer@test-cluster.jnsni.mongodb.net/db-contacts?retryWrites=true&w=majority'; - -mongoose.connect(DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) - .then(() => console.log('Database connection successful')) - .catch(error => { - console.error('Database connection error:', error.message); - process.exit(1); - }); - - -const contactsRouter = require('./routes/api/contacts') - -const app = express() +mongoose.connect(DB_URI) +.then(() => console.log('MongoDB connected successfully')) +.catch(err => console.error('MongoDB connection error:', err)); -const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short' -app.use(logger(formatsLogger)) -app.use(cors()) -app.use(express.json()) +const app = express(); -app.use('/api/contacts', contactsRouter) +app.use(express.json()); -app.use((req, res) => { - res.status(404).json({ message: 'Not found' }) -}) +// Register routes +app.use('/api/contacts', contactsRouter); +app.use('/api/users', usersRouter); -app.use((err, req, res, next) => { - res.status(500).json({ message: err.message }) -}) +// Error handling middleware +app.use((req, res, next) => { + res.status(404).send({ message: 'Not Found' }); +}); -module.exports = app +module.exports = app; // Export the app for use in server.js diff --git a/middlewares/auth.js b/middlewares/auth.js new file mode 100644 index 00000000000..fab3ae9c902 --- /dev/null +++ b/middlewares/auth.js @@ -0,0 +1,27 @@ +const jwt = require('jsonwebtoken'); +const User = require('../models/user'); + +const auth = async (req, res, next) => { + const { authorization = '' } = req.headers; + const [bearer, token] = authorization.split(' '); + + if (bearer !== 'Bearer' || !token) { + return res.status(401).json({ message: 'Not authorized' }); + } + + try { + const { id } = jwt.verify(token, process.env.JWT_SECRET); + const user = await User.findById(id); + + if (!user || user.token !== token) { + return res.status(401).json({ message: 'Not authorized' }); + } + + req.user = user; + next(); + } catch { + res.status(401).json({ message: 'Not authorized' }); + } +}; + +module.exports = auth; diff --git a/models/contacts.js b/models/contacts.js index c129d664ea6..6d56a52bb63 100644 --- a/models/contacts.js +++ b/models/contacts.js @@ -1,39 +1,16 @@ const mongoose = require('mongoose'); const contactSchema = new mongoose.Schema({ - name: { - type: String, - required: [true, 'Set name for contact'], - }, + name: String, email: String, phone: String, - favorite: { - type: Boolean, - default: false, + owner: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true, }, }); const Contact = mongoose.model('Contact', contactSchema); -const listContacts = async () => Contact.find(); - -const getContactById = async (contactId) => Contact.findById(contactId); - -const addContact = async (contactData) => Contact.create(contactData); - -const removeContact = async (contactId) => Contact.findByIdAndRemove(contactId); - -const updateContact = async (contactId, updateData) => - Contact.findByIdAndUpdate(contactId, updateData, { new: true }); - -const updateFavorite = async (contactId, favorite) => - Contact.findByIdAndUpdate(contactId, { favorite }, { new: true }); - -module.exports = { - listContacts, - getContactById, - addContact, - removeContact, - updateContact, - updateFavorite, -}; +module.exports = Contact; diff --git a/models/user.js b/models/user.js new file mode 100644 index 00000000000..a78d5ecfd6c --- /dev/null +++ b/models/user.js @@ -0,0 +1,17 @@ +const mongoose = require('mongoose'); +const { Schema } = mongoose; + +const userSchema = new Schema({ + password: { type: String, required: [true, 'Password is required'] }, + email: { type: String, required: [true, 'Email is required'], unique: true }, + subscription: { + type: String, + enum: ['starter', 'pro', 'business'], + default: 'starter', + }, + token: { type: String, default: null }, +}); + +const User = mongoose.model('user', userSchema); + +module.exports = User; diff --git a/package-lock.json b/package-lock.json index 1c7ce3c95a9..0bc1e187925 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,10 +8,13 @@ "name": "template", "version": "0.0.0", "dependencies": { + "bcryptjs": "^2.4.3", "cors": "2.8.5", - "cross-env": "7.0.3", + "cross-env": "^7.0.3", + "dotenv": "^16.4.7", "express": "4.17.1", "joi": "^17.13.3", + "jsonwebtoken": "^9.0.2", "mongoose": "^8.8.2", "morgan": "1.10.0", "uuid": "^11.0.3" @@ -417,6 +420,12 @@ "node": ">= 0.8" } }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==", + "license": "MIT" + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -524,6 +533,12 @@ "node": ">=16.20.1" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", @@ -761,6 +776,7 @@ "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "license": "MIT", "dependencies": { "cross-spawn": "^7.0.1" }, @@ -894,12 +910,33 @@ "node": ">=8" } }, + "node_modules/dotenv": { + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/duplexer3": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", "dev": true }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -2299,6 +2336,49 @@ "json5": "lib/cli.js" } }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/kareem": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", @@ -2361,6 +2441,48 @@ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, "node_modules/lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", @@ -2376,18 +2498,6 @@ "node": ">=0.10.0" } }, - "node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", @@ -3260,13 +3370,10 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "node_modules/semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "license": "ISC", "bin": { "semver": "bin/semver.js" }, @@ -3917,12 +4024,6 @@ "engines": { "node": ">=8" } - }, - "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true } }, "dependencies": { @@ -4233,6 +4334,11 @@ "safe-buffer": "5.1.2" } }, + "bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==" + }, "binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -4319,6 +4425,11 @@ "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.0.tgz", "integrity": "sha512-ROchNosXMJD2cbQGm84KoP7vOGPO6/bOAW0veMMbzhXLqoZptcaYRVLitwvuhwhjjpU1qP4YZRWLhgETdgqUQw==" }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" + }, "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", @@ -4588,12 +4699,25 @@ "is-obj": "^2.0.0" } }, + "dotenv": { + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==" + }, "duplexer3": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", "dev": true }, + "ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -5645,6 +5769,42 @@ "minimist": "^1.2.0" } }, + "jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "requires": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + } + }, + "jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "requires": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "requires": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, "kareem": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.6.3.tgz", @@ -5694,6 +5854,41 @@ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, + "lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" + }, + "lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" + }, "lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", @@ -5706,15 +5901,6 @@ "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", "dev": true }, - "lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "requires": { - "yallist": "^4.0.0" - } - }, "make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", @@ -6334,13 +6520,9 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, - "requires": { - "lru-cache": "^6.0.0" - } + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==" }, "semver-diff": { "version": "3.1.1", @@ -6841,12 +7023,6 @@ "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", "dev": true - }, - "yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true } } } diff --git a/package.json b/package.json index 9e936b1bf3c..997a824a489 100644 --- a/package.json +++ b/package.json @@ -9,10 +9,13 @@ "lint:fix": "eslint --fix **/*.js" }, "dependencies": { + "bcryptjs": "^2.4.3", "cors": "2.8.5", - "cross-env": "7.0.3", + "cross-env": "^7.0.3", + "dotenv": "^16.4.7", "express": "4.17.1", "joi": "^17.13.3", + "jsonwebtoken": "^9.0.2", "mongoose": "^8.8.2", "morgan": "1.10.0", "uuid": "^11.0.3" diff --git a/routes/api/contacts.js b/routes/api/contacts.js index 3a6648216fc..b441c35b004 100644 --- a/routes/api/contacts.js +++ b/routes/api/contacts.js @@ -1,18 +1,10 @@ +const authenticate = require('../../middlewares/auth'); const express = require('express'); const Joi = require('joi'); - -const { - listContacts, - getContactById, - addContact, - removeContact, - updateContact, - updateFavorite, -} = require('../../models/contacts'); - +const Contact = require('../../models/contacts'); const router = express.Router(); -// Validation schema +// Validation schemas const contactSchema = Joi.object({ name: Joi.string().required(), email: Joi.string().email().required(), @@ -23,84 +15,47 @@ const favoriteSchema = Joi.object({ favorite: Joi.boolean().required(), }); -router.get('/', async (req, res, next) => { +// GET All Contacts (Paginated) +router.get('/', authenticate, async (req, res, next) => { try { - const contacts = await listContacts(); - res.status(200).json(contacts); - } catch (error) { - next(error); - } -}); + const { page = 1, limit = 10 } = req.query; + const skip = (page - 1) * limit; -router.get('/:contactId', async (req, res, next) => { - try { - const { contactId } = req.params; - const contact = await getContactById(contactId); - if (!contact) { - return res.status(404).json({ message: 'Not found' }); - } - res.status(200).json(contact); - } catch (error) { - next(error); - } -}); + const contacts = await Contact.find({ owner: req.user._id }) + .skip(skip) + .limit(parseInt(limit, 10)); + const total = await Contact.countDocuments({ owner: req.user._id }); -router.post('/', async (req, res, next) => { - try { - const { error } = contactSchema.validate(req.body); - if (error) { - return res.status(400).json({ message: 'missing required name field' }); - } - const newContact = await addContact(req.body); - res.status(201).json(newContact); + res.status(200).json({ + contacts, + page: parseInt(page, 10), + limit: parseInt(limit, 10), + totalPages: Math.ceil(total / limit), + totalContacts: total, + }); } catch (error) { next(error); } }); -router.delete('/:contactId', async (req, res, next) => { +// POST Create new Contact +router.post('/', authenticate, async (req, res, next) => { try { - const { contactId } = req.params; - const contact = await removeContact(contactId); - if (!contact) { - return res.status(404).json({ message: 'Not found' }); - } - res.status(200).json({ message: 'contact deleted' }); - } catch (error) { - next(error); - } -}); + // Validate request body + const { name, email, phone } = await contactSchema.validateAsync(req.body); -router.put('/:contactId', async (req, res, next) => { - try { - const { contactId } = req.params; - const { error } = contactSchema.validate(req.body); - if (error) { - return res.status(400).json({ message: 'missing fields' }); - } - const updatedContact = await updateContact(contactId, req.body); - if (!updatedContact) { - return res.status(404).json({ message: 'Not found' }); - } - res.status(200).json(updatedContact); - } catch (error) { - next(error); - } -}); + // Create a new contact + const newContact = new Contact({ + name, + email, + phone, + owner: req.user._id, // assuming the user is authenticated and assigned via the 'auth' middleware + }); -// PATCH route for updating favorite status -router.patch('/:contactId/favorite', async (req, res, next) => { - try { - const { contactId } = req.params; - const { error } = favoriteSchema.validate(req.body); - if (error) { - return res.status(400).json({ message: 'missing field favorite' }); - } - const updatedContact = await updateFavorite(contactId, req.body.favorite); - if (!updatedContact) { - return res.status(404).json({ message: 'Not found' }); - } - res.status(200).json(updatedContact); + // Save the new contact to the database + await newContact.save(); + + res.status(201).json(newContact); // Respond with the created contact } catch (error) { next(error); } diff --git a/routes/api/users.js b/routes/api/users.js new file mode 100644 index 00000000000..d8a0f04f74f --- /dev/null +++ b/routes/api/users.js @@ -0,0 +1,78 @@ +const express = require('express'); +const jwt = require('jsonwebtoken'); +const bcrypt = require('bcryptjs'); +const Joi = require('joi'); +const authenticate = require('../../middlewares/auth'); +const User = require('../../models/user'); + +const router = express.Router(); + +// Validation schemas +const userSchema = Joi.object({ + email: Joi.string().email().required(), + password: Joi.string().min(6).required(), +}); + +// Sign up +router.post('/signup', async (req, res) => { + try { + const { email, password } = await userSchema.validateAsync(req.body); + + const existingUser = await User.findOne({ email }); + if (existingUser) { + return res.status(409).json({ message: 'Email in use' }); + } + + const hashedPassword = await bcrypt.hash(password, 10); + const newUser = await User.create({ email, password: hashedPassword }); + + return res.status(201).json({ + user: { email: newUser.email, subscription: newUser.subscription }, + }); + } catch (error) { + return res.status(400).json({ message: error.message }); + } +}); + +// Login +router.post('/login', async (req, res) => { + try { + const { email, password } = await userSchema.validateAsync(req.body); + + const user = await User.findOne({ email }); + if (!user || !(await bcrypt.compare(password, user.password))) { + return res.status(401).json({ message: 'Email or password is wrong' }); + } + + const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' }); + user.token = token; + await user.save(); + + return res.status(200).json({ + token, + user: { email: user.email, subscription: user.subscription }, + }); + } catch (error) { + return res.status(400).json({ message: error.message }); + } +}); + +// Logout +router.get('/logout', authenticate, async (req, res) => { + try { + const user = req.user; + user.token = null; + await user.save(); + res.status(204).send(); + } catch (error) { + res.status(500).json({ message: error.message }); + } +}); + +// Get Current User +router.get('/current', authenticate, (req, res) => { + const { email, subscription } = req.user; + res.status(200).json({ email, subscription }); +}); + +module.exports = router; diff --git a/server.js b/server.js index fc4e4c6bb3a..b98d460bcfa 100644 --- a/server.js +++ b/server.js @@ -1,5 +1,8 @@ -const app = require("./app"); +require('dotenv').config(); +const app = require('./app'); // Import the app from app.js -app.listen(3000, () => { - console.log("Server is running. Use our API on port: 3000"); +const PORT = process.env.PORT || 3000; + +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); }); diff --git a/testConnection.js b/testConnection.js index 2ce278536b1..a0b7600cda3 100644 --- a/testConnection.js +++ b/testConnection.js @@ -2,7 +2,7 @@ const mongoose = require('mongoose'); const DB_URI = 'mongodb+srv://sorintene:1234qwer@test-cluster.jnsni.mongodb.net/db-contacts?retryWrites=true&w=majority'; -mongoose.connect(DB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) +mongoose.connect(DB_URI) .then(() => { console.log('Database connection successful'); mongoose.disconnect(); diff --git a/verifytoken.js b/verifytoken.js new file mode 100644 index 00000000000..c5151a61884 --- /dev/null +++ b/verifytoken.js @@ -0,0 +1,11 @@ +const jwt = require('jsonwebtoken'); + +const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY3NTU0YzBiZDk3ZmQ1Y2VlNjRjNWY4MCIsImlhdCI6MTczMzY0MzUzNywiZXhwIjoxNzMzNjQ3MTM3fQ.-XsjQybMjDHiLMjVl5txmp_deJmlZOznApi_1xvr5uA"; +const secret = "MySuperSecureSecretKey1234567890!"; + +try { + const decoded = jwt.verify(token, secret); + console.log("Token is valid:", decoded); +} catch (error) { + console.error("Token is invalid:", error.message); +}