From 28097e9a39e55e0d5d47f9e40a0689cf1699059a Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Wed, 21 Sep 2022 22:16:42 +0530 Subject: [PATCH 1/8] remove unused imports in services --- src/services/initializeUpload.service.js | 1 - src/services/metadata.service.js | 9 -- src/services/uploadToEstuary.service.js | 118 +++++++++++++++++------ 3 files changed, 89 insertions(+), 39 deletions(-) diff --git a/src/services/initializeUpload.service.js b/src/services/initializeUpload.service.js index 4253d62..7bc8423 100644 --- a/src/services/initializeUpload.service.js +++ b/src/services/initializeUpload.service.js @@ -1,4 +1,3 @@ -const express = require("express"); const { msgCache } = require("../init"); /** diff --git a/src/services/metadata.service.js b/src/services/metadata.service.js index 79a6841..7e89c58 100644 --- a/src/services/metadata.service.js +++ b/src/services/metadata.service.js @@ -1,17 +1,8 @@ -const express = require("express"); -const axios = require("axios"); -const fse = require("fs-extra"); const mongodb = require("mongodb"); -const web3 = require("web3"); -const { ethers } = require("ethers"); -const { packToFs } = require("ipfs-car/pack/fs"); -const { FsBlockStore } = require("ipfs-car/blockstore/fs"); -const { unpackToFs } = require("ipfs-car/unpack/fs"); const sanitizeHtml = require("sanitize-html"); const dbWrapper = require("../utils/dbWrapper"); const estuaryWrapper = require("../utils/estuaryWrapper"); const utils = require("../utils/utils"); -const { fetchJson } = require("ethers/lib/utils"); /** * Get dataset metadata for every dataset belonging to the specified address. diff --git a/src/services/uploadToEstuary.service.js b/src/services/uploadToEstuary.service.js index f5710dc..3ea1b3f 100644 --- a/src/services/uploadToEstuary.service.js +++ b/src/services/uploadToEstuary.service.js @@ -1,8 +1,5 @@ -const express = require("express"); -const axios = require("axios"); const fs = require("fs"); const fse = require("fs-extra"); -const FormData = require("form-data"); const web3 = require("web3"); const { ethers } = require("ethers"); const mongodb = require("mongodb"); @@ -46,12 +43,20 @@ const runInitialInputValidation = async (req) => { if (!req.body.address || !req.files || !req.body.signature) { console.log("Missing argument"); await utils.removeFiles(req.files[0].destination); - return { error: "Missing argument. Please provide address files and signature." }; + return { + error: "Missing argument. Please provide address files and signature.", + }; } - if (req.body.address.length != 42 || req.body.address.substring(0, 2) != "0x") { + if ( + req.body.address.length != 42 || + req.body.address.substring(0, 2) != "0x" + ) { console.log("Invalid address"); await utils.removeFiles(req.files[0].destination); - return { error: "Invalid address. Address must be 42 characters long and start with 0x." }; + return { + error: + "Invalid address. Address must be 42 characters long and start with 0x.", + }; } const address = req.body.address.toLowerCase(); const secretMessage = msgCache.take(address); @@ -61,11 +66,15 @@ const runInitialInputValidation = async (req) => { return { error: `No secret message for ${address} at time ${Date.now()}` }; } const msgHash = web3.utils.sha3(secretMessage); - const signer = (await ethers.utils.recoverAddress(msgHash, req.body.signature)).toLowerCase(); + const signer = ( + await ethers.utils.recoverAddress(msgHash, req.body.signature) + ).toLowerCase(); if (signer != address) { console.log(`signer != address\nsigner: ${signer}\naddress: ${address}`); await utils.removeFiles(req.files[0].destination); - return { error: `No secret message for ${address} in cache. Sign secret message before uploading.` }; + return { + error: `No secret message for ${address} in cache. Sign secret message before uploading.`, + }; } return { success: "Initial input validation succeeded." }; @@ -79,7 +88,10 @@ const moveFilesToCorrectFolders = async (req) => { for (const file of req.files) { if (typeof req.body[file.originalname] != "string") { // Check if these files are in .git folder. If so, ignore and continue. - if (Array.isArray(req.body[file.originalname]) && req.body[file.originalname].length > 0) { + if ( + Array.isArray(req.body[file.originalname]) && + req.body[file.originalname].length > 0 + ) { if (req.body[file.originalname][0].includes("/.git/")) { continue; } @@ -195,7 +207,10 @@ const generateChunk = (params) => { datasetId: params.datasetId, path: params.path || "/", doi: params.doi || "", - storageIds: { cid: params.storageIds?.cid || "", estuaryId: params.storageIds?.estuaryId || null }, + storageIds: { + cid: params.storageIds?.cid || "", + estuaryId: params.storageIds?.estuaryId || null, + }, fileIds: params.fileIds || [], size: params.size, }; @@ -225,7 +240,9 @@ const insertMetadata = async (datasetMetadata, chunkMetadata, files) => { if (acknowledged) break; } if (!acknowledged) { - console.log(`${new Date().toISOString()} Request to insert dataset metadata was not acknowledged by database. Exiting.`); + console.log( + `${new Date().toISOString()} Request to insert dataset metadata was not acknowledged by database. Exiting.` + ); return false; } @@ -240,11 +257,16 @@ const insertMetadata = async (datasetMetadata, chunkMetadata, files) => { if (acknowledged) break; } if (!acknowledged) { - console.log(`${new Date().toISOString()} Request to insert chunk metadata was not acknowledged by database. Exiting.`); + console.log( + `${new Date().toISOString()} Request to insert chunk metadata was not acknowledged by database. Exiting.` + ); await dbWrapper.deleteDataset({ _id: dataset._id }); return false; } - await dbWrapper.updateDataset({ _id: dataset._id }, { $set: { chunkIds: [chunk._id] } }); + await dbWrapper.updateDataset( + { _id: dataset._id }, + { $set: { chunkIds: [chunk._id] } } + ); // commonsFiles const fileIds = []; @@ -256,7 +278,9 @@ const insertMetadata = async (datasetMetadata, chunkMetadata, files) => { if (acknowledged) break; } if (!acknowledged) { - console.log(`${new Date().toISOString()} Request to insert commonsFile metadata was not acknowledged by database. Exiting.`); + console.log( + `${new Date().toISOString()} Request to insert commonsFile metadata was not acknowledged by database. Exiting.` + ); await dbWrapper.deleteDataset({ _id: dataset._id }); await dbWrapper.deleteChunk({ _id: chunk._id }); await dbWrapper.deleteCommonsFiles({ _id: { $in: fileIds } }); @@ -266,12 +290,17 @@ const insertMetadata = async (datasetMetadata, chunkMetadata, files) => { } const queryFilter = { _id: chunk._id }; const updateDocument = { $set: { fileIds: fileIds } }; - const updateSuccess = await dbWrapper.updateChunk(queryFilter, updateDocument); + const updateSuccess = await dbWrapper.updateChunk( + queryFilter, + updateDocument + ); if (!updateSuccess) { await dbWrapper.deleteDataset({ _id: dataset._id }); await dbWrapper.deleteChunk({ _id: chunk._id }); await dbWrapper.deleteCommonsFiles({ _id: { $in: fileIds } }); - console.log(`${new Date().toISOString()} Failed to set chunk.files in database. Exiting.`); + console.log( + `${new Date().toISOString()} Failed to set chunk.files in database. Exiting.` + ); } return updateSuccess; }; @@ -282,7 +311,11 @@ const uploadFiles = async (req, res) => { console.log(`${new Date().toISOString()} uploadFile: Entered`); const initValidation = await runInitialInputValidation(req); if (initValidation.error) { - return res.status(400).json({ error: `Failed initial input validation. Problem: ${initValidation.error}` }); + return res + .status(400) + .json({ + error: `Failed initial input validation. Problem: ${initValidation.error}`, + }); } // console.log(req.files); @@ -291,7 +324,8 @@ const uploadFiles = async (req, res) => { const files = await moveFilesToCorrectFolders(req); if (files.length == 0) { - const message = "Files could not be organized into their proper directories."; + const message = + "Files could not be organized into their proper directories."; console.log(`${new Date().toISOString()} uploadFiles: ${message}`); await utils.removeFiles(req.files[0].destination); return res.status(400).json({ error: message }); @@ -300,7 +334,8 @@ const uploadFiles = async (req, res) => { const timestampedFolder = req.files[0].destination; const dirChildren = fs.readdirSync(timestampedFolder); if (dirChildren.length != 1) { - const message = "Files could not be organized into their proper directories."; + const message = + "Files could not be organized into their proper directories."; console.log(`${new Date().toISOString()} uploadFiles: ${message}`); await utils.removeFiles(req.files[0].destination); return res.status(400).json({ error: message }); @@ -323,24 +358,39 @@ const uploadFiles = async (req, res) => { }); // Upload file - console.log(`${new Date().toISOString()} Uploading ${carFilename} to Estuary`); + console.log( + `${new Date().toISOString()} Uploading ${carFilename} to Estuary` + ); const file = fs.createReadStream(carFilename); const uploadResp = await estuaryWrapper.uploadFile(file, 3); // const uploadResp = { cid: "0x124", estuaryId: "81" }; // THIS LINE IS FOR TESTING ONLY await utils.removeFiles(timestampedFolder); if (!uploadResp) { - console.log(`${new Date().toISOString()} Failed to upload ${carFilename} to Estuary`); - return res.status(400).json({ error: "An error occurred trying to upload to Estuary. Try again later." }); + console.log( + `${new Date().toISOString()} Failed to upload ${carFilename} to Estuary` + ); + return res + .status(400) + .json({ + error: + "An error occurred trying to upload to Estuary. Try again later.", + }); } const newUploadCid = uploadResp.cid; const newUploadEstuaryId = uploadResp.estuaryId; // Delete this file from Estuary and exit if the user has already uploaded a file with this CID - const matchingChunkDocuments = await dbWrapper.getChunks({ "storageIds.cid": newUploadCid }); + const matchingChunkDocuments = await dbWrapper.getChunks({ + "storageIds.cid": newUploadCid, + }); if (matchingChunkDocuments.length > 0) { - console.log(`${new Date().toISOString()} User has already uploaded this file. Removing the duplicate file from Estuary and exiting.`); + console.log( + `${new Date().toISOString()} User has already uploaded this file. Removing the duplicate file from Estuary and exiting.` + ); await estuaryWrapper.deleteFile(newUploadEstuaryId); - return res.status(400).json({ error: "This dataset has already been uploaded." }); + return res + .status(400) + .json({ error: "This dataset has already been uploaded." }); } const sumFileSizes = files.map((file) => file.size).reduce((a, b) => a + b); @@ -362,13 +412,23 @@ const uploadFiles = async (req, res) => { storageIds: { cid: newUploadCid, estuaryId: parseInt(newUploadEstuaryId) }, size: sumFileSizes, }; - const insertSuccess = await insertMetadata(datasetMetadata, chunkMetadata, files); + const insertSuccess = await insertMetadata( + datasetMetadata, + chunkMetadata, + files + ); if (!insertSuccess) { - console.log(`${new Date().toISOString()} Failed to insert metadata into database. Removing file from Estuary and exiting.`); + console.log( + `${new Date().toISOString()} Failed to insert metadata into database. Removing file from Estuary and exiting.` + ); await estuaryWrapper.deleteFile(newUploadEstuaryId); - return res.status(400).json({ error: "Failed to insert metadata into database." }); + return res + .status(400) + .json({ error: "Failed to insert metadata into database." }); } else { - console.log(`${new Date().toISOString()} Successfully uploaded files for ${address}`); + console.log( + `${new Date().toISOString()} Successfully uploaded files for ${address}` + ); } return res.status(201).json({ message: `Successfully uploaded dataset for address ${address}.`, From eaef055b59aaef7a45c856203017919132e13152 Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Tue, 27 Sep 2022 16:59:54 +0530 Subject: [PATCH 2/8] create auth routes --- .env-example | 2 + package-lock.json | 226 +++++++++++++++++++++++++++++++++ package.json | 3 + src/index.js | 5 + src/utils/metadataValidator.js | 1 + 5 files changed, 237 insertions(+) diff --git a/.env-example b/.env-example index 1a071f1..fabea75 100644 --- a/.env-example +++ b/.env-example @@ -1,2 +1,4 @@ ESTUARY_API_KEY=api_key MONGO_DB_URL=some/url +ORCID_CLIENT_ID= orcid api client id +ORCID_CLIENT_SECRET= orcid api client secret \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 24115fa..48e54f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "dotenv": "^16.0.0", "ethers": "^5.6.5", "express": "^4.17.1", + "express-session": "^1.17.3", "form-data": "^4.0.0", "fs-extra": "^10.1.0", "helmet": "^4.2.0", @@ -23,6 +24,8 @@ "mongodb": "^4.7.0", "multer": "^1.4.4", "node-cache": "^5.1.2", + "passport": "^0.6.0", + "passport-orcid": "^0.0.4", "sanitize-html": "^2.7.1", "web3": "^1.7.4", "yup": "^0.32.11" @@ -2435,6 +2438,14 @@ } ] }, + "node_modules/base64url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/base64url/-/base64url-3.0.1.tgz", + "integrity": "sha512-ir1UPr3dkwexU7FdV8qBBbNDRUhMmIekYMFZfi+C/sLNnRESKPl23nB9b2pltqfOQNnGzsDdId90AEtG5tCx4A==", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -4006,6 +4017,32 @@ "node": ">= 0.10.0" } }, + "node_modules/express-session": { + "version": "1.17.3", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.17.3.tgz", + "integrity": "sha512-4+otWXlShYlG1Ma+2Jnn+xgKUZTMJ5QD3YvfilX3AcocOAbIkVylSWEklzALe/+Pu4qV6TYBj5GwOBFfdKqLBw==", + "dependencies": { + "cookie": "0.4.2", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.0.2", + "parseurl": "~1.3.3", + "safe-buffer": "5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/express-session/node_modules/cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/ext": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/ext/-/ext-1.6.0.tgz", @@ -6359,6 +6396,11 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.6.tgz", "integrity": "sha512-XWwnNNFCuuSQ0m3r3C4LE3EiORltHd9M05pq6FOlVeiophzRbMo50Sbz1ehl8K3Z+jw9+vmgnXefY1hz8X+2wA==" }, + "node_modules/oauth": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", + "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==" + }, "node_modules/oauth-sign": { "version": "0.9.0", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", @@ -6427,6 +6469,14 @@ "node": ">= 0.8" } }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -6586,6 +6636,58 @@ "node": ">= 0.8" } }, + "node_modules/passport": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/passport/-/passport-0.6.0.tgz", + "integrity": "sha512-0fe+p3ZnrWRW74fe8+SvCyf4a3Pb2/h7gFkQ8yTJpAO50gDzlfjZUZTO1k5Eg9kUct22OxHLqDZoKUWRHOh9ug==", + "dependencies": { + "passport-strategy": "1.x.x", + "pause": "0.0.1", + "utils-merge": "^1.0.1" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-oauth2": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/passport-oauth2/-/passport-oauth2-1.6.1.tgz", + "integrity": "sha512-ZbV43Hq9d/SBSYQ22GOiglFsjsD1YY/qdiptA+8ej+9C1dL1TVB+mBE5kDH/D4AJo50+2i8f4bx0vg4/yDDZCQ==", + "dependencies": { + "base64url": "3.x.x", + "oauth": "0.9.x", + "passport-strategy": "1.x.x", + "uid2": "0.0.x", + "utils-merge": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-orcid": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/passport-orcid/-/passport-orcid-0.0.4.tgz", + "integrity": "sha512-swqn1PIQpzAz0qHXwlBlBaRFkfYXsXJ9o33T11QykCuuxR/UppbHGPgBOnrZaIf/Mytq6uYn8s5C4lAahaMYxQ==", + "dependencies": { + "passport-oauth2": "^1.5.0" + } + }, + "node_modules/passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha512-CB97UUvDKJde2V0KDWWB3lyf6PC3FaZP7YxZ2G8OAtn9p4HI9j9JLP9qjOGZFvyl8uwNT8qM+hGnz/n16NI7oA==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/path": { "version": "0.12.7", "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", @@ -6642,6 +6744,11 @@ "node": "*" } }, + "node_modules/pause": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", + "integrity": "sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==" + }, "node_modules/pbkdf2": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", @@ -6881,6 +6988,14 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -8111,6 +8226,22 @@ "is-typedarray": "^1.0.0" } }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uid2": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.4.tgz", + "integrity": "sha512-IevTus0SbGwQzYh3+fRsAMTVVPOoIVufzacXcHPmdlle1jUpq7BRL+mw3dgeLanvGZdwwbWhRV6XrcFNdBmjWA==" + }, "node_modules/uint8arrays": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/uint8arrays/-/uint8arrays-3.0.0.tgz", @@ -10772,6 +10903,11 @@ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" }, + "base64url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/base64url/-/base64url-3.0.1.tgz", + "integrity": "sha512-ir1UPr3dkwexU7FdV8qBBbNDRUhMmIekYMFZfi+C/sLNnRESKPl23nB9b2pltqfOQNnGzsDdId90AEtG5tCx4A==" + }, "bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -12102,6 +12238,28 @@ "vary": "~1.1.2" } }, + "express-session": { + "version": "1.17.3", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.17.3.tgz", + "integrity": "sha512-4+otWXlShYlG1Ma+2Jnn+xgKUZTMJ5QD3YvfilX3AcocOAbIkVylSWEklzALe/+Pu4qV6TYBj5GwOBFfdKqLBw==", + "requires": { + "cookie": "0.4.2", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.0.2", + "parseurl": "~1.3.3", + "safe-buffer": "5.2.1", + "uid-safe": "~2.1.5" + }, + "dependencies": { + "cookie": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", + "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==" + } + } + }, "ext": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/ext/-/ext-1.6.0.tgz", @@ -13952,6 +14110,11 @@ } } }, + "oauth": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", + "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==" + }, "oauth-sign": { "version": "0.9.0", "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", @@ -13999,6 +14162,11 @@ "ee-first": "1.1.1" } }, + "on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==" + }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -14122,6 +14290,41 @@ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" }, + "passport": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/passport/-/passport-0.6.0.tgz", + "integrity": "sha512-0fe+p3ZnrWRW74fe8+SvCyf4a3Pb2/h7gFkQ8yTJpAO50gDzlfjZUZTO1k5Eg9kUct22OxHLqDZoKUWRHOh9ug==", + "requires": { + "passport-strategy": "1.x.x", + "pause": "0.0.1", + "utils-merge": "^1.0.1" + } + }, + "passport-oauth2": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/passport-oauth2/-/passport-oauth2-1.6.1.tgz", + "integrity": "sha512-ZbV43Hq9d/SBSYQ22GOiglFsjsD1YY/qdiptA+8ej+9C1dL1TVB+mBE5kDH/D4AJo50+2i8f4bx0vg4/yDDZCQ==", + "requires": { + "base64url": "3.x.x", + "oauth": "0.9.x", + "passport-strategy": "1.x.x", + "uid2": "0.0.x", + "utils-merge": "1.x.x" + } + }, + "passport-orcid": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/passport-orcid/-/passport-orcid-0.0.4.tgz", + "integrity": "sha512-swqn1PIQpzAz0qHXwlBlBaRFkfYXsXJ9o33T11QykCuuxR/UppbHGPgBOnrZaIf/Mytq6uYn8s5C4lAahaMYxQ==", + "requires": { + "passport-oauth2": "^1.5.0" + } + }, + "passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha512-CB97UUvDKJde2V0KDWWB3lyf6PC3FaZP7YxZ2G8OAtn9p4HI9j9JLP9qjOGZFvyl8uwNT8qM+hGnz/n16NI7oA==" + }, "path": { "version": "0.12.7", "resolved": "https://registry.npmjs.org/path/-/path-0.12.7.tgz", @@ -14171,6 +14374,11 @@ "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==" }, + "pause": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", + "integrity": "sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==" + }, "pbkdf2": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", @@ -14355,6 +14563,11 @@ } } }, + "random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==" + }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -15318,6 +15531,19 @@ "is-typedarray": "^1.0.0" } }, + "uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "requires": { + "random-bytes": "~1.0.0" + } + }, + "uid2": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.4.tgz", + "integrity": "sha512-IevTus0SbGwQzYh3+fRsAMTVVPOoIVufzacXcHPmdlle1jUpq7BRL+mw3dgeLanvGZdwwbWhRV6XrcFNdBmjWA==" + }, "uint8arrays": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/uint8arrays/-/uint8arrays-3.0.0.tgz", diff --git a/package.json b/package.json index ccb3523..09f6466 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dotenv": "^16.0.0", "ethers": "^5.6.5", "express": "^4.17.1", + "express-session": "^1.17.3", "form-data": "^4.0.0", "fs-extra": "^10.1.0", "helmet": "^4.2.0", @@ -18,6 +19,8 @@ "mongodb": "^4.7.0", "multer": "^1.4.4", "node-cache": "^5.1.2", + "passport": "^0.6.0", + "passport-orcid": "^0.0.4", "sanitize-html": "^2.7.1", "web3": "^1.7.4", "yup": "^0.32.11" diff --git a/src/index.js b/src/index.js index ab346a1..e28d97e 100644 --- a/src/index.js +++ b/src/index.js @@ -1,9 +1,12 @@ const express = require("express"); const cors = require("cors"); +const passportSetup = require("./utils/passport-setup"); const metadata = require("./routes/metadata"); const uploadToEstuary = require("./routes/uploadToEstuary"); const initializeUpload = require("./routes/initializeUpload"); +const orcidOauth = require("./routes/orcid-oauth"); +const req = require("express/lib/request"); const app = express(); @@ -16,8 +19,10 @@ app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cors(corsOptions)); + app.use("/metadata", metadata); app.use("/uploadToEstuary", uploadToEstuary); app.use("/initializeUpload", initializeUpload); +app.use("/auth", orcidOauth); module.exports = app; diff --git a/src/utils/metadataValidator.js b/src/utils/metadataValidator.js index 03cb24a..a46ea1e 100644 --- a/src/utils/metadataValidator.js +++ b/src/utils/metadataValidator.js @@ -11,6 +11,7 @@ const bidsValidationSchema = yup.object().shape({ warnings: yup.array().of(yup.string()), errors: yup.array().of(yup.string()), }); + const datasetSchema = yup.object().shape({ title: yup.string(), description: yup.string(), From 87c8467dec7aac88348aab191e303e69a4b81123 Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Tue, 27 Sep 2022 17:00:13 +0530 Subject: [PATCH 3/8] add auth files --- src/routes/orcid-oauth.js | 15 +++++++++ src/services/orcidAuth.service.js | 52 +++++++++++++++++++++++++++++++ src/utils/db-auth-handler.js | 42 +++++++++++++++++++++++++ src/utils/passport-setup.js | 33 ++++++++++++++++++++ 4 files changed, 142 insertions(+) create mode 100644 src/routes/orcid-oauth.js create mode 100644 src/services/orcidAuth.service.js create mode 100644 src/utils/db-auth-handler.js create mode 100644 src/utils/passport-setup.js diff --git a/src/routes/orcid-oauth.js b/src/routes/orcid-oauth.js new file mode 100644 index 0000000..b9fb299 --- /dev/null +++ b/src/routes/orcid-oauth.js @@ -0,0 +1,15 @@ +const router = require("express").Router(); +const orcidAuthService = require("../services/orcidAuth.service"); +//auth login screen +router.get("/login", orcidAuthService.onLogin); + +// auth logout +router.get("/logout", orcidAuthService.onLogout); + +//auth with orcid +router.get("/orcid", orcidAuthService.onAuthClick); + +// handle oauth redirect +router.get("/orcid/redirect", orcidAuthService.onAuthRedirect); + +module.exports = router; diff --git a/src/services/orcidAuth.service.js b/src/services/orcidAuth.service.js new file mode 100644 index 0000000..852da4b --- /dev/null +++ b/src/services/orcidAuth.service.js @@ -0,0 +1,52 @@ +const passport = require("passport"); + +//auth login screen +router.get("/login"); + +const onLogin = async (req, res) => { + // handle with passport + const message = ` User Login Sucessfull`; + return res.status(200).json({ message: message }); +}; + +const onLogout = async (req, res) => { + //handle with passport + res.send("logging out"); +}; + +//auth with orcid +const onAuthClick = async (req, res) => { + try { + passport.authenticate("orcid", { + scope: ["/authenticate"], + }); + const message = `Passport Authentication Triggered`; + return res.status(200).json({ message: message }); + } catch (error) { + console.error(error); + } + const message = `Passport Authentication Failed`; + return res.status(500).json({ error: message }); +}; + +// handle oauth redirect +const onAuthRedirect = async (req, res) => { + try { + passport.authenticate("orcid", () => { + console.log(" Hiii user, You've reached callback redirect"); + }); + const message = `Passport Authentication Redirect Triggered`; + return res.status(200).json({ message: message }); + } catch (error) { + console.error(error); + } + const message = `Passport Authentication Redirect Failed`; + return res.status(500).json({ error: message }); +}; + +module.exports = { + onLogin, + onLogout, + onAuthClick, + onAuthRedirect, +}; diff --git a/src/utils/db-auth-handler.js b/src/utils/db-auth-handler.js new file mode 100644 index 0000000..e173fc9 --- /dev/null +++ b/src/utils/db-auth-handler.js @@ -0,0 +1,42 @@ +const { mongoClient, msgCache } = require("../init"); +const mongoDbName = "admin"; +const UserCollectionName = "users"; + +/** + * @param user The user Object to be stored in the database + * @param collectionName The name of the MongoDB collection to insert the item into + * @returns True if the insertion request was acknowledged, false otherwise + */ +const createUser = async (user) => { + let acknowledged = false; + try { + const db = mongoClient.db(mongoDbName); + const collection = db.collection(UserCollectionName); + const result = await collection.insertOne(user); + if (result.acknowledged) acknowledged = true; + } catch (err) { + console.log(err); + } + return acknowledged; +}; + +/** + * @param query The query document to use for the MongoDB query + * @param collectionName The name of the MongoDB collection to retrieve items from + */ +const getUser = async (query) => { + let users; + try { + const db = mongoClient.db(mongoDbName); + const collection = db.collection(UserCollectionName); + users = await collection.find(query).toArray(); + } catch (err) { + console.log(err); + } + return users; +}; + +module.exports = { + getUser, + createUser, +}; diff --git a/src/utils/passport-setup.js b/src/utils/passport-setup.js new file mode 100644 index 0000000..aa2da42 --- /dev/null +++ b/src/utils/passport-setup.js @@ -0,0 +1,33 @@ +const passport = require("passport"); +const OrcidStrategy = require("passport-orcid").Strategy; +const orcidKeys = require("./keys"); +const { createUser, getUser } = require("./db-auth-handler"); +passport.use( + new OrcidStrategy( + { + sandbox: true, // remove this to use the production API + state: false, // remove this if not using sessions + clientID: process.env.ORCID_CLIENT_ID, + clientSecret: process.env.ORCID_CLIENT_SECRET, + callbackURL: "/auth/orcid/redirect", + }, + (accessToken, refreshToken, params, profile, done) => { + // `profile` is empty as ORCID has no generic profile URL, + // so populate the profile object from the params instead + profile = { orcid: params.orcid, name: params.name }; + + getUser({ orcid: profile.orcid }).then((currentUser) => { + if (currentUser) { + // User already exists, log their info + console.log("User is:" + currentUser); + } else { + createUser(profile).then((newUser) => { + console.log("New User Created:" + newUser); + }); + } + }); + + // return done(null, profile); + } + ) +); From b1d5cfea9321e4df101eecde5debf6a5baee6353 Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Tue, 27 Sep 2022 17:05:46 +0530 Subject: [PATCH 4/8] add comment --- src/routes/orcid-oauth.js | 2 +- src/services/orcidAuth.service.js | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/routes/orcid-oauth.js b/src/routes/orcid-oauth.js index b9fb299..c1b60de 100644 --- a/src/routes/orcid-oauth.js +++ b/src/routes/orcid-oauth.js @@ -1,6 +1,6 @@ const router = require("express").Router(); const orcidAuthService = require("../services/orcidAuth.service"); -//auth login screen +// show auth login screen in frontend, if unnecessary remove this route router.get("/login", orcidAuthService.onLogin); // auth logout diff --git a/src/services/orcidAuth.service.js b/src/services/orcidAuth.service.js index 852da4b..fd0630b 100644 --- a/src/services/orcidAuth.service.js +++ b/src/services/orcidAuth.service.js @@ -1,11 +1,9 @@ const passport = require("passport"); -//auth login screen -router.get("/login"); - +// show auth login screen in frontend, if unnecessary remove this route const onLogin = async (req, res) => { - // handle with passport - const message = ` User Login Sucessfull`; + // render login screen + const message = `Display Login Screen`; return res.status(200).json({ message: message }); }; From 80410e6c6dc0c6a20794ddac2a6db39fb49afeae Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Tue, 27 Sep 2022 18:29:08 +0530 Subject: [PATCH 5/8] serialize and deserialize with cookies --- .env-example | 3 +- package-lock.json | 107 ++++++++++++++++++++++++++++++ package.json | 1 + src/index.js | 10 ++- src/services/orcidAuth.service.js | 2 +- src/utils/db-auth-handler.js | 6 +- src/utils/passport-setup.js | 25 +++++-- 7 files changed, 143 insertions(+), 11 deletions(-) diff --git a/.env-example b/.env-example index fabea75..70c98e0 100644 --- a/.env-example +++ b/.env-example @@ -1,4 +1,5 @@ ESTUARY_API_KEY=api_key MONGO_DB_URL=some/url ORCID_CLIENT_ID= orcid api client id -ORCID_CLIENT_SECRET= orcid api client secret \ No newline at end of file +ORCID_CLIENT_SECRET= orcid api client secret +COOKIE_SECRET = secret salt \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 48e54f9..db8d447 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "axios": "^0.27.2", "bids-validator": "^1.9.3", "chai": "^4.3.6", + "cookie-session": "^2.0.0", "cors": "^2.8.5", "dotenv": "^16.0.0", "ethers": "^5.6.5", @@ -3170,6 +3171,33 @@ "node": ">= 0.6" } }, + "node_modules/cookie-session": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/cookie-session/-/cookie-session-2.0.0.tgz", + "integrity": "sha512-hKvgoThbw00zQOleSlUr2qpvuNweoqBtxrmx0UFosx6AGi9lYtLoA+RbsvknrEX8Pr6MDbdWAb2j6SnMn+lPsg==", + "dependencies": { + "cookies": "0.8.0", + "debug": "3.2.7", + "on-headers": "~1.0.2", + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cookie-session/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/cookie-session/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==" + }, "node_modules/cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", @@ -3180,6 +3208,18 @@ "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.3.tgz", "integrity": "sha512-JxbCBUdrfr6AQjOXrxoTvAMJO4HBTUIlBzslcJPAz+/KT8yk53fXun51u+RenNYvad/+Vc2DIz5o9UxlCDymFQ==" }, + "node_modules/cookies": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.8.0.tgz", + "integrity": "sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -5622,6 +5662,17 @@ "node": ">=10.0.0" } }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/keyv": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", @@ -8161,6 +8212,14 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "engines": { + "node": ">=0.6.x" + } + }, "node_modules/tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", @@ -11524,6 +11583,32 @@ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==" }, + "cookie-session": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/cookie-session/-/cookie-session-2.0.0.tgz", + "integrity": "sha512-hKvgoThbw00zQOleSlUr2qpvuNweoqBtxrmx0UFosx6AGi9lYtLoA+RbsvknrEX8Pr6MDbdWAb2j6SnMn+lPsg==", + "requires": { + "cookies": "0.8.0", + "debug": "3.2.7", + "on-headers": "~1.0.2", + "safe-buffer": "5.2.1" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, "cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", @@ -11534,6 +11619,15 @@ "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.3.tgz", "integrity": "sha512-JxbCBUdrfr6AQjOXrxoTvAMJO4HBTUIlBzslcJPAz+/KT8yk53fXun51u+RenNYvad/+Vc2DIz5o9UxlCDymFQ==" }, + "cookies": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.8.0.tgz", + "integrity": "sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==", + "requires": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + } + }, "core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -13491,6 +13585,14 @@ "readable-stream": "^3.6.0" } }, + "keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "requires": { + "tsscmp": "1.0.6" + } + }, "keyv": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", @@ -15481,6 +15583,11 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" }, + "tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==" + }, "tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", diff --git a/package.json b/package.json index 09f6466..ca7c50e 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "axios": "^0.27.2", "bids-validator": "^1.9.3", "chai": "^4.3.6", + "cookie-session": "^2.0.0", "cors": "^2.8.5", "dotenv": "^16.0.0", "ethers": "^5.6.5", diff --git a/src/index.js b/src/index.js index e28d97e..695fc6f 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,7 @@ const express = require("express"); const cors = require("cors"); const passportSetup = require("./utils/passport-setup"); - +const cookiesSession = require("cookie-session"); const metadata = require("./routes/metadata"); const uploadToEstuary = require("./routes/uploadToEstuary"); const initializeUpload = require("./routes/initializeUpload"); @@ -19,6 +19,14 @@ app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cors(corsOptions)); +app.use(cookiesSession( + { + maxAge: 24 * 60 * 60 * 1000, + keys: [process.env.COOKIE_SECRET] + } +)); +app.use(passport.initialize()) +app.use(passport.session()) app.use("/metadata", metadata); app.use("/uploadToEstuary", uploadToEstuary); diff --git a/src/services/orcidAuth.service.js b/src/services/orcidAuth.service.js index fd0630b..c98fe90 100644 --- a/src/services/orcidAuth.service.js +++ b/src/services/orcidAuth.service.js @@ -34,7 +34,7 @@ const onAuthRedirect = async (req, res) => { console.log(" Hiii user, You've reached callback redirect"); }); const message = `Passport Authentication Redirect Triggered`; - return res.status(200).json({ message: message }); + return res.status(200).json(req.user); } catch (error) { console.error(error); } diff --git a/src/utils/db-auth-handler.js b/src/utils/db-auth-handler.js index e173fc9..fead796 100644 --- a/src/utils/db-auth-handler.js +++ b/src/utils/db-auth-handler.js @@ -25,15 +25,15 @@ const createUser = async (user) => { * @param collectionName The name of the MongoDB collection to retrieve items from */ const getUser = async (query) => { - let users; + let user; try { const db = mongoClient.db(mongoDbName); const collection = db.collection(UserCollectionName); - users = await collection.find(query).toArray(); + user = await collection.find(query).toString(); } catch (err) { console.log(err); } - return users; + return user; }; module.exports = { diff --git a/src/utils/passport-setup.js b/src/utils/passport-setup.js index aa2da42..6661457 100644 --- a/src/utils/passport-setup.js +++ b/src/utils/passport-setup.js @@ -1,7 +1,22 @@ const passport = require("passport"); const OrcidStrategy = require("passport-orcid").Strategy; const orcidKeys = require("./keys"); -const { createUser, getUser } = require("./db-auth-handler"); +const dbAuthHandler = require("./db-auth-handler"); +const mongodb = require("mongodb"); + +passport.serializeUser(function (user, done) { + done(null, user.id) + }); + +passport.deserializeUser(function (id, done) { + const query = { _id: mongodb.ObjectId(req.query.userId)}; + await dbAuthHandler.getUser(query).then((user) => { + done(null, user.id) + } + ); + }) + + passport.use( new OrcidStrategy( { @@ -16,18 +31,18 @@ passport.use( // so populate the profile object from the params instead profile = { orcid: params.orcid, name: params.name }; - getUser({ orcid: profile.orcid }).then((currentUser) => { + await dbAuthHandler.getUser({ orcid: profile.orcid }).then((currentUser) => { if (currentUser) { // User already exists, log their info console.log("User is:" + currentUser); + done(null, currentUser); } else { - createUser(profile).then((newUser) => { + await dbAuthHandler.createUser(profile).then((newUser) => { console.log("New User Created:" + newUser); + done(null, newUser); }); } }); - - // return done(null, profile); } ) ); From a03892638788c887696e77b1ddf7aaef8910e254 Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Wed, 28 Sep 2022 15:46:33 +0530 Subject: [PATCH 6/8] add profile routes --- src/index.js | 3 +++ src/services/orcidAuth.service.js | 9 +++++---- src/utils/passport-setup.js | 1 - 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index 695fc6f..d072250 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,7 @@ const metadata = require("./routes/metadata"); const uploadToEstuary = require("./routes/uploadToEstuary"); const initializeUpload = require("./routes/initializeUpload"); const orcidOauth = require("./routes/orcid-oauth"); +const profileRoutes = require('./routes/userProfile'); const req = require("express/lib/request"); const app = express(); @@ -32,5 +33,7 @@ app.use("/metadata", metadata); app.use("/uploadToEstuary", uploadToEstuary); app.use("/initializeUpload", initializeUpload); app.use("/auth", orcidOauth); +app.use("/profile", profileRoutes); + module.exports = app; diff --git a/src/services/orcidAuth.service.js b/src/services/orcidAuth.service.js index c98fe90..3c366bf 100644 --- a/src/services/orcidAuth.service.js +++ b/src/services/orcidAuth.service.js @@ -4,12 +4,12 @@ const passport = require("passport"); const onLogin = async (req, res) => { // render login screen const message = `Display Login Screen`; - return res.status(200).json({ message: message }); + return res.status(200).json({ user: req.user, message: message }); }; const onLogout = async (req, res) => { - //handle with passport - res.send("logging out"); + req.logout(); + return res.redirect('/'); }; //auth with orcid @@ -34,7 +34,8 @@ const onAuthRedirect = async (req, res) => { console.log(" Hiii user, You've reached callback redirect"); }); const message = `Passport Authentication Redirect Triggered`; - return res.status(200).json(req.user); + //return res.status(200).json(req.user); + return res.redirect('/profile'); } catch (error) { console.error(error); } diff --git a/src/utils/passport-setup.js b/src/utils/passport-setup.js index 6661457..4030de1 100644 --- a/src/utils/passport-setup.js +++ b/src/utils/passport-setup.js @@ -1,6 +1,5 @@ const passport = require("passport"); const OrcidStrategy = require("passport-orcid").Strategy; -const orcidKeys = require("./keys"); const dbAuthHandler = require("./db-auth-handler"); const mongodb = require("mongodb"); From ee90cca67ceec46fe11d79f97180c251bb32afef Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Wed, 28 Sep 2022 15:54:05 +0530 Subject: [PATCH 7/8] add profileRoute files --- src/index.js | 1 + src/routes/userProfile.js | 6 ++++++ src/services/userProile.service.js | 17 +++++++++++++++++ src/utils/passport-setup.js | 6 +++--- 4 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 src/routes/userProfile.js create mode 100644 src/services/userProile.service.js diff --git a/src/index.js b/src/index.js index d072250..251a025 100644 --- a/src/index.js +++ b/src/index.js @@ -8,6 +8,7 @@ const initializeUpload = require("./routes/initializeUpload"); const orcidOauth = require("./routes/orcid-oauth"); const profileRoutes = require('./routes/userProfile'); const req = require("express/lib/request"); +const passport = require("passport"); const app = express(); diff --git a/src/routes/userProfile.js b/src/routes/userProfile.js new file mode 100644 index 0000000..c67e765 --- /dev/null +++ b/src/routes/userProfile.js @@ -0,0 +1,6 @@ +const router = require("express").Router(); +const { authCheck, onProfilePage } = require("../services/userProile.service"); + +router.get("/", authCheck, onProfilePage); + +module.exports = router; diff --git a/src/services/userProile.service.js b/src/services/userProile.service.js new file mode 100644 index 0000000..e7ad1d8 --- /dev/null +++ b/src/services/userProile.service.js @@ -0,0 +1,17 @@ +const authCheck = (req, res, next) => { + if(!req.user){ + res.redirect('/auth/login'); + } else { + next(); + } +}; + +const onProfilePage = (req, res) => { + // should render a user profile page on frontend + res.send('you are logged in, this is your profile - ' + req.user.name); +}; + +module.exports = { + authCheck, + onProfilePage +}; \ No newline at end of file diff --git a/src/utils/passport-setup.js b/src/utils/passport-setup.js index 4030de1..a0129c4 100644 --- a/src/utils/passport-setup.js +++ b/src/utils/passport-setup.js @@ -9,7 +9,7 @@ passport.serializeUser(function (user, done) { passport.deserializeUser(function (id, done) { const query = { _id: mongodb.ObjectId(req.query.userId)}; - await dbAuthHandler.getUser(query).then((user) => { + dbAuthHandler.getUser(query).then((user) => { done(null, user.id) } ); @@ -30,13 +30,13 @@ passport.use( // so populate the profile object from the params instead profile = { orcid: params.orcid, name: params.name }; - await dbAuthHandler.getUser({ orcid: profile.orcid }).then((currentUser) => { + dbAuthHandler.getUser({ orcid: profile.orcid }).then((currentUser) => { if (currentUser) { // User already exists, log their info console.log("User is:" + currentUser); done(null, currentUser); } else { - await dbAuthHandler.createUser(profile).then((newUser) => { + dbAuthHandler.createUser(profile).then((newUser) => { console.log("New User Created:" + newUser); done(null, newUser); }); From fdb20ef89e23e31d6d860c2bf9096fbfc46ef43a Mon Sep 17 00:00:00 2001 From: Rashmi V Abbigeri Date: Mon, 17 Oct 2022 14:29:04 +0530 Subject: [PATCH 8/8] progress --- src/utils/passport-setup.js | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/src/utils/passport-setup.js b/src/utils/passport-setup.js index a0129c4..33f45f3 100644 --- a/src/utils/passport-setup.js +++ b/src/utils/passport-setup.js @@ -17,31 +17,5 @@ passport.deserializeUser(function (id, done) { passport.use( - new OrcidStrategy( - { - sandbox: true, // remove this to use the production API - state: false, // remove this if not using sessions - clientID: process.env.ORCID_CLIENT_ID, - clientSecret: process.env.ORCID_CLIENT_SECRET, - callbackURL: "/auth/orcid/redirect", - }, - (accessToken, refreshToken, params, profile, done) => { - // `profile` is empty as ORCID has no generic profile URL, - // so populate the profile object from the params instead - profile = { orcid: params.orcid, name: params.name }; - - dbAuthHandler.getUser({ orcid: profile.orcid }).then((currentUser) => { - if (currentUser) { - // User already exists, log their info - console.log("User is:" + currentUser); - done(null, currentUser); - } else { - dbAuthHandler.createUser(profile).then((newUser) => { - console.log("New User Created:" + newUser); - done(null, newUser); - }); - } - }); - } - ) + );