diff --git a/.gitignore b/.gitignore index 30bc162..b1bee9a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -/node_modules \ No newline at end of file +/node_modules + +.env diff --git a/controllers/common.js b/controllers/common.js index 6736850..9e7829a 100644 --- a/controllers/common.js +++ b/controllers/common.js @@ -3,7 +3,6 @@ const email = require('../models/insertdata'); const userType = require('../server/auth/usertype'); const price = (price) => { - console.log('price', price); if (price < 0 || isNaN(price)) return 422; return price = Math.trunc(price); diff --git a/controllers/company.js b/controllers/company.js index 3d59e4f..4078355 100755 --- a/controllers/company.js +++ b/controllers/company.js @@ -5,6 +5,7 @@ const Settings = require('../models/insertdata'); const check = require('./common.js'); const tip = require('../models/tip'); const transaction = require('../models/transactions'); +const history = require('../models/history'); const addCompany = async (ctx) => { const res = await Settings.addCompany(ctx.request.body); //ctx.request.body @@ -60,9 +61,9 @@ const editItem = async (ctx) => { } const getItems = async (ctx) => { - console.log('in controller getting items'); const userEmail = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); + console.log('======LOGGER\n', userEmail, 'is retrieving the list of items', '\n======'); if (isAdmin) { ctx.status = 201; @@ -78,14 +79,14 @@ const getItems = async (ctx) => { const getCompanyPage = async (ctx) => { const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); - if (isAdmin) { - console.log('is admin', email); + console.log('======LOGGER\n', email, 'requested company page\n admin status:', isAdmin,'\n======'); + if (isAdmin === 'not found') { + return ctx.status = 403; + } else if (isAdmin) { const data = await Settings.getCompanyPage(email); data ? ctx.response.body = data : ctx.status = 404; } else if (!isAdmin) { - console.log('not admin', email); const data = await Settings.getUserPage(email); - console.log('data',data); data ? ctx.response.body = data : ctx.status = 404; } } @@ -111,7 +112,6 @@ const updateSettings = async (ctx) => { const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); if (isAdmin) { const data = await Settings.editSettings(ctx.request.body); - console.log('data', data); data ? ctx.status = 200 : ctx.status = 418; } @@ -121,27 +121,47 @@ const listUsers = async (ctx) => { const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); if (isAdmin) { - console.log('admin'); + console.log('ADMIN'); const data = await tip.listUsersForAdmin(email, isAdmin); data ? ctx.body = data : ctx.status = 404; } else if (!isAdmin) { - console.log('not admin'); + console.log('NOT ADMIN'); const data = await tip.listUsersForUser(email, isAdmin); data ? ctx.body = data : ctx.status = 404; - } else { - ctx.status = 403 } } const getAdminTransactions = async (ctx) => { - console.log('TRANSACTIO NCONTROLLER'); const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); if (isAdmin) { - const data = await transaction.getAdminTransactions(); - console.log('a very long list', data); + ctx.body = await history.getHistory(email, isAdmin); + ctx.status = 200; + } else if (!isAdmin) { + const fullHistory = await history.getUserHistory(email); + const filteredHistory = userHistory(fullHistory); + const transactionsInfo = { + recentTransactions: filteredHistory, + userToUserCompTotal: companyTotal(fullHistory.history, 'UserToUser'), + userSpentCompTotal: companyTotal(fullHistory.history, 'UserSpent'), + }; + ctx.body = transactionsInfo; + ctx.status = 200; } - return data +} + +const companyTotal = (filteredHistory, type) => { + return filteredHistory.filter (transaction => { + return transaction.type == type; + }).reduce ((acc, transaction) => { + return Number(acc) + Number(transaction.amount); + }, 0); +} + +const userHistory = (fullHistory) => { + return fullHistory.history.filter ((transaction) => { + return transaction.from.id == fullHistory.user.id || transaction.to.id == fullHistory.user.id; + }); } module.exports = { diff --git a/controllers/user.js b/controllers/user.js index bb11755..5fbceb2 100644 --- a/controllers/user.js +++ b/controllers/user.js @@ -4,10 +4,9 @@ const adminPrivilege = require('../server/auth/usertype'); const catalog = require('../models/catalog'); const add = async (ctx) => { - console.log('controller, adding a user...'); + console.log('======LOGGER, adding a user...'); const companyEmail = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); - console.log('isAdmin?', isAdmin, companyEmail); if (isAdmin) { const res = await setUser.addUser(companyEmail, ctx.request.body) return (res) ? ctx.status = 200 : ctx.status = 409; @@ -21,7 +20,7 @@ const buyItem = async (ctx) => { const userEmail = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7)); if (!isAdmin) { - console.log('a user is buying...'); + console.log('======LOGGER a user is buying...'); const res = await catalog.buy(userEmail, urlId, ctx.request.body); (res) ? ctx.status = 201 : ctx.body = 'ops... something went wrong'; } else { @@ -48,7 +47,6 @@ const edit = async (ctx) => { const signup = async (ctx) => { const userId = ctx.request.query; const data = await setUser.signup(ctx.request.body, userId); // to be replaced with ctx.request.body - console.log('data', data); if (!data) { ctx.status = 401; } else { diff --git a/controllers/wallet.js b/controllers/wallet.js index 076824e..eaa3859 100644 --- a/controllers/wallet.js +++ b/controllers/wallet.js @@ -8,20 +8,14 @@ async function addFunds (ctx) { data ? ctx.status = 200 : ctx.body = 'Operation failed'; } -// async function transferFunds (ctx) { -// const data = await Transaction.transferFunds(ctx.request.body.senderID, ctx.request.body.receiverID, ctx.request.body.amount); -// data ? ctx.status = 200 : ctx.body = 'Transaction failed'; -// } - async function tipUser (ctx) { const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7)); - const data = await tip.tipUser(ctx.request.body.id, ctx.request.body.amount, ctx.request.body.reason, email) data ? ctx.status = 200 : ctx.body = 'Transaction failed'; + } module.exports = { addFunds, -// transferFunds, tipUser } diff --git a/models/aws.js b/models/aws.js new file mode 100644 index 0000000..2a82e33 --- /dev/null +++ b/models/aws.js @@ -0,0 +1,47 @@ +// const uuid = require('uuid/v4'); +const AWS = require('aws-sdk'); +require('dotenv').config() + +sendToAWS = async (profilePicBase64, filename) => { + ////// file names and id + // var fileName = Object.keys(ctx.request.body.fields)[0]; + var albumPhotosKey = 'zendama/'; + var photoKey = albumPhotosKey + filename; + + ///////// amazon webservices + const albumBucketName = process.env.AWS_FOLDER; + const bucketRegion = process.env.AWS_BUCKET_REGION; + const IdentityPoolId = process.env.AWS_IDENT_POOL_ID; + + await AWS.config.update({ + region: bucketRegion, + credentials: new AWS.CognitoIdentityCredentials({ + IdentityPoolId: IdentityPoolId + }) + }); + + var s3 = new AWS.S3({ + apiVersion: '2006-03-01', + params: {Bucket: albumBucketName} + }); + + //////// stack exchange answer + buf = new Buffer(profilePicBase64.replace(/^data:image\/\w+;base64,/, ""),'base64') + var data = { + Bucket: process.env.AWS_BUCKET, + Key: photoKey, + Body: buf, + ContentEncoding: 'base64', + ContentType: 'image/jpeg', + ACL: 'public-read', + }; + let loc; + return new Promise((resolve, reject) => { + s3.upload(data, (err, data) => { + if (err) reject(err); + resolve(data.Location); + }); + }) +} + +module.exports = sendToAWS; diff --git a/models/catalog.js b/models/catalog.js index fd8a15b..da77c8a 100644 --- a/models/catalog.js +++ b/models/catalog.js @@ -4,14 +4,14 @@ const Company = mongoose.model('Companies', Schemas.AdminSchema); const User = mongoose.model('Users', Schemas.UserSchema); const Catalog = mongoose.model('Catalog', Schemas.CatalogSchema); const Domo = require('../zendomo.js'); - +const history = require('./history'); const add = async (product, companyEmail, isService) => { - console.log('add item', product, companyEmail, isService); let company = new Company(); //I need to check if I really need this company = await Company.find({email: companyEmail}); let newProduct = new Catalog(); newProduct = product; + newProduct.picture = await sendToAWS(product.picture,product.name); newProduct.isService = isService; if (!newProduct.isService) { newProduct.schedule = null; @@ -20,13 +20,18 @@ const add = async (product, companyEmail, isService) => { await company[0].save(); } -const buy = async (userEmail, idItem, infoProduct) => { //Need to be tested - console.log('USER BUYING', userEmail, idItem, infoProduct); +const buy = async (userEmail, idItem, infoProduct) => { const user = await User.find({email: userEmail}); - console.log('user', user); await Domo.purchase(user[0]._id, infoProduct.price); - //Need to send an email to the admin - //now store arguments + const receiverInfo = await Company.find({email: user[0].company}) + const senderInfo = await User.find({email: userEmail}); + const receiver = receiverInfo[0]; + const sender = senderInfo[0]; + const financialReceiver = await Domo.getOneUser(receiver._id); + const financialSender = await Domo.getOneUser(sender._id); + const response = history.history(receiver, sender, infoProduct.price, 'UserSpent', infoProduct.name, user[0].company, financialSender, financialReceiver); + const addTransaction = await history.saveHistory(response, sender.company); + console.log('======LOGGER \n product bought', addTransaction, '\n======'); } const del = async (companyEmail, companyId) => { diff --git a/models/history.js b/models/history.js new file mode 100644 index 0000000..051f262 --- /dev/null +++ b/models/history.js @@ -0,0 +1,73 @@ +const mongoose = require('mongoose'); +const bcrypt = require('bcrypt'); +const Schemas = require('./schemas'); +const Company = mongoose.model('Companies', Schemas.AdminSchema); +const User = mongoose.model('Users', Schemas.UserSchema); +const Domo = require('../zendomo.js'); +const mailer = require('../server/mailer/mailer'); +const Token = mongoose.model('Tokens', Schemas.TokenSchema); + +const history = (receiver, sender, amount, transactionType, reason, companyEmail, financialSender, financialReceiver) => { + return { + from: { + id: sender._id, + username: sender.username, + profilePic: sender.profilePic || sender.logo, + }, + to: { + id: receiver._id, + username: receiver.username, + profilePic: receiver.profilePic || receiver.logo, + }, + amount: amount, + type: transactionType, + reason: reason, + fromBalanceTokens: financialSender.tokens, + fromBalanceCredits: financialSender.credits, + toBalanceTokens: financialReceiver.tokens, + toBalanceCredits: financialReceiver.credits, + _id: financialSender.tradeId + ':' + financialReceiver.tradeId, //transaction id + date: Date.now(), + company: companyEmail, + } +} + +const saveHistory = async (history, companyEmail) => { + const company = await Company.find({email: companyEmail}); + company[0].history.push(history); + await company[0].save(); + return true; +} + +const getHistory = async (email, isAdmin) => { + if (isAdmin) { + const company = await Company.find({email:email}); + return { + adminDetails: {username: 'bla', profilePic: null}, + transactions: company[0].history, + } + } else if (!isAdmin) { + const user = await User.find({email:email}); + return { + adminDetails: {username: 'bla', profilePic: null}, + transactions: user[0].history, + } + } else { + ctx.status = 403; + } +} + +const getUserHistory = async (email) => { + const user = await User.find({email:email}); + const companyEmail = user[0].company; + const companyInfo = await Company.find({email: companyEmail}); + const companyHistory = companyInfo[0].history; +return {history: companyHistory, user:user[0]}; +} + +module.exports = { + history, + saveHistory, + getHistory, + getUserHistory, +} diff --git a/models/insertdata.js b/models/insertdata.js index 33e16f0..92ecf36 100755 --- a/models/insertdata.js +++ b/models/insertdata.js @@ -6,6 +6,7 @@ const User = mongoose.model('Users', Schemas.UserSchema); const Domo = require('../zendomo.js'); const mailer = require('../server/mailer/mailer'); const Token = mongoose.model('Tokens', Schemas.TokenSchema); +const sendToAWS = require('./aws.js') async function addCompany (newCompanyInfo) { console.log('creating new company...'); @@ -16,9 +17,10 @@ async function addCompany (newCompanyInfo) { const hash = bcrypt.hashSync(newCompanyInfo.password, 10); newCompany.isAdmin = true; newCompany.password = hash; + newCompany.logo = await sendToAWS(newCompanyInfo.logo, newCompany.name); await newCompany.save(); const newToken = new Token(); - console.log('newCompany', newCompany.email); + console.log('======LOGGER new company created:', newCompany.email); newToken.email = newCompany.email; newToken.isAdmin = true; await newToken.save(); @@ -31,6 +33,7 @@ async function addCompany (newCompanyInfo) { } async function addUser (companyEmail, userInfo) { + console.log('======LOGGER\n', companyEmail, 'added a new user', '\n======'); try { const user = await User.find({email: userInfo.email}); //I check if the user exists in the user collection @@ -87,10 +90,8 @@ const delUser = async (companyEmail, userId) => { //need to be tested yet } async function signup (user, urlId) { - console.log('user', user); let oldUserInfo = await User.findOne({email: user.email}); if (!oldUserInfo) return null; - console.log('who is undefined? ', oldUserInfo, urlId); if (oldUserInfo['_id'].toString() !== urlId['user-id'].toString()) { return false; } @@ -102,7 +103,7 @@ async function signup (user, urlId) { newProfile.firstName = user.firstName; newProfile.username = user.username; newProfile.password = bcrypt.hashSync(user.password, 10); - newProfile.profilePic = user.profilePic; + newProfile.profilePic = await sendToAWS(user.profilePic, user.username); newProfile.hashkey = null; newProfile.isAdmin = false; newProfile.lastName = user.lastName; @@ -114,27 +115,23 @@ async function signup (user, urlId) { //I want to add the id of the user in the company db only after we are //sure that the user has successfully signed up //I look for the company where we want the user to be added and I push his id - console.log('new profile', newProfile); - const company = await Company.findOne({email: oldUserInfo.company}, 'usersId'); //newUser.company - console.log('company found', company); - console.log('saving this id', newProfile._id); + const company = await Company.findOne({email: oldUserInfo.company}); //newUser.company + console.log('COMPANY CONST CREATED', company); company.usersId.push(newProfile._id); const updatedCompany = new Company(company); + console.log('UPDATED COMPANY, this is gonna be saved', updatedCompany); await updatedCompany.save(); const newToken = new Token(); newToken.email = user.email; newToken.isAdmin = false; - console.log('new token created', newToken); await newToken.save(); return true; } const getCompanyPage = async (companyEmail) => { - console.log('getting company page...', companyEmail); try { const companyInfo = await Company.find({email: companyEmail}); const userIdList = companyInfo[0].usersId; - console.log('list of users', userIdList); const financialInfo = await Domo.getAllUsers(); const userList = userIdList.filter(id => (companyInfo[0].usersId.indexOf(id) !== -1)) const totalTokens = financialInfo.reduce((acc, user) => { @@ -163,7 +160,6 @@ const getCompanyPage = async (companyEmail) => { const getUserPage = async (userEmail) => { try { const userInfo = await User.find({email: userEmail}); - console.log('userinfo', userInfo); const financialInfo = await Domo.getOneUser(userInfo[0]._id); const panelUserInfo = { username: userInfo[0].username, diff --git a/models/schemas.js b/models/schemas.js index 299dcaf..37603f9 100644 --- a/models/schemas.js +++ b/models/schemas.js @@ -45,16 +45,7 @@ const AdminSchema = mongoose.Schema({ createdOn: Number, //timestamp ??????????????????? what address: String, color: {}, - history: - [ - { - from: {}, - to: {}, - amount: Number, - transactionType: String, - date: Date, - } - ] + history: [ ] }); const TokenSchema = mongoose.Schema({ diff --git a/models/tip.js b/models/tip.js index e764a19..da5afe4 100644 --- a/models/tip.js +++ b/models/tip.js @@ -4,7 +4,7 @@ const Company = mongoose.model('Companies', Schemas.AdminSchema); const User = mongoose.model('Users', Schemas.UserSchema); const Domo = require('../zendomo.js'); const Transaction = require('../models/transactions'); - +const history = require('./history'); const listUsersForUser = async (companyEmail, isAdmin) => { var user = await User.find({email: companyEmail}); @@ -34,7 +34,6 @@ const listUsersForAdmin = async (companyEmail, isAdmin) => { company = await Company.find({email: companyEmail}); for (let i = 0; i < company[0].usersId.length; i++) { const user = await User.find({_id: company[0].usersId[i]}); - console.log('====== USER INFO', user, '=========='); if (!user[0]) return {users: []}; const userInfo = { img: user[0].profilePic, @@ -49,33 +48,41 @@ const listUsersForAdmin = async (companyEmail, isAdmin) => { const tipUser = async (idReceiver, amount, reason, emailSender) => { const company = await Company.find({email: emailSender}); let user = new User(); - console.log('COMPANY', company); if (!company.length) { //not an admin user = await User.find({email: emailSender}) - await Transaction.tipUser(idReceiver, amount); - const idSender = await sender(emailSender); - console.log('ID USER', idSender, 'amount', amount); - const data = await Domo.donation(idSender, amount); - console.log('DATA', data); - if (!user.length) console.error('good luck'); + await Transaction.tipUser(idReceiver, amount, user[0]._id); + const senderInfo = await User.find({email: emailSender}); + console.log('========= HERE'); + const data = await Domo.donation(senderInfo[0]._id, amount); + console.log('DATA=======', data); + if (!user.length) console.log('good luck'); + const receiverInfo = await User.find({_id: idReceiver}) + const receiver = receiverInfo[0]; + const sender = senderInfo[0]; + const financialReceiver = await Domo.getOneUser(receiver._id); + console.log('FINANCIAL RECEIVER', financialReceiver, 'RECEIVER', receiver._id); + const financialSender = await Domo.getOneUser(sender._id); + console.log('======LOGGER\n', financialSender.firstName, ' has just tipped', financialReceiver.firstName, amount, 'zen'); + const response = history.history(receiver, sender, amount, 'UserToUser', reason, senderInfo[0].company, financialSender, financialReceiver); + const addTransaction = await history.saveHistory(response, senderInfo[0].company) } else if (company.length) { await Transaction.tipUser(idReceiver, amount); + // can be refactored, same code repeated + const receiverInfo = await User.find({_id: idReceiver}) + const senderInfo = await Company.find({email: emailSender}); + const receiver = receiverInfo[0]; + const sender = senderInfo[0]; + const financialReceiver = await Domo.getOneUser(receiver._id); + const financialSender = await Domo.getOneUser(sender._id); + const response = history.history(receiver, sender, amount, 'AdminExpense', reason, senderInfo[0].company, financialSender, financialReceiver); + const addTransaction = await history.saveHistory(response, senderInfo[0].email) + // } else { ctx.status = 404; } } -const sender = async (emailSender) => { - const company = await Company.find({email: emailSender}); - let user = new User(); - if (!company.length) { - user = await User.find({email: emailSender}); - } - console.log('USER', user); - return user[0]._id; -} - module.exports = { listUsersForAdmin, listUsersForUser, diff --git a/models/transactions.js b/models/transactions.js index b1b796f..a5297d6 100644 --- a/models/transactions.js +++ b/models/transactions.js @@ -3,28 +3,6 @@ const Domo = require('../zendomo.js'); const Schemas = require('./schemas'); const Company = mongoose.model('Companies', Schemas.AdminSchema); -const history = (receiver, sender, amount, transactionType, reason) => { - return { - from: { - id: sender._id, - username: sender.username, - profilePic: sender.profilePic || sender.logo, - }, //id - to: { - id: receiver._id, - username: receiver.username, - profilePic: receiver.profilePic || receiver.logo, - }, //id - amount: amount, - type: transactionType, - reason: reason, - fromBalance: null, - toBalance: null, - _id: null, //transaction id - date: Date.now() - } -} - async function addFunds (id, ammount, companyEmail) { const companyInfo = Company.find({email: companyEmail}); const userInfo = User.find({_id: id}); @@ -40,21 +18,21 @@ async function addFunds (id, ammount, companyEmail) { } } -async function transferFunds (senderID, receiverID, ammount) { - try { - await Domo.transferFunds(senderID, receiverID, parseInt(ammount)); - // - const sender = retrieveInfo(senderID); - console.log('===========sender', sender); - const receiver = retrieveInfo(receiverID); - console.log('=============receiver', receiver); - - // - return true; - } catch (e) { - throw e; - } -} +// async function transferFunds (senderID, receiverID, ammount) { +// try { +// await Domo.transferFunds(senderID, receiverID, parseInt(ammount)); +// // +// const sender = retrieveInfo(senderID); +// console.log('===========sender', sender); +// const receiver = retrieveInfo(receiverID); +// console.log('=============receiver', receiver); +// +// // +// return true; +// } catch (e) { +// throw e; +// } +// } const retrieveInfo = async (id) => { let company = new Company(); @@ -67,11 +45,12 @@ const retrieveInfo = async (id) => { return company[0]; } -async function tipUser (id, ammount) { - console.log('id', id, 'amount', ammount); +async function tipUser (receiverId, ammount, senderId) { try { - console.log('ADDING FUNDS', ammount); - await Domo.tipUser(id, parseInt(ammount)); + await Domo.tipUser(receiverId, parseInt(ammount)); + const sender = retrieveInfo(senderId); + const receiver = retrieveInfo(receiverId); + console.log('======LOGGER\n', 'someone is tipping someone\n', '======') return true; } catch (e) { throw e; @@ -82,9 +61,10 @@ const getAdminTransactions = async () => { return await Domo.getAllUsers(); } +//IMA FIX DIS SHIT! + module.exports = { addFunds, - transferFunds, tipUser, getAdminTransactions } diff --git a/package-lock.json b/package-lock.json index 85d290c..46e5dae 100755 --- a/package-lock.json +++ b/package-lock.json @@ -86,6 +86,23 @@ "resolved": "https://registry.npmjs.org/atob/-/atob-2.0.3.tgz", "integrity": "sha1-GcenYEc3dEaPILLS0DNyrX1Mv10=" }, + "aws-sdk": { + "version": "2.164.0", + "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.164.0.tgz", + "integrity": "sha1-45iGV7fH6W58pan/UskLlrSyKdk=", + "requires": { + "buffer": "4.9.1", + "crypto-browserify": "1.0.9", + "events": "1.1.1", + "jmespath": "0.15.0", + "querystring": "0.2.0", + "sax": "1.2.1", + "url": "0.10.3", + "uuid": "3.1.0", + "xml2js": "0.4.17", + "xmlbuilder": "4.2.1" + } + }, "aws-sign2": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", @@ -101,6 +118,11 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, + "base64-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.2.1.tgz", + "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==" + }, "base64url": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz", @@ -166,6 +188,23 @@ "resolved": "https://registry.npmjs.org/bson/-/bson-1.0.4.tgz", "integrity": "sha1-k8ENOeqltYQVy8QFLz5T5WKwtyw=" }, + "buffer": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", + "requires": { + "base64-js": "1.2.1", + "ieee754": "1.1.8", + "isarray": "1.0.0" + }, + "dependencies": { + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + } + } + }, "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", @@ -289,6 +328,11 @@ } } }, + "crypto-browserify": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-1.0.9.tgz", + "integrity": "sha1-zFRJaF37hesRyYKKzHy4erW7/MA=" + }, "dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", @@ -335,6 +379,11 @@ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" }, + "dotenv": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-4.0.0.tgz", + "integrity": "sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0=" + }, "ecc-jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", @@ -386,6 +435,11 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, + "events": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", + "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" + }, "extend": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", @@ -593,6 +647,11 @@ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==" }, + "ieee754": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.8.tgz", + "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=" + }, "inflation": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/inflation/-/inflation-2.0.0.tgz", @@ -664,6 +723,11 @@ "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" }, + "jmespath": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", + "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=" + }, "joi": { "version": "6.10.1", "resolved": "https://registry.npmjs.org/joi/-/joi-6.10.1.tgz", @@ -1229,6 +1293,11 @@ "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==" }, + "querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" + }, "raw-body": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", @@ -1347,6 +1416,11 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" }, + "sax": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", + "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=" + }, "semver": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", @@ -1532,6 +1606,22 @@ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" }, + "url": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz", + "integrity": "sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ=", + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" + } + } + }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -1575,6 +1665,23 @@ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, + "xml2js": { + "version": "0.4.17", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.17.tgz", + "integrity": "sha1-F76T6q4/O3eTWceVtBlwWogX6Gg=", + "requires": { + "sax": "1.2.1", + "xmlbuilder": "4.2.1" + } + }, + "xmlbuilder": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-4.2.1.tgz", + "integrity": "sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU=", + "requires": { + "lodash": "4.17.4" + } + }, "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", diff --git a/package.json b/package.json index 152cf55..e6aa5a4 100755 --- a/package.json +++ b/package.json @@ -21,7 +21,9 @@ "homepage": "https://github.com/pierroberto/koa-server#readme", "dependencies": { "atob": "^2.0.3", + "aws-sdk": "^2.164.0", "bcrypt": "^1.0.3", + "dotenv": "^4.0.0", "faker": "^4.1.0", "isomorphic-fetch": "^2.2.1", "jsonwebtoken": "^8.1.0", diff --git a/server/auth/authenticate.js b/server/auth/authenticate.js index be48230..3a7be39 100644 --- a/server/auth/authenticate.js +++ b/server/auth/authenticate.js @@ -8,7 +8,7 @@ const bcrypt = require('bcrypt'); const atob = require('atob'); module.exports = async function (ctx) { - console.log('authentication...'); + console.log('Start authentication...'); const userpass = atob(ctx.header.authorization.slice(6, ctx.header.authorization.length)); console.log('user pass', userpass); const email = userpass.split(':')[0]; @@ -34,7 +34,11 @@ module.exports = async function (ctx) { } async function sign (authenticated, ctx, email, admin) { - console.log('authentication:', authenticated, email, admin); + console.log('====== LOGGER'); + console.log('is the account authenticated?', authenticated); + console.log('email:', email); + console.log('is this an admin?', admin); + console.log('======'); if (authenticated) { //I send the token in the body const token = ctx.body = { @@ -43,28 +47,29 @@ async function sign (authenticated, ctx, email, admin) { //I check if the token already exist in the db //and I check whether the user is an admin or not const isToken = await Token.find({email: email}); - console.log('is token', isToken); isToken[0].token = token.token; await isToken[0].save(); if (isToken.length) { if (isToken[0].isAdmin) { + console.log('====== LOGGER\n', email, '\nAuthenticated successfully!\n', '======'); return ctx.body = { isAdmin: true, token: token.token }; } + console.log('====== LOGGER\n', email, '\nAuthenticated successfully!\n', '======'); return ctx.body = { isAdmin: false, token: token.token }; } else { //I save the token into the db - console.log('a new token has been created...', token.token); const newToken = new Token(); newToken.token = token.token; newToken.email = email; newToken.isAdmin = admin; await newToken.save(); + console.log('====== LOGGER\n', email, '\nAuthenticated successfully!\n', '======'); return token; } } diff --git a/server/auth/usertype.js b/server/auth/usertype.js index 5b1c7bb..c129959 100644 --- a/server/auth/usertype.js +++ b/server/auth/usertype.js @@ -11,7 +11,6 @@ async function checkUserType (token) { } async function userEmail (token) { - console.log('token', token); const email = await Token.find({token:token}); if (email.length) return email[0].email; diff --git a/server/mailer/mailer.js b/server/mailer/mailer.js index 7529f5a..63ce1df 100644 --- a/server/mailer/mailer.js +++ b/server/mailer/mailer.js @@ -8,7 +8,6 @@ const nodemailer = require('nodemailer'); // Generate test SMTP service account from ethereal.email // Only needed if you don't have a real mail account for testing module.exports = function sendEmail (userData, id, ) { - console.log('userdata received in the mailer', userData); nodemailer.createTestAccount((err, account) => { // create reusable transporter object using the default SMTP transport @@ -24,9 +23,9 @@ module.exports = function sendEmail (userData, id, ) { // setup email data with unicode symbols let mailOptions = { - from: '"Zendama 👻" ', // sender address + from: '"Zendama 💰" ', // sender address to: `${userData.email}`, // list of receivers - subject: 'NAMEOFTHECOMPANY added you ✔', // Subject line + subject: 'You\'ve been invited to join Zendama ✔', // Subject line text: ` Hello ${userData.name}, You received an invitation to join Zendama diff --git a/zendomo.js b/zendomo.js index 0d822c1..b9d1e70 100644 --- a/zendomo.js +++ b/zendomo.js @@ -175,7 +175,7 @@ const tipUser = async (id, ammount) => { tradeId: response.tradeId, firstName: response.firstName, lastName: response.lastName, - tokens: response.tokens + ammount, + tokens: response.tokens + parseInt(ammount), credits: response.credits }), mode: 'cors' @@ -217,6 +217,7 @@ const purchase = async (id, price) => { const donation = async (id, price) => { let success= false; + console.log('========= HERE 2222', id); const person = await getOneUser(id) .then( response => { if (response.credits >= price) {