Created
May 14, 2015 01:11
-
-
Save mikeuduc/e66ef152775dd9d078d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// =========================================================== | |
// Project Name: Testimonial Guard ============== | |
// Company: Quodisys - SimpleCrew ============== | |
// Date Created: 2015 - 03 - 14 ============== | |
// Date Updated: ============== | |
// Dev Lead : Max Nguyen ============== | |
// Dev Editor : Tung Ton ============== | |
// Dev Supporter : Trinh Hong ============== | |
// =========================================================== | |
// load up the auth | |
var auth2 = require('../config/auth-new.js') | |
// load up the user model | |
var User = require('../app/models/user'); | |
// load up the company model | |
var Company = require('../app/models/Company'); | |
// load up the testimonial model | |
var Testimonial = require('../app/models/Testimonial'); | |
// include the company | |
var company = require('../config/company.js'); | |
// include the underscore framework | |
var underscore = require('underscore'); | |
// include testimonial's changed states handler | |
var testimonial = require('../config/testimonial.js'); | |
// include https | |
var https = require('https'); | |
// include the built-in node's Oauth | |
var OAuth = require('oauth').OAuth; | |
// Load http | |
var http = require('http'); | |
// app/routes.js | |
var TestimonialTime = require('moment'); | |
var config = require('../config/config'); | |
var request = require('request'); | |
// Generator for the companyID | |
var random = function (len, an) { | |
an = an && an.toLowerCase(); | |
var str = "", i = 0, min = an == "a"?10:0, max = an == "n"?10:62; | |
for (; i++ < len;) { | |
var r = Math.random() * (max - min) + min << 0; | |
str += String.fromCharCode(r += r > 9?r < 36?55:61:48); | |
} | |
return str; | |
} | |
// Ready? | |
module.exports = function (app, passport) { | |
// ================================ | |
// ERROR PAGE ===================== | |
// ================================ | |
app.get('/page/error' , function (req, res) { | |
res.write('Something wrong here'); | |
res.end(); | |
}); | |
// ===================================== | |
// HOME PAGE (with login links) ======== | |
// ===================================== | |
app.get('/', function (req, res) { | |
res.render('index.ejs'); // load the index.ejs file | |
}); | |
// ===================================== | |
// USER LOGIN ========================== | |
// ===================================== | |
// show the login form | |
app.get('/Account/login', function (req, res) { | |
// render the page and pass in any flash data if it exists | |
res.render('login.ejs', { message: req.flash('loginMessage') }); | |
}); | |
// Redirect the to the correct user account's profile | |
app.get('/Account/user', function (req, res) { | |
res.redirect('/' + req.user.id + '/account'); | |
}); | |
// process the login form | |
app.post('/Account/login', passport.authenticate('local-login', { | |
successRedirect : '/Admin/Testimonial', // redirect to the secure profile section | |
failureRedirect : '/Account/login', // redirect back to the signup page if there is an error | |
failureFlash : true // allow flash messages | |
})); | |
// ===================================== | |
// USER LOGOUT ========================= | |
// ===================================== | |
app.get('/Account/logout', function (req, res) { | |
// Logout and redirect to the homepage | |
req.logout(); | |
res.redirect('/'); | |
}); | |
// ===================================== | |
// USER SIGNUP ========================= | |
// ===================================== | |
// show the signup form | |
app.get('/Account/signup', function (req, res) { | |
// render the page and pass in any flash data if it exists | |
res.render('signup.ejs', { | |
message: req.flash('signupMessage'), | |
}); | |
}); | |
// process the signup form | |
app.post('/Account/signup', passport.authenticate('local-signup', { | |
successRedirect : '/Admin/Testimonial', // redirect to the secure profile section | |
failureRedirect : '/Account/signup', // redirect back to the signup page if there is an error | |
failureFlash : true // allow flash messages | |
})); | |
// ===================================== | |
// ADD / UPDATE COMPANY INFO =========== | |
// ===================================== | |
app.get('/Account/:userid/:companyid/addinfo', auth2.requireCompanyRole(['owner']), function (req, res) { | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
res.render('addinfo.ejs', { | |
userId : req.user.id, | |
userName: req.user.fullname, | |
companyId : req.param('companyid'), | |
companyName : docs.name, | |
companyWebsite : docs.website, | |
companyPhone : docs.phone, | |
companyEmail : docs.email | |
}); | |
} | |
}) | |
}); | |
// ===================================== | |
// SAVE COMPANY INFO HERE ============== | |
// ===================================== | |
app.post('/Account/:companyid/saved', auth2.requireCompanyRole(['owner']), function (req, res) { | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
if (req.body.website) { | |
docs.website = req.body.website; | |
} else { | |
docs.website = ""; | |
} | |
if (req.body.phone) { | |
docs.phone = req.body.phone; | |
} else { | |
docs.phone = ""; | |
} | |
if (req.body.email) { | |
docs.email = req.body.email; | |
} else { | |
docs.email = ""; | |
} | |
docs.save(function (err) { | |
if (err) | |
throw err | |
res.redirect('/' + req.param('companyid')); | |
}); | |
} | |
}); | |
}); | |
// ===================================== | |
// ADD NEW COMPANY FOR LOGGED USER ==== | |
// ===================================== | |
app.get('/Account/:userid/newcompany' , auth2.requireLoggedIn(), function (req, res) { | |
User.findOne({ '_id' : req.param('userid') }, function (err, docs) { | |
if (docs) { | |
res.render('addcompany.ejs', { | |
userId : docs.id, | |
userName: docs.fullname | |
}); | |
} | |
}) | |
}); | |
// ====================================== | |
// SAVE NEW COMPANY FOR LOGGED USER ==== | |
// ====================================== | |
app.post('/Account/:userid/companysaved', auth2.requireLoggedIn(), function (req, res) { | |
User.findOne({ '_id' : req.param('userid') }, function (err, docs) { | |
if (docs) { | |
var randomID = random(7); | |
docs.save(function (err, docs) { | |
if (err) { throw err } | |
else { | |
var newCompany = new Company(); | |
newCompany.id = randomID; | |
newCompany.name = req.body.companyname; | |
newCompany.totaltestimonial = 0; | |
newCompany.totalunpublished = 0; | |
newCompany.totalpublished = 0; | |
newCompany.totalarchive = 0; | |
newCompany.User._id = docs._id; | |
newCompany.User.email = docs.email; | |
newCompany.save(function (err, newCompany) { | |
if (err) { throw err } | |
else { | |
var oldCompInfo = docs.Company; | |
var addedCompInfo = { "_id": newCompany._id, "id": randomID , "name": req.body.companyname , "role" : "owner", "createddate": Date.now() }; | |
oldCompInfo.push(addedCompInfo); | |
docs.Company = oldCompInfo; | |
docs.save(function (err, docs) { | |
if (err) | |
throw err | |
res.redirect('/' + docs.Company[0].id); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}) | |
}); | |
// ========================================= | |
// TESTIMONIAL============================== | |
// ========================================= | |
app.get('/Admin/Testimonial', function (req, res) { | |
// Redirect to the first company id in the company list | |
if (req.user.Company[0].id) { | |
res.redirect('/' + req.user.Company[0].id); | |
} | |
}); | |
// ===================================== | |
// TESTIMONIAL/UNPUBLISHED ============= | |
// ===================================== | |
app.get('/:companyid', auth2.requireUserInCompany(), function (req, res) { | |
Testimonial.find({ 'Company.id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
res.render('unpublished.ejs', { | |
companyId : req.param('companyid'), | |
userName: req.user.fullname, | |
userInfo : req.user.id, | |
companyName: req.user.Company, | |
unpublished: underscore.filter(docs, function (testimonial) { return testimonial.state == 'un-published' }), | |
published: underscore.size(underscore.filter(docs, function (testimonial) { return testimonial.state == 'published' })), | |
archive: underscore.size(underscore.filter(docs, function (testimonial) { return testimonial.state == 'archive' })), | |
message: 'Testimonial', | |
urlPattern: "/[companyID]", | |
}); | |
} | |
}); | |
}); | |
// ===================================== | |
// CHANGE UNPUBLISHED to PUBLISHED ===== | |
// ===================================== | |
app.post('/unpublished/published/:companyid/:testimonialid', function (req, res) { | |
// Calling the change publish and passing request and response | |
testimonial.changepublish(req, res); | |
}); | |
// ===================================== | |
// CHANGE UNPUBLISHED to ARCHIVE ======= | |
// ===================================== | |
app.post('/unpublished/archive/:companyid/:testimonialid', function (req, res) { | |
// Calling the change archive and passing request and response | |
testimonial.changearchive(req, res); | |
}); | |
// ==================================================== | |
// TESTIMONIAL/PUBLISHED ============================== | |
// ==================================================== | |
app.get('/:companyid/published', auth2.requireCompanyRole(['owner']) , function (req, res) { | |
Testimonial.find({ 'Company.id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
var publishedState = underscore.filter(docs, function (testimonial) { return testimonial.state == 'published' }); | |
res.render('published.ejs', { | |
host : req.headers.host, | |
userId : req.user.id, | |
userName: req.user.fullname, | |
userInfo : req.user.id, | |
companyId : req.param('companyid'), | |
companyName: req.user.Company, | |
unpublished: underscore.size(underscore.filter(docs, function (testimonial) { return testimonial.state == 'un-published' })), | |
published: underscore.sortBy(publishedState, function (testimonial) { return testimonial.order }), | |
archive: underscore.size(underscore.filter(docs, function (testimonial) { return testimonial.state == 'archive' })), | |
message: 'Testimonial', | |
urlPattern: "/[companyID]/published" | |
}); | |
} | |
}); | |
}); | |
// ==================================================== | |
// TESTIMONIAL'S ORDER AJAX HANDLER =================== | |
// ==================================================== | |
app.post('/published/testimonial/orderchanged', function (req, res, next) { | |
var changedTestimonialOrder = req.body.data; | |
var companyId = req.body.companyid; | |
Testimonial.find({ 'Company.id' : companyId }, function (err, docs) { | |
if (docs) { | |
var publishedTestimonial = underscore.filter(docs, function (testimonial) { return testimonial.state == 'published' }); | |
var i = 0; | |
var j = 0; | |
underscore.each(changedTestimonialOrder, function (list_testimonial) { | |
var foundedTestimonial = underscore.find(publishedTestimonial, function (arr) { return arr._id == list_testimonial }); | |
//i += 1; | |
foundedTestimonial.order = i; | |
i++; | |
foundedTestimonial.save(function (err) { | |
if (err) { throw err } | |
j++; | |
if (j == changedTestimonialOrder.length) { | |
res.send("success"); | |
res.end(); | |
} | |
}) | |
}); | |
} | |
}) | |
}); | |
// ===================================== | |
// CHANGE PUBLISHED to UNPUBLISHED ===== | |
// ===================================== | |
app.post('/published/unpublish/:companyid/:testimonialid', function (req, res) { | |
// Calling the change unpublish and passing request and response | |
testimonial.changeunpublish(req, res); | |
}); | |
// ===================================== | |
// TESTIMONIAL/ARCHIVE ============================== | |
// ===================================== | |
app.get('/:companyid/archived', auth2.requireCompanyRole(['owner']), function (req, res) { | |
Testimonial.find({ 'Company.id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
res.render('archive.ejs', { | |
companyId : req.param('companyid'), | |
userName: req.user.fullname, | |
userInfo : req.user.id, | |
companyName: req.user.Company, | |
unpublished: underscore.size(underscore.filter(docs, function (testimonial) { return testimonial.state == 'un-published' })), | |
published: underscore.size(underscore.filter(docs, function (testimonial) { return testimonial.state == 'published' })), | |
archive: underscore.filter(docs, function (testimonial) { return testimonial.state == 'archive' }), | |
message: 'Testimonial', | |
urlPattern: "/[companyID]/archived" | |
}); | |
} | |
}) | |
}); | |
// ===================================== | |
// CHANGE ARCHIVE to UNPUBLISHED ======= | |
// ===================================== | |
app.post('/archive/unpublish/:companyid/:testimonialid', function (req, res) { | |
// Calling the change archive to unpublished and passing request and response | |
testimonial.changearchive_unpublished(req, res); | |
}); | |
// ===================================== | |
// EDIT/SAVE =========================== | |
// ===================================== | |
app.post('/Edit/save/:companyid/:testimonialid', function (req, res) { | |
// Calling the edit testimonial and passing request and response | |
testimonial.edittestimonial(req, res); | |
}); | |
// ===================================== | |
// EDIT/RESET ========================== | |
// ===================================== | |
app.post('/Edit/reset/:companyid/:testimonialid', function (req, res) { | |
// Calling the reset testimonial and passing request and response | |
testimonial.resettestimonial(req, res); | |
}); | |
// ===================================== | |
// BADGES ============================== | |
// ===================================== | |
app.get('/Admin/install', function (req, res) { | |
// render the page and pass in any flash data if it exists | |
res.redirect('/install/' + req.user.Company[0].id); | |
}); | |
// ===================================== | |
// BADGES TAB ========================== | |
// ===================================== | |
app.get('/install/:companyid', auth2.requireCompanyRole(['owner']), function (req, res) { | |
// Find the company based on the requested company id | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
if (docs.User.email == req.user.email && docs.User._id == req.user.id) { | |
res.render('install.ejs', { | |
host : req.headers.host, | |
userInfo : req.user.id, | |
userName: req.user.fullname, | |
companyName: req.user.Company, | |
companyId : req.param('companyid'), | |
message: 'Badges', | |
urlPattern: "/install/[companyID]", | |
}); | |
} | |
} | |
}) | |
}); | |
// ===================================== | |
// BADGES EMBED.JS EVENT HANDLER ======= | |
// ===================================== | |
app.get('/embed/Badge/:q/:companyId/:badgeType', function (req, res) { | |
if (req.param('q') == "jcvnukhf76ygdhuit") { | |
if (req.param('badgeType')) { | |
res.redirect('/BadgesRequest/' + req.param('companyId') + '/' + req.param('badgeType')); | |
} | |
} | |
else if (req.param('q') == "loadEmbedContent") { | |
if (req.param('badgeType')) { | |
res.redirect('/BadgeCertificate/' + req.param('companyId')); | |
} | |
} | |
}); | |
// ===================================== | |
// BADGES EMBEDDED SELECTED BADGE ====== | |
// ===================================== | |
app.get('/BadgesRequest/:companyid/:badgetype' , function (req, res, next) { | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
if (req.param('badgetype') == 'badgelogo') { | |
// Render out the testimonial request ejs | |
res.render('badges.ejs', { | |
host : req.headers.host, | |
message: 'badgelogo' | |
}); | |
} else if (req.param('badgetype') == 'badgeseal2') { | |
// Render out the testimonial request ejs | |
res.render('badges.ejs', { | |
host : req.headers.host, | |
message: 'badgeseal2' | |
}); | |
} else { | |
// Render out the testimonial request ejs | |
res.render('badges.ejs', { | |
host : req.headers.host, | |
message: 'badgeseal3' | |
}); | |
} | |
} | |
}) | |
}); | |
// =================================================== | |
// BADGES EMBEDDED SELECTED BADGE'S CERTIFICATE ====== | |
// =================================================== | |
app.get('/BadgeCertificate/:companyid' , function (req, res, next) { | |
Testimonial.find({ 'Company.id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
var publishedState = underscore.filter(docs, function (testimonial) { return testimonial.state == 'published' }); | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, comp) { | |
if (comp) { | |
res.render('badgecertificate.ejs', { | |
host : req.headers.host, | |
companyId : req.param('companyid'), | |
companyWebsite : comp.website, | |
companyPhone : comp.phone, | |
companyEmail : comp.email, | |
companyInfo : comp, | |
testimonial: underscore.sortBy(publishedState, function (testimonial) { return testimonial.order }), | |
}); | |
} | |
}) | |
} | |
}) | |
}); | |
// ===================================== | |
// REQUEST ============================ | |
// ===================================== | |
app.get('/Admin/request', function (req, res) { | |
// Redirect when the request is make | |
res.redirect('/request/' + req.user.Company[0].id); // need to be change here based on the selected company from the testimonial | |
}); | |
// ===================================== | |
// REQUEST TAB ========================= | |
// ===================================== | |
app.get('/request/:companyid', auth2.requireCompanyRole(['owner']), function (req, res) { | |
// Find the company based on the requested company id | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
if (docs.User.email == req.user.email && docs.User._id == req.user.id) { | |
res.render('request.ejs', { | |
host : req.headers.host, | |
userInfo : req.user.id, | |
userName: req.user.fullname, | |
companyId : req.param('companyid'), | |
companyName: req.user.Company, | |
message: 'Request', | |
urlPattern: "/request/[companyID]", | |
}); | |
} | |
} | |
}) | |
}); | |
// ===================================== | |
// REQUEST URL LINK/IFRAME HANDLER ===== | |
// ===================================== | |
app.get('/TestimonialRequest/:userid/:companyid', function (req, res) { | |
// Find the company based on the requested company id | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
if (docs.User._id == req.param('userid')) { | |
res.render('testimonialrequested.ejs', { | |
host : req.headers.host, | |
companyId : req.param('companyid'), | |
companyName : docs.name, | |
}); | |
} | |
} | |
}) | |
}); | |
// ===================================== | |
// REQUEST EMBEDDED CODE =============== | |
// ===================================== | |
// THIS SHOULD BE COMMENT OUT HERE | |
app.get('/embed/Request/:q/:userId/:companyId', function (req, res) { | |
if (req.param('q') == "jcvnukhf76ygdhuit") { | |
if (req.param('userId') && req.param('companyId')) { | |
res.redirect('/TestimonialRequest/' + req.param('userId') + '/' + req.param('companyId')); | |
} | |
} | |
else if (req.param('q') == "loadEmbedContent") { | |
if (req.param('userId') && req.param('companyId')) { | |
//var arr = req.param('companyId').split(";"); | |
var fblink = "https://www.facebook.com/dialog/oauth?client_id=852249214821890" + "&redirect_uri=http://" + req.headers.host + "/facebook/verification?companyID=" + req.param('companyId') + "&response_type=code&scope=email,public_profile,user_friends,user_about_me,publish_actions,read_stream"; | |
//request.get(fblink, function (err, response, body) { | |
// if (!err && response.statusCode == 200) { | |
// console.log(body) // Show the HTML for the Google homepage. | |
// } | |
//}); | |
https.get(fblink, function (facebookRes) { | |
var a = 'aaaa'; | |
facebookRes.on('data', function (d) { | |
var b = 'bbbbbbb'; | |
}); | |
}).on('error', function (e) { | |
console.error(e); | |
}); | |
} | |
} | |
//if (req.param('q') == 'abc') { | |
// res.send('dfhdsfh'); | |
// res.end(); | |
//} | |
}); | |
// ================================ | |
// ABOVE FUNCTION ENDS ============ | |
// ================================ | |
// ====================================================== | |
// INDIVIDUAL TESTIMONIAL EMBEDDED HANDLER ============== | |
// ====================================================== | |
app.get('/embed/Testimonial/:q/:companyId/:testimonialId', function (req, res) { | |
if (req.param('q') == "jcvnukhf76ygdhuit") { | |
if (req.param('testimonialId')) { | |
res.redirect('/Embedded/' + req.param('companyId') + '/' + req.param('testimonialId')); | |
} | |
} | |
else if (req.param('q') == "loadEmbedContent") { | |
if (req.param('testimonialId')) { | |
res.redirect('/TestimonialCertificate/' + req.param('companyId') + '/' + req.param('testimonialId')); | |
} | |
} | |
}); | |
// ======================================================================= | |
// INDIVIDUAL TESTIMONIAL EMBEDDED SELECTED TESTIMONIAL ================== | |
// ======================================================================= | |
app.get('/Embedded/:companyid/:testimonialid' , function (req, res) { | |
Testimonial.find({ 'Company.id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
var index_testimonial = underscore.findIndex(docs, function (testimonial) { return testimonial._id == req.param('testimonialid') }); | |
if (index_testimonial != -1) { | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, comp) { | |
if (comp) { | |
res.render('testimonialtemplate.ejs', { | |
host : req.headers.host, | |
userId: req.param('userid'), | |
companyId : req.param('companyid'), | |
companyInfo : comp, | |
testimonial: docs[index_testimonial], | |
}); | |
} | |
}) | |
} | |
} | |
}) | |
}); | |
// ================================================================================ | |
// INDIVIDUAL TESTIMONIAL EMBEDDED SELECTED TESTIMONIAL'S CERTIFICATE ============= | |
// ================================================================================ | |
app.get('/TestimonialCertificate/:companyid/:testimonialid' , function (req, res, next) { | |
Testimonial.find({ 'Company.id' : req.param('companyid') }, function (err, docs) { | |
if (docs) { | |
var index_testimonial = underscore.findIndex(docs, function (testimonial) { return testimonial._id == req.param('testimonialid') }); | |
if (index_testimonial != -1) { | |
Company.findOne({ 'id' : req.param('companyid') }, function (err, comp) { | |
if (comp) { | |
res.render('testimonialcertificate.ejs', { | |
userId: comp.User._id, | |
host : req.headers.host, | |
companyId : req.param('companyid'), | |
companyWebsite : comp.website, | |
companyPhone : comp.phone, | |
companyEmail : comp.email, | |
companyInfo : comp, | |
testimonial: docs[index_testimonial], | |
}); | |
} | |
}) | |
} | |
} | |
}) | |
}); | |
// ===================================================================== | |
// SET THE TESTIMONIAL RATING AND COMMENT IN THE SESSION =============== | |
// ===================================================================== | |
app.post('/TestimonialRequest/Saved', function (req, res) { | |
var _savingData = req.body.data; | |
req.session.cid = _savingData.cid; | |
req.session.rating = _savingData.rating; | |
req.session.comment = _savingData.comment; | |
res.send(_savingData); | |
res.end(); | |
}); | |
// ===================================== | |
// FACEBOOK ERROR/REDIRECT ============= | |
// ===================================== | |
app.get('/page/error/face' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
res.write('Please sign out current facebook . Retry Sign in facebook'); | |
res.end(); | |
}); | |
app.get('/page/update/face' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
//res.write('User existed and have not verify SO UPDATED, thank you for the testimonial tho'); | |
res.write('Thank you'); | |
res.end(); | |
}); | |
app.get('/page/old/face' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
//res.write('User existed and verified, thank you for the testimonial tho'); | |
res.write('Thank you'); | |
res.end(); | |
}); | |
app.get('/page/new/face' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
//res.write('New User, SO CREATED NEW USER, thank you for the testimonial tho'); | |
res.write('Thank you'); | |
res.end(); | |
}); | |
// ===================================== | |
// FACEBOOK SIGNED HANDLER ============= | |
// ===================================== | |
app.get('/facebook/verification', function (req, res) { | |
var _cid = req.session.cid; | |
var _rating = req.session.rating; | |
var _comment = req.session.comment; | |
var time = TestimonialTime(new Date()); | |
var formatTime = time.format("MMMM D YYYY"); | |
var _facebookExchangeTokenURL = "https://graph.facebook.com/oauth/access_token?client_id=" + config.facebook.app_id + "&redirect_uri=http://" + req.headers.host + "/facebook/verification?companyID=" + _cid + "&client_secret=" + config.facebook.app_secret + "&code=" + req.param("code"); | |
https.get(_facebookExchangeTokenURL, function (facebookRes) { | |
facebookRes.on('data', function (d) { | |
var _accessToken = d.toString('utf-8').split('='); | |
_accessToken = _accessToken[1].split('&'); | |
_accessToken = _accessToken[0]; | |
https.get("https://graph.facebook.com/v2.3/me?fields=id,email,picture,name,link&access_token=" + _accessToken, function (facebookResData) { | |
facebookResData.on('data', function (d) { | |
var _facebookResData = JSON.parse(d); | |
// Check if facebook email match with current user email | |
if (_facebookResData.email) { | |
User.findOne({ 'email': _facebookResData.email }, function (err, user) { | |
// If the user found here | |
if (user) { | |
// update the testimonial count | |
user.testimonialcount = user.testimonialcount + 1; | |
// if the user haven't verify yet | |
if (!user.verifytype) { | |
// updating the user | |
user.facebookid = _facebookResData.id; | |
user.verifytype = 'facebook'; | |
user.profileimage = _facebookResData.picture.data.url; | |
// Saving the updated user | |
user.save(function (err, savedUser) { | |
if (err) { throw err } | |
// updating the testimonial now if no error | |
else { | |
Company.findOne({ 'id': req.session.cid }, function (err, company) { | |
if (company) { | |
company.totaltestimonial = company.totaltestimonial + 1; | |
company.totalunpublished = company.totalunpublished + 1; | |
company.save(function (err, savedCompany) { | |
if (err) { throw err } | |
else { | |
var newTestimonial = new Testimonial(); | |
// Save the testimonial's info | |
newTestimonial.name = _facebookResData.name; | |
newTestimonial.createddate = formatTime; | |
newTestimonial.verifytype = "Facebook"; | |
newTestimonial.originaltext = req.session.comment; | |
newTestimonial.currenttext = ""; | |
newTestimonial.state = "un-published"; | |
newTestimonial.order = -1; | |
newTestimonial.rating = req.session.rating; | |
// Save the Testimonial.User info | |
newTestimonial.User._id = savedUser._id; | |
newTestimonial.User.fullname = savedUser.fullname; | |
newTestimonial.User.email = savedUser.email; | |
newTestimonial.User.profileimage = savedUser.profileimage; | |
newTestimonial.User.socialurl = _facebookResData.link; | |
// Save the Testimonial.Company info | |
newTestimonial.Company.id = savedCompany.id; | |
newTestimonial.Company._id = savedCompany._id; | |
newTestimonial.save(function (err) { | |
if (err) { throw err } | |
res.redirect('/page/update/face'); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
// if the user verified already, then what? | |
else { | |
user.testimonial = user.testimonial + 1; | |
user.save(function (err, savedUser) { | |
if (err) { throw err } | |
else { | |
Company.findOne({ 'id': req.session.cid }, function (err, company) { | |
if (company) { | |
company.totaltestimonial = company.totaltestimonial + 1; | |
company.totalunpublished = company.totalunpublished + 1; | |
company.save(function (err, savedCompany) { | |
if (err) { throw err } | |
else { | |
var newTestimonial = new Testimonial(); | |
// Save the testimonial's info | |
newTestimonial.name = _facebookResData.name; | |
newTestimonial.createddate = formatTime; | |
newTestimonial.verifytype = "Facebook"; | |
newTestimonial.originaltext = req.session.comment; | |
newTestimonial.currenttext = ""; | |
newTestimonial.state = "un-published"; | |
newTestimonial.order = -1; | |
newTestimonial.rating = req.session.rating; | |
// Save the Testimonial.User info | |
newTestimonial.User._id = savedUser._id; | |
newTestimonial.User.fullname = savedUser.fullname; | |
newTestimonial.User.email = savedUser.email; | |
newTestimonial.User.profileimage = savedUser.profileimage; | |
newTestimonial.User.socialurl = _facebookResData.link; | |
// Save the Testimonial.Company info | |
newTestimonial.Company.id = savedCompany.id; | |
newTestimonial.Company._id = savedCompany._id; | |
newTestimonial.save(function (err) { | |
if (err) { throw err } | |
res.redirect('/page/old/face'); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
} else { | |
// Creating new user here | |
var newUser = new User(); | |
newUser.email = _facebookResData.email; | |
newUser.password = ""; | |
newUser.fullname = _facebookResData.name; | |
newUser.createddate = Date.now(); | |
newUser.testimonialcount = 1; | |
newUser.facebookid = _facebookResData.id; | |
newUser.verifytype = "Facebook"; | |
newUser.linkedinid = ""; | |
newUser.profileimage = _facebookResData.picture.data.url; | |
newUser.save(function (err , savedUser) { | |
if (err) { throw err } | |
else { | |
Company.findOne({ 'id': req.session.cid }, function (err, company) { | |
if (company) { | |
company.totaltestimonial = company.totaltestimonial + 1; | |
company.totalunpublished = company.totalunpublished + 1; | |
company.save(function (err, savedCompany) { | |
if (err) { throw err } | |
else { | |
var newTestimonial = new Testimonial(); | |
// Save the testimonial's info | |
newTestimonial.name = _facebookResData.name; | |
newTestimonial.createddate = formatTime; | |
newTestimonial.verifytype = "Facebook"; | |
newTestimonial.originaltext = req.session.comment; | |
newTestimonial.currenttext = ""; | |
newTestimonial.state = "un-published"; | |
newTestimonial.order = -1; | |
newTestimonial.rating = req.session.rating; | |
// Save the Testimonial.User info | |
newTestimonial.User._id = savedUser._id; | |
newTestimonial.User.fullname = savedUser.fullname; | |
newTestimonial.User.email = savedUser.email; | |
newTestimonial.User.profileimage = savedUser.profileimage; | |
newTestimonial.User.socialurl = _facebookResData.link; | |
// Save the Testimonial.Company info | |
newTestimonial.Company.id = savedCompany.id; | |
newTestimonial.Company._id = savedCompany._id; | |
newTestimonial.save(function (err) { | |
if (err) { throw err } | |
res.redirect('/page/new/face'); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} else { | |
res.redirect('/page/error/face'); | |
res.end(); | |
} | |
}); | |
}); | |
}); | |
}).on('error', function (e) { | |
console.error(e); | |
}); | |
}); | |
// ============================================================= | |
// LINKEDIN ERROR/ TESTIMONIAL'S REDIRECTS ===================== | |
// ============================================================= | |
app.get('/page/error/linkedin' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
res.write('Please sign out current facebook . Retry Sign in facebook'); | |
res.end(); | |
}); | |
app.get('/page/update/linkedin' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
//res.write('User existed and have not verify SO UPDATED, thank you for the testimonial tho'); | |
res.write('Thank you'); | |
res.end(); | |
}); | |
app.get('/page/old/linkedin' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
//res.write('User existed and verified, thank you for the testimonial tho'); | |
res.write('Thank you'); | |
res.end(); | |
}); | |
app.get('/page/new/linkedin' , function (req, res) { | |
//res.render('Error.ejs'); // load the error.ejs file | |
//res.write('New User, SO CREATED NEW USER, thank you for the testimonial tho'); | |
res.write('Thank you'); | |
res.end(); | |
}); | |
// ===================================== | |
// LINKEDIN SIGNED HANDLER ============= | |
// ===================================== | |
app.get('/linkedin/verification', function (req, res) { | |
var LinkedInCallBack = "http://" + req.headers.host + "/linked/signin-linkedin"; | |
var getRequestTokenUrl = "https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress"; | |
var oa = new OAuth(getRequestTokenUrl, | |
"https://api.linkedin.com/uas/oauth/accessToken", | |
config.linkedin.app_id, | |
config.linkedin.app_secret, | |
"1.0", | |
LinkedInCallBack + (req.param('action') && req.param('action') != "" ? "?action=" + querystring.escape(req.param('action')) : ""), | |
"HMAC-SHA1"); | |
oa.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) { | |
if (error) { | |
console.log('error'); | |
} | |
else { | |
req.session.oa = oa; | |
req.session.oauth_token = oauth_token; | |
req.session.oauth_token_secret = oauth_token_secret; | |
res.redirect("https://www.linkedin.com/uas/oauth/authorize?oauth_token=" + oauth_token); | |
} | |
}) | |
}); | |
// ===================================== | |
// LINKEDIN SIGNED-IN CALLBACK ========= | |
// ===================================== | |
app.get('/linked/signin-linkedin', function (req, res) { | |
req.session.oauth_verifier = req.query.oauth_verifier; | |
var oa = new OAuth(req.session.oa._requestUrl, | |
req.session.oa._accessUrl, | |
req.session.oa._consumerKey, | |
req.session.oa._consumerSecret, | |
req.session.oa._version, | |
req.session.oa._authorize_callback, | |
req.session.oa._signatureMethod); | |
oa.getOAuthAccessToken(req.session.oauth_token, req.session.oauth_token_secret, req.param('oauth_verifier'), | |
function (error, oauth_access_token, oauth_access_token_secret, results) { | |
if (error) { | |
console.log('error'); | |
} | |
else { | |
req.session.oauth_access_token = oauth_access_token; | |
req.session.oauth_access_token_secret = oauth_access_token_secret; | |
res.redirect((req.param('action') && req.param('action') != "") ? req.param('action') : "/success/linkedin_track"); | |
} | |
}); | |
}); | |
// ===================================== | |
// LINKEDIN SUCCEDDED CALLBACK ========= | |
// ===================================== | |
app.get('/success/linkedin_track', function (req, res) { | |
var time = TestimonialTime(new Date()); | |
var formatTime = time.format("MMMM D YYYY"); | |
var oa = new OAuth(req.session.oa._requestUrl, | |
req.session.oa._accessUrl, | |
req.session.oa._consumerKey, | |
req.session.oa._consumerSecret, | |
req.session.oa._version, | |
req.session.oa._authorize_callback, | |
req.session.oa._signatureMethod); | |
oa.getProtectedResource("http://api.linkedin.com/v1/people/~:(id,public-profile-url,picture-url,last-name,first-name,email-address,site-standard-profile-request)?format=json", "GET", req.session.oauth_access_token, req.session.oauth_access_token_secret, function (error, data, response) { | |
var _linkedinResData = JSON.parse(data); | |
if (_linkedinResData.emailAddress) { | |
User.findOne({ 'email': _linkedinResData.emailAddress }, function (err, user) { | |
// If the user found here | |
if (user) { | |
// update the testimonial count | |
user.testimonialcount = user.testimonialcount + 1; | |
// if the user haven't verify yet | |
if (!user.verifytype) { | |
// updating the user | |
user.linkedinid = _linkedinResData.id; | |
user.verifytype = 'LinkedIn'; | |
user.profileimage = _linkedinResData.pictureUrl; | |
// Saving the updated user | |
user.save(function (err, savedUser) { | |
if (err) { throw err } | |
// updating the testimonial now if no error | |
else { | |
Company.findOne({ 'id': req.session.cid }, function (err, company) { | |
if (company) { | |
company.totaltestimonial = company.totaltestimonial + 1; | |
company.totalunpublished = company.totalunpublished + 1; | |
company.save(function (err, savedCompany) { | |
if (err) { throw err } | |
else { | |
var newTestimonial = new Testimonial(); | |
// Save the testimonial's info | |
newTestimonial.name = _linkedinResData.firstName + " " + _linkedinResData.lastName; | |
newTestimonial.createddate = formatTime; | |
newTestimonial.verifytype = "LinkedIn"; | |
newTestimonial.originaltext = req.session.comment; | |
newTestimonial.currenttext = ""; | |
newTestimonial.state = "un-published"; | |
newTestimonial.order = -1; | |
newTestimonial.rating = req.session.rating; | |
// Save the Testimonial.User info | |
newTestimonial.User._id = savedUser._id; | |
newTestimonial.User.fullname = savedUser.fullname; | |
newTestimonial.User.email = savedUser.email; | |
newTestimonial.User.profileimage = savedUser.profileimage; | |
newTestimonial.User.socialurl = _linkedinResData.publicProfileUrl; | |
// Save the Testimonial.Company info | |
newTestimonial.Company.id = savedCompany.id; | |
newTestimonial.Company._id = savedCompany._id; | |
newTestimonial.save(function (err) { | |
if (err) { throw err } | |
res.redirect('/page/update/linkedin'); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
// if the user verified already, then what? | |
else { | |
user.testimonial = user.testimonial + 1; | |
user.save(function (err, savedUser) { | |
if (err) { throw err } | |
else { | |
Company.findOne({ 'id': req.session.cid }, function (err, company) { | |
if (company) { | |
company.totaltestimonial = company.totaltestimonial + 1; | |
company.totalunpublished = company.totalunpublished + 1; | |
company.save(function (err, savedCompany) { | |
if (err) { throw err } | |
else { | |
var newTestimonial = new Testimonial(); | |
// Save the testimonial's info | |
newTestimonial.name = _linkedinResData.firstName + " " + _linkedinResData.lastName; | |
newTestimonial.createddate = formatTime; | |
newTestimonial.verifytype = "LinkedIn"; | |
newTestimonial.originaltext = req.session.comment; | |
newTestimonial.currenttext = ""; | |
newTestimonial.state = "un-published"; | |
newTestimonial.order = -1; | |
newTestimonial.rating = req.session.rating; | |
// Save the Testimonial.User info | |
newTestimonial.User._id = savedUser._id; | |
newTestimonial.User.fullname = savedUser.fullname; | |
newTestimonial.User.email = savedUser.email; | |
newTestimonial.User.profileimage = savedUser.profileimage; | |
newTestimonial.User.socialurl = _linkedinResData.publicProfileUrl; | |
// Save the Testimonial.Company info | |
newTestimonial.Company.id = savedCompany.id; | |
newTestimonial.Company._id = savedCompany._id; | |
newTestimonial.save(function (err) { | |
if (err) { throw err } | |
res.redirect('/page/old/linkedin'); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
} else { | |
// Creating new user here | |
var newUser = new User(); | |
newUser.email = _linkedinResData.emailAddress; | |
newUser.password = ""; | |
newUser.fullname = _linkedinResData.firstName + " " + _linkedinResData.lastName; | |
newUser.createddate = formatTime; | |
newUser.testimonialcount = 1; | |
newUser.facebookid = ""; | |
newUser.verifytype = "LinkedIn"; | |
newUser.linkedinid = _linkedinResData.id; | |
newUser.profileimage = _linkedinResData.pictureUrl; | |
newUser.save(function (err , savedUser) { | |
if (err) { throw err } | |
else { | |
Company.findOne({ 'id': req.session.cid }, function (err, company) { | |
if (company) { | |
company.totaltestimonial = company.totaltestimonial + 1; | |
company.totalunpublished = company.totalunpublished + 1; | |
company.save(function (err, savedCompany) { | |
if (err) { throw err } | |
else { | |
var newTestimonial = new Testimonial(); | |
// Save the testimonial's info | |
newTestimonial.name = _linkedinResData.firstName + " " + _linkedinResData.lastName; | |
newTestimonial.createddate = formatTime; | |
newTestimonial.verifytype = "LinkedIn"; | |
newTestimonial.originaltext = req.session.comment; | |
newTestimonial.currenttext = ""; | |
newTestimonial.state = "un-published"; | |
newTestimonial.order = -1; | |
newTestimonial.rating = req.session.rating; | |
// Save the Testimonial.User info | |
newTestimonial.User._id = savedUser._id; | |
newTestimonial.User.fullname = savedUser.fullname; | |
newTestimonial.User.email = savedUser.email; | |
newTestimonial.User.profileimage = savedUser.profileimage; | |
newTestimonial.User.socialurl = _linkedinResData.publicProfileUrl; | |
// Save the Testimonial.Company info | |
newTestimonial.Company.id = savedCompany.id; | |
newTestimonial.Company._id = savedCompany._id; | |
newTestimonial.save(function (err) { | |
if (err) { throw err } | |
res.redirect('/page/new/linkedin'); | |
res.end(); | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
} else { | |
res.redirect('/page/error/linkedin'); | |
res.end(); | |
} | |
}); | |
}); | |
// ================================ | |
// ABOVE FUNCTION ENDS ============ | |
// ================================ | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment