diff --git a/plugins/file.js b/plugins/file.js new file mode 100644 index 0000000..518a1a4 --- /dev/null +++ b/plugins/file.js @@ -0,0 +1,45 @@ +var fs = require('fs'); + +var FILE = function() {}; + +FILE.prototype.save = function(base64, file_url, callback) { + var base64Data = base64.split(',')[1]; + return fs.writeFile( + file_url, + base64Data, + { + flags: 'wx', + encoding: 'base64' + }, + function(err) { + if (err) { + console.error('writeFile', err); + throw err; + } + + callback(); + } + ); +}; + +FILE.prototype.get = function(path, isVideo) { + var bitmap = fs.readFileSync(path); + + if (!isVideo) { + try { + return new Buffer(bitmap).toString('base64'); + } catch (e) { + throw e; + } + } else { + var binary = ''; + var bytes = new Uint8Array(bitmap); + var len = bytes.byteLength; + for (var i = 0; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return new Buffer(binary).toString('base64'); + } +}; + +module.exports = new FILE(); diff --git a/plugins/googleapi.js b/plugins/googleapi.js new file mode 100644 index 0000000..ce987a6 --- /dev/null +++ b/plugins/googleapi.js @@ -0,0 +1,193 @@ +const fs = require('fs'); +const readline = require('readline'); +const {google} = require('googleapis'); +var FILE = require('./file'); + +var GOOGLEAPI = function() {}; +var auth = null; + +GOOGLEAPI.prototype.init = function() { + // If modifying these scopes, delete token.json. + const SCOPES = [ + 'https://www.googleapis.com/auth/drive', + 'https://www.googleapis.com/auth/drive.file', + 'https://www.googleapis.com/auth/drive.appdata', + 'https://www.googleapis.com/auth/drive.apps.readonly', + 'https://www.googleapis.com/auth/drive.readonly', + 'https://www.googleapis.com/auth/drive.metadata.readonly', + 'https://www.googleapis.com/auth/drive.metadata', + 'https://www.googleapis.com/auth/drive.photos.readonly' + ]; + // The file token.json stores the user's access and refresh tokens, and is + // created automatically when the authorization flow completes for the first + // time. + const TOKEN_PATH = 'token.json'; + + // Load client secrets from a local file. + fs.readFile('credentials.json', (err, content) => { + if (err) return console.log('Error loading client secret file:', err); + // Authorize a client with credentials, then call the Google Drive API. + authorize(JSON.parse(content), listFiles); + }); + + /** + * Create an OAuth2 client with the given credentials, and then execute the + * given callback function. + * @param {Object} credentials The authorization client credentials. + * @param {function} callback The callback to call with the authorized client. + */ + function authorize(credentials, callback) { + const {client_secret, client_id, redirect_uris} = credentials.installed; + const oAuth2Client = new google.auth.OAuth2( + client_id, + client_secret, + redirect_uris[0] + ); + + // Check if we have previously stored a token. + fs.readFile(TOKEN_PATH, (err, token) => { + if (err) return getAccessToken(oAuth2Client, callback); + oAuth2Client.setCredentials(JSON.parse(token)); + callback(oAuth2Client); + }); + } + + /** + * Get and store new token after prompting for user authorization, and then + * execute the given callback with the authorized OAuth2 client. + * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for. + * @param {getEventsCallback} callback The callback for the authorized client. + */ + function getAccessToken(oAuth2Client, callback) { + const authUrl = oAuth2Client.generateAuthUrl({ + access_type: 'offline', + scope: SCOPES + }); + console.log('Authorize this app by visiting this url:', authUrl); + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + rl.question('Enter the code from that page here: ', code => { + rl.close(); + oAuth2Client.getToken(code, (err, token) => { + if (err) return console.error('Error retrieving access token', err); + oAuth2Client.setCredentials(token); + // Store the token to disk for later program executions + fs.writeFile(TOKEN_PATH, JSON.stringify(token), err => { + if (err) console.error(err); + // console.log('Token stored to', TOKEN_PATH); + }); + callback(oAuth2Client); + }); + }); + } + + /** + * Lists the names and IDs of up to 10 files. + * @param {google.auth.OAuth2} auth An authorized OAuth2 client. + */ + function listFiles(a) { + auth = a; + // console.log('auth', auth); + const drive = google.drive({version: 'v3', auth}); + drive.files.list( + { + pageSize: 10, + fields: 'nextPageToken, files(id, name, mimeType, size)' + }, + (err, res) => { + if (err) return console.log('The API returned an error: ' + err); + const files = res.data.files; + if (files.length) { + console.log('Files:'); + files.map(file => { + console.log(`${file.name} (${file.id})`); + }); + } else { + console.log('No files found.'); + } + } + ); + } +}; + +GOOGLEAPI.prototype.listGoogleDrive = function(callback) { + console.log('listGoogleDrive'); + const drive = google.drive({version: 'v3', auth}); + drive.files.list( + { + pageSize: 10, + fields: 'nextPageToken, files(id, name, mimeType, size)' + }, + (err, res) => { + if (err) return console.log('The API returned an error: ' + err); + var files = res.data.files; + // console.log('Files:', files); + files.map(f => { + f.filename = f.name; + return f; + }); + files = files.filter(f => !f.mimeType.includes('vnd.google-apps.document')) + callback(files); + } + ); +}; + +GOOGLEAPI.prototype.uploadGoogleDrive = function( + file_name, + type, + file_url, + callback +) { + const drive = google.drive({version: 'v3', auth}); + var fileMetadata = { + name: file_name + }; + var media = { + mimeType: type, + body: fs.createReadStream(file_url) + }; + console.log('uploadGoogleDrive...'); + drive.files.create( + { + resource: fileMetadata, + media: media, + fields: 'id' + }, + function(err, file) { + if (err) { + // Handle error + console.error('uploadGoogleDrive', err); + } else { + console.log('uploadGoogleDrive => file', file); + callback(file.data.id); + } + } + ); +}; + +GOOGLEAPI.prototype.downloadGoogleDrive = function(file, callback) { + console.log('downloadGoogleDrive => file', file); + let drive = google.drive({version: 'v3', auth}); + let file_url = 'files\\' + file.filename; + var dest = fs.createWriteStream(file_url); + drive.files.get( + {fileId: file.id, alt: 'media'}, + {responseType: 'stream'}, + function(err, res) { + if (err) console.error('drive.files.get', err); + res.data + .on('end', () => { + console.log('Done'); + callback(file_url); + }) + .on('error', err => { + console.log('Error', err); + }) + .pipe(dest); + } + ); +}; + +module.exports = new GOOGLEAPI(); diff --git a/server/middleware/authenticate.js b/server/middleware/authenticate.js index a68a007..c0ab221 100644 --- a/server/middleware/authenticate.js +++ b/server/middleware/authenticate.js @@ -30,4 +30,27 @@ const authenticate = (req, res, next) => { }); }; -module.exports = {authenticate}; +const authenticate_noerror = (req, res, next) => { + const token = req.header('x-auth'); + + const access = 'auth'; + + User.findByToken(token, access).then((user) => { + if (!user) { + req.user = null; + req.token = null; + req.access = null; + }else { + req.user = user; + req.token = token; + req.access = access; + } + next(); + }).catch((e) => { + req.user = null; + req.token = null; + req.access = null; + }); +}; + +module.exports = {authenticate, authenticate_noerror}; diff --git a/server/models/booking.js b/server/models/booking.js index ae8274c..0758bc1 100644 --- a/server/models/booking.js +++ b/server/models/booking.js @@ -42,7 +42,6 @@ const bookingSchema = new Schema({ booked: { type: Boolean, }, - }); bookingSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) { diff --git a/server/models/contribtype.js b/server/models/contribtype.js new file mode 100644 index 0000000..4d71c14 --- /dev/null +++ b/server/models/contribtype.js @@ -0,0 +1,43 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const tools = require('../tools/general'); + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const ContribtypeSchema = new Schema({ + idapp: { + type: String, + }, + label: { + type: String, + }, + showprice: { + type: Boolean, + } +}); + +ContribtypeSchema.statics.executeQueryTable = function (idapp, params) { + return tools.executeQueryTable(this, idapp, params); +}; + +ContribtypeSchema.statics.findAllIdApp = function (idapp) { + const Contribtype = this; + + const myfind = { idapp }; + + return Contribtype.find(myfind, (err, arrrec) => { + return arrrec + }); +}; + +const Contribtype = mongoose.model('Contribtype', ContribtypeSchema); + +module.exports = { Contribtype }; diff --git a/server/models/myevent.js b/server/models/myevent.js index 0cdba28..93eebd6 100644 --- a/server/models/myevent.js +++ b/server/models/myevent.js @@ -50,8 +50,8 @@ const MyEventSchema = new Schema({ wherecode: { type: String, }, - contribtype: { // TABLE - type: Number, + contribtype: { + type: String, }, price: { type: Number, @@ -59,7 +59,7 @@ const MyEventSchema = new Schema({ infoafterprice: { type: String, }, - teacher: { // TABLE ?! + teacher: { type: String, }, teacher2: { diff --git a/server/router/booking_router.js b/server/router/booking_router.js index b6b73c8..972d620 100644 --- a/server/router/booking_router.js +++ b/server/router/booking_router.js @@ -10,6 +10,7 @@ const { Booking } = require('../models/booking'); const { MyEvent } = require('../models/myevent'); const { Operator } = require('../models/operator'); const { Where } = require('../models/where'); +const { Contribtype } = require('../models/contribtype'); const { ObjectID } = require('mongodb'); @@ -97,45 +98,41 @@ router.delete('/:id/:notify/:idapp', authenticate, (req, res) => { }); -router.get('/:userId/:idapp/:sall', authenticate, (req, res) => { - const userId = req.params.userId; - const idapp = req.params.idapp; - const sall = req.params.sall; - // var category = req.params.category; - - // tools.mylog('GET BOOKINGS : ', req.params); - - if (!ObjectID.isValid(userId)) { - return res.status(404).send(); - } - - if (userId !== String(req.user._id)) { - // I'm trying to write something not mine! - return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); - } - - // Extract all the todos of the userId only - Booking.findAllByUserIdAndIdApp(userId, idapp, sall).then((bookedevent) => { - - return MyEvent.findAllIdApp(idapp) - .then((eventlist) => { - return Operator.findAllIdApp(idapp) - .then((operators) => { - - return Where.findAllIdApp(idapp) - .then((wheres) => { - - res.send({ bookedevent, eventlist, operators, wheres }); - }) - }) - }) - - }).catch((e) => { - console.log(e); - res.status(400).send(e); - }); - -}); - +// router.get('/:userId/:idapp/:sall', authenticate, (req, res) => { +// const userId = req.params.userId; +// const idapp = req.params.idapp; +// const sall = req.params.sall; +// // var category = req.params.category; +// +// // tools.mylog('GET BOOKINGS : ', req.params); +// +// if (!ObjectID.isValid(userId)) { +// return res.status(404).send(); +// } +// +// if (userId !== String(req.user._id)) { +// // I'm trying to write something not mine! +// return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); +// } +// +// // Extract all the todos of the userId only +// const bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall); +// const eventlist = MyEvent.findAllIdApp(idapp); +// const operators = Operator.findAllIdApp(idapp); +// const wheres = Where.findAllIdApp(idapp); +// const contribtype = Contribtype.findAllIdApp(idapp); +// +// return Promise.all([bookedevent, eventlist, operators, wheres, contribtype]) +// .then((arrdata) => { +// console.table(arrdata); +// res.send({ bookedevent: arrdata[0], eventlist: arrdata[1], operators: arrdata[2], wheres: arrdata[3], contribtype: arrdata[4] }); +// }) +// .catch((e) => { +// console.log(e); +// res.status(400).send(e); +// }); +// +// }); +// module.exports = router; diff --git a/server/router/index_router.js b/server/router/index_router.js index d50c7fd..c015abd 100644 --- a/server/router/index_router.js +++ b/server/router/index_router.js @@ -1,7 +1,7 @@ const express = require('express'); const router = express.Router(); -const { authenticate } = require('../middleware/authenticate'); +const { authenticate, authenticate_noerror } = require('../middleware/authenticate'); const { ObjectID } = require('mongodb'); @@ -15,6 +15,7 @@ const { Booking } = require('../models/booking'); const { Operator } = require('../models/operator'); const { Where } = require('../models/where'); const { MyEvent } = require('../models/myevent'); +const { Contribtype } = require('../models/contribtype'); const tools = require('../tools/general'); @@ -59,9 +60,9 @@ router.post(process.env.LINKVERIF_REG, (req, res) => { // Faccio richiesta di una Nuova Password router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => { - var body = _.pick(req.body, ['idapp', 'email']); - var idapp = body.idapp; - var email = body.email; + const body = _.pick(req.body, ['idapp', 'email']); + const idapp = body.idapp; + const email = body.email; console.log("POST " + process.env.LINK_REQUEST_NEWPASSWORD + " idapp= " + idapp + " email = " + email); User.findByEmail(idapp, email).then((user) => { @@ -84,6 +85,7 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => { }); + router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => { const userId = req.user._id; @@ -167,6 +169,8 @@ function getTableByTableName(tablename) { mytable = Where; else if (tablename === 'myevents') mytable = MyEvent; + else if (tablename === 'contribtype') + mytable = Contribtype; return mytable } @@ -325,5 +329,38 @@ function doOtherThingsAfterDeleted() { } +router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) => { + const userId = req.params.userId; + const idapp = req.params.idapp; + const sall = req.params.sall; + // var category = req.params.category; + + tools.mylog('loadsite : ', req.params); + + let bookedevent = []; + + if (userId !== '0') { + // LOGGED WITH USERID + bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall); + } + + // Extract all the todos of the userId only + const eventlist = MyEvent.findAllIdApp(idapp); + const operators = Operator.findAllIdApp(idapp); + const wheres = Where.findAllIdApp(idapp); + const contribtype = Contribtype.findAllIdApp(idapp); + + return Promise.all([bookedevent, eventlist, operators, wheres, contribtype]) + .then((arrdata) => { + console.table(arrdata); + res.send({ bookedevent: arrdata[0], eventlist: arrdata[1], operators: arrdata[2], wheres: arrdata[3], contribtype: arrdata[4] }); + }) + .catch((e) => { + console.log(e); + res.status(400).send(e); + }); + +}); + module.exports = router;