app.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  1. // FinalsClub Server
  2. //
  3. // This file consists of the main webserver for FinalsClub.org
  4. // and is split between a standard CRUD style webserver and
  5. // a websocket based realtime webserver.
  6. //
  7. // A note on house keeping: Anything with XXX is marked
  8. // as such because it should be looked at and possibly
  9. // revamped or removed depending on circumstances.
  10. // Module loading
  11. var sys = require( 'sys' );
  12. var os = require( 'os' );
  13. var url = require( 'url' );
  14. var express = require( 'express' );
  15. var mongoStore = require( 'connect-mongo' );
  16. var async = require( 'async' );
  17. var db = require( './db.js' );
  18. var mongoose = require( './models.js' ).mongoose;
  19. var Mailer = require( './mailer.js' );
  20. var hat = require('hat');
  21. var connect = require( 'connect' );
  22. var Session = connect.middleware.session.Session;
  23. var parseCookie = connect.utils.parseCookie;
  24. var Backchannel = require('./bc/backchannel');
  25. // Depracated
  26. // Used for initial testing
  27. var log3 = function() {}
  28. // Create webserver
  29. var app = module.exports = express.createServer();
  30. // Load Mongoose Schemas
  31. // The actual schemas are located in models.j
  32. var User = mongoose.model( 'User' );
  33. var School = mongoose.model( 'School' );
  34. var Course = mongoose.model( 'Course' );
  35. var Lecture = mongoose.model( 'Lecture' );
  36. var Note = mongoose.model( 'Note' );
  37. // More schemas used for legacy data
  38. var ArchivedCourse = mongoose.model( 'ArchivedCourse' );
  39. var ArchivedNote = mongoose.model( 'ArchivedNote' );
  40. var ArchivedSubject = mongoose.model( 'ArchivedSubject' );
  41. // XXX Not sure if necessary
  42. var ObjectId = mongoose.SchemaTypes.ObjectId;
  43. // Configuration
  44. // Use the environment variable DEV_EMAIL for testing
  45. var ADMIN_EMAIL = process.env.DEV_EMAIL || 'info@finalsclub.org';
  46. // Set server hostname and port from environment variables,
  47. // then check if set.
  48. // XXX Can be cleaned up
  49. var serverHost = process.env.SERVER_HOST;
  50. var serverPort = process.env.SERVER_PORT;
  51. if( serverHost ) {
  52. console.log( 'Using server hostname defined in environment: %s', serverHost );
  53. } else {
  54. serverHost = os.hostname();
  55. console.log( 'No hostname defined, defaulting to os.hostname(): %s', serverHost );
  56. }
  57. // Express configuration depending on environment
  58. // development is intended for developing locally or
  59. // when not in production, otherwise production is used
  60. // when the site will be run live for regular usage.
  61. app.configure( 'development', function() {
  62. // In development mode, all errors and stack traces will be
  63. // dumped to the console and on page for easier troubleshooting
  64. // and debugging.
  65. app.set( 'errorHandler', express.errorHandler( { dumpExceptions: true, showStack: true } ) );
  66. // Set database connection information from environment
  67. // variables otherwise use localhost.
  68. app.set( 'dbHost', process.env.MONGO_HOST || 'localhost' );
  69. app.set( 'dbUri', 'mongodb://' + app.set( 'dbHost' ) + '/fc' );
  70. // Set Amazon access and secret keys from environment
  71. // variables. These keys are intended to be secret, so
  72. // are not included in the source code, but set on the server
  73. // manually.
  74. app.set( 'awsAccessKey', process.env.AWS_ACCESS_KEY_ID );
  75. app.set( 'awsSecretKey', process.env.AWS_SECRET_ACCESS_KEY );
  76. // If a port wasn't set earlier, set to 3000
  77. if ( !serverPort ) {
  78. serverPort = 3000;
  79. }
  80. });
  81. // Production configuration settings
  82. app.configure( 'production', function() {
  83. // At the moment we have errors outputting everything
  84. // so if there are any issues it is easier to track down.
  85. // Once the site is more stable it will be prudent to
  86. // use less error tracing.
  87. app.set( 'errorHandler', express.errorHandler( { dumpExceptions: true, showStack: true } ) );
  88. // Disable view cache due to stale views.
  89. // XXX Disable view caching temp
  90. app.disable( 'view cache' )
  91. // Against setting the database connection information
  92. // XXX Can be cleaned up or combined
  93. app.set( 'dbHost', process.env.MONGO_HOST || 'localhost' );
  94. app.set( 'dbUri', 'mongodb://' + app.set( 'dbHost' ) + '/fc' );
  95. // XXX Can be cleaned up or combined
  96. app.set( 'awsAccessKey', process.env.AWS_ACCESS_KEY_ID );
  97. app.set( 'awsSecretKey', process.env.AWS_SECRET_ACCESS_KEY );
  98. // Set to port 80 if not set through environment variables
  99. if ( !serverPort ) {
  100. serverPort = 80;
  101. }
  102. });
  103. // General Express configuration settings
  104. app.configure(function(){
  105. // Views are rendered from public/index.html and main.js except for the pad that surrounds EPL and BC
  106. // FIXME: make all views exist inside of public/index.html
  107. // Views are housed in the views folder
  108. app.set( 'views', __dirname + '/views' );
  109. // All templates use jade for rendering
  110. app.set( 'view engine', 'jade' );
  111. // Bodyparser is required to handle form submissions
  112. // without manually parsing them.
  113. app.use( express.bodyParser() );
  114. app.use( express.cookieParser() );
  115. // Sessions are stored in mongodb which allows them
  116. // to be persisted even between server restarts.
  117. app.set( 'sessionStore', new mongoStore( {
  118. 'db' : 'fc',
  119. 'url' : app.set( 'dbUri' )
  120. }));
  121. // This is where the actual Express session handler
  122. // is defined, with a mongoStore being set as the
  123. // session storage versus in memory storage that is
  124. // used by default.
  125. app.use( express.session( {
  126. // A secret 'password' for encrypting and decrypting
  127. // cookies.
  128. // XXX Should be handled differently
  129. 'secret' : 'finalsclub',
  130. // The max age of the cookies that is allowed
  131. // 60 (seconds) * 60 (minutes) * 24 (hours) * 30 (days) * 1000 (milliseconds)
  132. 'maxAge' : new Date(Date.now() + (60 * 60 * 24 * 30 * 1000)),
  133. 'store' : app.set( 'sessionStore' )
  134. }));
  135. // methodOverride is used to handle PUT and DELETE HTTP
  136. // requests that otherwise aren't handled by default.
  137. app.use( express.methodOverride() );
  138. // Static files are loaded when no dynamic views match.
  139. app.use( express.static( __dirname + '/public', {maxAge: 900000} ) );
  140. // Sets the routers middleware to load after everything set
  141. // before it, but before static files.
  142. app.use( app.router );
  143. app.use(express.logger({ format: ':method :url' }));
  144. // This is the command to use the default express error logger/handler
  145. app.use(express.errorHandler({ dumpExceptions: true }));
  146. });
  147. // Mailer functions and helpers
  148. // These are helper functions that make for cleaner code.
  149. // sendUserActivation is for when a user registers and
  150. // first needs to activate their account to use it.
  151. function sendUserActivation( user ) {
  152. var message = {
  153. 'to' : user.email,
  154. 'subject' : 'Activate your FinalsClub.org Account',
  155. // Templates are in the email folder and use ejs
  156. 'template' : 'userActivation',
  157. // Locals are used inside ejs so dynamic information
  158. // can be rendered properly.
  159. 'locals' : {
  160. 'user' : user,
  161. 'serverHost' : serverHost
  162. }
  163. };
  164. // Email is sent here
  165. mailer.send( message, function( err, result ) {
  166. if( err ) {
  167. // XXX: Add route to resend this email
  168. console.log( 'Error sending user activation email\nError Message: '+err.Message );
  169. } else {
  170. console.log( 'Successfully sent user activation email.' );
  171. }
  172. });
  173. }
  174. // sendUserWelcome is for when a user registers and
  175. // a welcome email is sent.
  176. function sendUserWelcome( user, school ) {
  177. // If a user is not apart of a supported school, they are
  178. // sent a different template than if they are apart of a
  179. // supported school.
  180. var template = school ? 'userWelcome' : 'userWelcomeNoSchool';
  181. var message = {
  182. 'to' : user.email,
  183. 'subject' : 'Welcome to FinalsClub',
  184. 'template' : template,
  185. 'locals' : {
  186. 'user' : user,
  187. 'serverHost' : serverHost
  188. }
  189. };
  190. mailer.send( message, function( err, result ) {
  191. if( err ) {
  192. // XXX: Add route to resend this email
  193. console.log( 'Error sending user welcome email\nError Message: '+err.Message );
  194. } else {
  195. console.log( 'Successfully sent user welcome email.' );
  196. }
  197. });
  198. }
  199. // Helper middleware
  200. // These functions are used later in the routes to help
  201. // load information and variables, as well as handle
  202. // various instances like checking if a user is logged in
  203. // or not.
  204. function loggedIn( req, res, next ) {
  205. // If req.user is set, then pass on to the next function
  206. // or else alert the user with an error message.
  207. if( req.user ) {
  208. next();
  209. } else {
  210. req.flash( 'error', 'You must be logged in to access that feature!' );
  211. res.redirect( '/' );
  212. }
  213. }
  214. // This loads the user if logged in
  215. function loadUser( req, res, next ) {
  216. var sid = req.sessionID;
  217. console.log( 'got request from session ID: %s', sid );
  218. // Find a user based on their stored session id
  219. User.findOne( { session : sid }, function( err, user ) {
  220. log3(err);
  221. log3(user);
  222. // If a user is found then set req.user the contents of user
  223. // and make sure req.user.loggedIn is true.
  224. if( user ) {
  225. req.user = user;
  226. req.user.loggedIn = true;
  227. log3( 'authenticated user: '+req.user._id+' / '+req.user.email+'');
  228. // Check if a user is activated. If not, then redirec
  229. // to the homepage and tell them to check their email
  230. // for the activation email.
  231. if( req.user.activated ) {
  232. // Is the user's profile complete? If not, redirect to their profile
  233. if( ! req.user.isComplete ) {
  234. if( url.parse( req.url ).pathname != '/profile' ) {
  235. req.flash( 'info', 'Your profile is incomplete. Please complete your profile to fully activate your account.' );
  236. res.redirect( '/profile' );
  237. } else {
  238. next();
  239. }
  240. } else {
  241. next();
  242. }
  243. } else {
  244. req.flash( 'info', 'This account has not been activated. Check your email for the activation URL.' );
  245. res.redirect( '/' );
  246. }
  247. } else if('a'==='b'){
  248. console.log('never. in. behrlin.');
  249. } else {
  250. // If no user record was found, then we store the requested
  251. // path they intended to view and redirect them after they
  252. // login if it is requred.
  253. var path = url.parse( req.url ).pathname;
  254. req.session.redirect = path;
  255. // Set req.user to an empty object so it doesn't throw errors
  256. // later on that it isn't defined.
  257. req.user = {
  258. sanitized: {}
  259. };
  260. next();
  261. }
  262. });
  263. }
  264. // loadSchool is used to load a school by it's id
  265. function loadSchool( req, res, next ) {
  266. var user = req.user;
  267. var schoolName = req.params.name;
  268. console.log( 'loading a school by id' );
  269. School.findOne({'name': schoolName}).run( function( err, school ) {
  270. //sys.puts(school);
  271. if( school ) {
  272. req.school = school;
  273. // If a school is found, the user is checked to see if they are
  274. // authorized to see or interact with anything related to that
  275. // school.
  276. school.authorize( user, function( authorized ){
  277. req.school.authorized = authorized;
  278. });
  279. next();
  280. } else {
  281. // If no school is found, display an appropriate error.
  282. sendJson(res, {status: 'not_found', message: 'Invalid school specified!'} );
  283. }
  284. });
  285. }
  286. // loadSchool is used to load a course by it's id
  287. function loadCourse( req, res, next ) {
  288. var user = req.user;
  289. var courseId = req.params.id;
  290. Course.findById( courseId, function( err, course ) {
  291. if( course && !course.deleted ) {
  292. req.course = course;
  293. // If a course is found, the user is checked to see if they are
  294. // authorized to see or interact with anything related to that
  295. // school.
  296. course.authorize( user, function( authorized ) {
  297. req.course.authorized = authorized;
  298. next();
  299. });
  300. } else {
  301. // If no course is found, display an appropriate error.
  302. sendJson(res, {status: 'not_found', message: 'Invalid course specified!'} );
  303. }
  304. });
  305. }
  306. // loadLecture is used to load a lecture by it's id
  307. function loadLecture( req, res, next ) {
  308. var user = req.user;
  309. var lectureId = req.params.id;
  310. Lecture.findById( lectureId, function( err, lecture ) {
  311. if( lecture && !lecture.deleted ) {
  312. req.lecture = lecture;
  313. // If a lecture is found, the user is checked to see if they are
  314. // authorized to see or interact with anything related to that
  315. // school.
  316. lecture.authorize( user, function( authorized ) {
  317. req.lecture.authorized = authorized;
  318. next();
  319. });
  320. } else {
  321. // If no lecture is found, display an appropriate error.
  322. sendJson(res, {status: 'not_found', message: 'Invalid lecture specified!'} );
  323. }
  324. });
  325. }
  326. // loadNote is used to load a note by it's id
  327. // This is a lot more complicated than the above
  328. // due to public/private handling of notes.
  329. function loadNote( req, res, next ) {
  330. var user = req.user ? req.user : false;
  331. var noteId = req.params.id;
  332. Note.findById( noteId, function( err, note ) {
  333. // If a note is found, and user is set, check if
  334. // user is authorized to interact with that note.
  335. if( note && user && !note.deleted ) {
  336. note.authorize( user, function( auth ) {
  337. if( auth ) {
  338. // If authorzied, then set req.note to be used later
  339. req.note = note;
  340. next();
  341. } else if ( note.public ) {
  342. // If not authorized, but the note is public, then
  343. // designate the note read only (RO) and store req.note
  344. req.RO = true;
  345. req.note = note;
  346. next();
  347. } else {
  348. // If the user is not authorized and the note is private
  349. // then display and error.
  350. sendJson(res, {status: 'error', message: 'You do not have permission to access that note.'} );
  351. }
  352. })
  353. } else if ( note && note.public && !note.deleted ) {
  354. // If note is found, but user is not set because they are not
  355. // logged in, and the note is public, set the note to read only
  356. // and store the note for later.
  357. req.note = note;
  358. req.RO = true;
  359. next();
  360. } else if ( note && !note.public && !note.deleted ) {
  361. // If the note is found, but user is not logged in and the note is
  362. // not public, then ask them to login to view the note. Once logged
  363. // in they will be redirected to the note, at which time authorization
  364. // handling will be put in effect above.
  365. //req.session.redirect = '/note/' + note._id;
  366. sendJson(res, {status: 'error', message: 'You must be logged in to view that note.'} );
  367. } else {
  368. // No note was found
  369. sendJson(res, {status: 'error', message: 'Invalid note specified!'} );
  370. }
  371. });
  372. }
  373. function checkAjax( req, res, next ) {
  374. if ( req.xhr ) {
  375. next();
  376. } else {
  377. res.sendfile( 'public/index.html', function(err){
  378. if(err){
  379. console.log(err);
  380. }
  381. });
  382. }
  383. }
  384. // Dynamic Helpers are loaded automatically into views
  385. app.dynamicHelpers( {
  386. // express-messages is for flash messages for easy
  387. // errors and information display
  388. 'messages' : require( 'express-messages' ),
  389. // By default the req object isn't sen't to views
  390. // during rendering, this allows you to use the
  391. // user object if available in views.
  392. 'user' : function( req, res ) {
  393. return req.user;
  394. },
  395. // Same, this allows session to be available in views.
  396. 'session' : function( req, res ) {
  397. return req.session;
  398. }
  399. });
  400. function sendJson( res, obj ) {
  401. res.header('Cache-Control', 'no-cache, no-store');
  402. res.json(obj);
  403. }
  404. // Schools list
  405. // Used to display all available schools
  406. // Public with some private information
  407. app.get( '/schools', checkAjax, loadUser, function( req, res ) {
  408. var user = req.user;
  409. var schoolList = [];
  410. // Find all schools and sort by name
  411. // XXX mongoose's documentation on sort is extremely poor, tread carefully
  412. School.find( {} ).sort( 'name', '1' ).run( function( err, schools ) {
  413. if( schools ) {
  414. // If schools are found, loop through them gathering any courses that are
  415. // associated with them and then render the page with that information.
  416. var schools_todo = schools.length;
  417. schools.map(function (school) {
  418. Course.find( { 'school': school.id } ).run(function (err, courses) {
  419. school.courses_length = courses.length
  420. schools_todo -= 1;
  421. if (schools_todo <= 0) {
  422. sendJson(res, { 'user': user.sanitized, 'schools': schools.map( function(s) {
  423. var school = {
  424. _id: s._id,
  425. name: s.name,
  426. description: s.description,
  427. url: s.url,
  428. slug: s.slug,
  429. courses: s.courses_length,
  430. courseNum: s.courseNum
  431. };
  432. return school;
  433. })
  434. });
  435. }
  436. });
  437. });
  438. } else {
  439. // If no schools have been found, display none
  440. //res.render( 'schools', { 'schools' : [] } );
  441. sendJson(res, { 'schools' : [] , 'user': user.sanitized });
  442. }
  443. });
  444. });
  445. app.get( '/school/:name', checkAjax, loadUser, loadSchool, function( req, res ) {
  446. var school = req.school;
  447. var user = req.user;
  448. console.log("Loading a school");
  449. school.authorize( user, function( authorized ) {
  450. // This is used to display interface elements for those users
  451. // that are are allowed to see th)m, for instance a 'New Course' button.
  452. var sanitizedSchool = school.sanitized;
  453. //var sanitizedSchool = {
  454. // _id: school.id,
  455. // name: school.name,
  456. // description: school.description,
  457. // url: school.url
  458. //};
  459. sanitizedSchool.authorized = authorized;
  460. // Find all courses for school by it's id and sort by name
  461. Course.find( { 'school' : school._id } ).sort( 'name', '1' ).run( function( err, courses ) {
  462. // If any courses are found, set them to the appropriate school, otherwise
  463. // leave empty.
  464. if( courses.length > 0 ) {
  465. sanitizedSchool.courses = courses.filter(function(course) {
  466. if (!course.deleted) return course;
  467. }).map(function(course) {
  468. return course.sanitized;
  469. });
  470. } else {
  471. school.courses = [];
  472. }
  473. // This tells async (the module) that each iteration of forEach is
  474. // done and will continue to call the rest until they have all been
  475. // completed, at which time the last function below will be called.
  476. sendJson(res, { 'school': sanitizedSchool, 'user': user.sanitized })
  477. });
  478. });
  479. });
  480. // Recieves new course form
  481. app.post( '/school/:id', checkAjax, loadUser, loadSchool, function( req, res ) {
  482. var school = req.school;
  483. // Creates new course from Course Schema
  484. var course = new Course;
  485. // Gathers instructor information from form
  486. var instructorEmail = req.body.email.toLowerCase();
  487. var instructorName = req.body.instructorName;
  488. if( ( ! school ) || ( ! school.authorized ) ) {
  489. return sendJson(res, {status: 'error', message: 'There was a problem trying to create a course'})
  490. }
  491. if ( !instructorName ) {
  492. return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
  493. }
  494. if ( ( instructorEmail === '' ) || ( !isValidEmail( instructorEmail ) ) ) {
  495. return sendJson(res, {status: 'error', message:'Please enter a valid email'} );
  496. }
  497. // Fill out the course with information from the form
  498. course.number = req.body.number;
  499. course.name = req.body.name;
  500. course.description = req.body.description;
  501. course.school = school._id;
  502. course.creator = req.user._id;
  503. course.subject = req.body.subject;
  504. course.department = req.body.department;
  505. // Check if a user exists with the instructorEmail, if not then create
  506. // a new user and send them an instructor welcome email.
  507. User.findOne( { 'email' : instructorEmail }, function( err, user ) {
  508. if ( !user ) {
  509. var user = new User;
  510. user.name = instructorName
  511. user.email = instructorEmail;
  512. user.affil = 'Instructor';
  513. user.school = school.name;
  514. user.activated = false;
  515. // Once the new user information has been completed, save the user
  516. // to the database then email them the instructor welcome email.
  517. user.save(function( err ) {
  518. // If there was an error saving the instructor, prompt the user to fill out
  519. // the information again.
  520. if ( err ) {
  521. return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
  522. } else {
  523. var message = {
  524. to : user.email,
  525. 'subject' : 'A non-profit open education initiative',
  526. 'template' : 'instructorInvite',
  527. 'locals' : {
  528. 'course' : course,
  529. 'school' : school,
  530. 'user' : user,
  531. 'serverHost' : serverHost
  532. }
  533. };
  534. mailer.send( message, function( err, result ) {
  535. if( err ) {
  536. console.log( 'Error inviting instructor to course!' );
  537. } else {
  538. console.log( 'Successfully invited instructor to course.' );
  539. }
  540. });
  541. // After emails are sent, set the courses instructor to the
  542. // new users id and then save the course to the database.
  543. course.instructor = user._id;
  544. course.save( function( err ) {
  545. if( err ) {
  546. return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
  547. } else {
  548. // Once the course has been completed email the admin with information
  549. // on the course and new instructor
  550. var message = {
  551. to : ADMIN_EMAIL,
  552. 'subject' : school.name+' has a new course: '+course.name,
  553. 'template' : 'newCourse',
  554. 'locals' : {
  555. 'course' : course,
  556. 'instructor' : user,
  557. 'user' : req.user,
  558. 'serverHost' : serverHost
  559. }
  560. };
  561. mailer.send( message, function( err, result ) {
  562. if ( err ) {
  563. console.log( 'Error sending new course email to info@finalsclub.org' )
  564. } else {
  565. console.log( 'Successfully invited instructor to course')
  566. }
  567. })
  568. // Redirect the user to the schools page where they can see
  569. // their new course.
  570. // XXX Redirect to the new course instead
  571. return sendJson(res, {status: 'ok', message: 'Course created'} )
  572. }
  573. });
  574. }
  575. })
  576. } else {
  577. // If the user exists, then check if they are already and instructor
  578. if (user.affil === 'Instructor') {
  579. // If they are an instructor, then save the course with the appropriate
  580. // information and email the admin.
  581. course.instructor = user._id;
  582. course.save( function( err ) {
  583. if( err ) {
  584. // XXX better validation
  585. return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
  586. } else {
  587. var message = {
  588. to : ADMIN_EMAIL,
  589. 'subject' : school.name+' has a new course: '+course.name,
  590. 'template' : 'newCourse',
  591. 'locals' : {
  592. 'course' : course,
  593. 'instructor' : user,
  594. 'user' : req.user,
  595. 'serverHost' : serverHost
  596. }
  597. };
  598. mailer.send( message, function( err, result ) {
  599. if ( err ) {
  600. console.log( 'Error sending new course email to info@finalsclub.org' )
  601. } else {
  602. console.log( 'Successfully invited instructor to course')
  603. }
  604. })
  605. // XXX Redirect to the new course instead
  606. return sendJson(res, {status: 'ok', message: 'Course created'} )
  607. }
  608. });
  609. } else {
  610. // The existing user isn't an instructor, so the user is notified of the error
  611. // and the course isn't created.
  612. sendJson(res, {status: 'error', message: 'The existing user\'s email you entered is not an instructor'} )
  613. }
  614. }
  615. })
  616. });
  617. // Individual Course Listing
  618. // Public with private information
  619. app.get( '/course/:id', checkAjax, loadUser, loadCourse, function( req, res ) {
  620. var userId = req.user._id;
  621. var course = req.course;
  622. // Check if the user is subscribed to the course
  623. // XXX Not currently used for anything
  624. //var subscribed = course.subscribed( userId );
  625. // Find lectures associated with this course and sort by name
  626. Lecture.find( { 'course' : course._id } ).sort( 'name', '1' ).run( function( err, lectures ) {
  627. // Get course instructor information using their id
  628. User.findById( course.instructor, function( err, instructor ) {
  629. // Render course and lectures
  630. var sanitizedInstructor = instructor.sanitized;
  631. var sanitizedCourse = course.sanitized;
  632. if (!course.authorized) {
  633. delete sanitizedInstructor.email;
  634. } else {
  635. sanitizedCourse.authorized = course.authorized;
  636. }
  637. sendJson(res, { 'course' : sanitizedCourse, 'instructor': sanitizedInstructor, 'lectures' : lectures.map(function(lecture) { return lecture.sanitized })} );
  638. })
  639. });
  640. });
  641. // Recieve New Lecture Form
  642. app.post( '/course/:id', checkAjax, loadUser, loadCourse, function( req, res ) {
  643. var course = req.course;
  644. // Create new lecture from Lecture schema
  645. var lecture = new Lecture;
  646. if( ( ! course ) || ( ! course.authorized ) ) {
  647. return sendJson(res, {status: 'error', message: 'There was a problem trying to create a lecture'})
  648. }
  649. // Populate lecture with form data
  650. lecture.name = req.body.name;
  651. lecture.date = req.body.date;
  652. lecture.course = course._id;
  653. lecture.creator = req.user._id;
  654. // Save lecture to database
  655. lecture.save( function( err ) {
  656. if( err ) {
  657. // XXX better validation
  658. sendJson(res, {status: 'error', message: 'Invalid parameters!'} );
  659. } else {
  660. sendJson(res, {status: 'ok', message: 'Created new lecture'} );
  661. }
  662. });
  663. });
  664. // Edit Course
  665. app.get( '/course/:id/edit', loadUser, loadCourse, function( req, res) {
  666. var course = req.course;
  667. var user = req.user;
  668. if ( user.admin ) {
  669. res.render( 'course/new', {course: course} )
  670. } else {
  671. req.flash( 'error', 'You don\'t have permission to do that' )
  672. res.redirect( '/schools' );
  673. }
  674. })
  675. // Recieve Course Edit Form
  676. app.post( '/course/:id/edit', loadUser, loadCourse, function( req, res ) {
  677. var course = req.course;
  678. var user = req.user;
  679. if (user.admin) {
  680. var courseChanges = req.body;
  681. course.number = courseChanges.number;
  682. course.name = courseChanges.name;
  683. course.description = courseChanges.description;
  684. course.department = courseChanges.department;
  685. course.save(function(err) {
  686. if (err) {
  687. req.flash( 'error', 'There was an error saving the course' );
  688. }
  689. res.redirect( '/course/'+ course._id.toString());
  690. })
  691. } else {
  692. req.flash( 'error', 'You don\'t have permission to do that' )
  693. res.redirect( '/schools' );
  694. }
  695. });
  696. // Delete Course
  697. app.get( '/course/:id/delete', loadUser, loadCourse, function( req, res) {
  698. var course = req.course;
  699. var user = req.user;
  700. if ( user.admin ) {
  701. course.delete(function( err ) {
  702. if ( err ) req.flash( 'info', 'There was a problem removing course: ' + err )
  703. else req.flash( 'info', 'Successfully removed course' )
  704. res.redirect( '/schools' );
  705. });
  706. } else {
  707. req.flash( 'error', 'You don\'t have permission to do that' )
  708. res.redirect( '/schools' );
  709. }
  710. })
  711. // Subscribe to course
  712. // XXX Not currently used for anything
  713. app.get( '/course/:id/subscribe', loadUser, loadCourse, function( req, res ) {
  714. var course = req.course;
  715. var userId = req.user._id;
  716. course.subscribe( userId, function( err ) {
  717. if( err ) {
  718. req.flash( 'error', 'Error subscribing to course!' );
  719. }
  720. res.redirect( '/course/' + course._id );
  721. });
  722. });
  723. // Unsubscribe from course
  724. // XXX Not currently used for anything
  725. app.get( '/course/:id/unsubscribe', loadUser, loadCourse, function( req, res ) {
  726. var course = req.course;
  727. var userId = req.user._id;
  728. course.unsubscribe( userId, function( err ) {
  729. if( err ) {
  730. req.flash( 'error', 'Error unsubscribing from course!' );
  731. }
  732. res.redirect( '/course/' + course._id );
  733. });
  734. });
  735. // Display individual lecture and related notes
  736. app.get( '/lecture/:id', checkAjax, loadUser, loadLecture, function( req, res ) {
  737. var lecture = req.lecture;
  738. // Grab the associated course
  739. // XXX this should be done with DBRefs eventually
  740. Course.findById( lecture.course, function( err, course ) {
  741. if( course ) {
  742. // If course is found, find instructor information to be displayed on page
  743. User.findById( course.instructor, function( err, instructor ) {
  744. // Pull out our notes
  745. Note.find( { 'lecture' : lecture._id } ).sort( 'name', '1' ).run( function( err, notes ) {
  746. if ( !req.user.loggedIn || !req.lecture.authorized ) {
  747. // Loop through notes and only return those that are public if the
  748. // user is not logged in or not authorized for that lecture
  749. notes = notes.filter(function( note ) {
  750. if ( note.public ) return note;
  751. })
  752. }
  753. var sanitizedInstructor = instructor.sanitized;
  754. var sanitizedLecture = lecture.sanitized;
  755. if (!lecture.authorized) {
  756. delete sanitizedInstructor.email;
  757. } else {
  758. sanitizedLecture.authorized = lecture.authorized;
  759. }
  760. sendJson(res, {
  761. 'lecture' : sanitizedLecture,
  762. 'course' : course.sanitized,
  763. 'instructor' : sanitizedInstructor,
  764. 'notes' : notes.map(function(note) {
  765. return note.sanitized;
  766. })
  767. });
  768. });
  769. })
  770. } else {
  771. sendJson(res, { status: 'not_found', msg: 'This course is orphaned' })
  772. }
  773. });
  774. });
  775. // Recieve new note form
  776. app.post( '/lecture/:id', checkAjax, loadUser, loadLecture, function( req, res ) {
  777. var lecture = req.lecture;
  778. if( ( ! lecture ) || ( ! lecture.authorized ) ) {
  779. return sendJson(res, {status: 'error', message: 'There was a problem trying to create a note pad'})
  780. }
  781. // Create note from Note schema
  782. var note = new Note;
  783. // Populate note from form data
  784. note.name = req.body.name;
  785. note.date = req.body.date;
  786. note.lecture = lecture._id;
  787. note.public = req.body.private ? false : true;
  788. note.creator = req.user._id;
  789. // Save note to database
  790. note.save( function( err ) {
  791. if( err ) {
  792. // XXX better validation
  793. sendJson(res, {status: 'error', message: 'There was a problem trying to create a note pad'})
  794. } else {
  795. sendJson(res, {status: 'ok', message: 'Successfully created a new note pad'})
  796. }
  797. });
  798. });
  799. // Display individual note page
  800. app.get( '/note/:id', /*checkAjax,*/ loadUser, loadNote, function( req, res ) {
  801. var note = req.note;
  802. // Set read only id for etherpad-lite or false for later check
  803. var roID = note.roID || false;
  804. var lectureId = note.lecture;
  805. // Count the amount of visits, but only once per session
  806. if ( req.session.visited ) {
  807. if ( req.session.visited.indexOf( note._id.toString() ) == -1 ) {
  808. req.session.visited.push( note._id );
  809. note.addVisit();
  810. }
  811. } else {
  812. req.session.visited = [];
  813. req.session.visited.push( note._id );
  814. note.addVisit();
  815. }
  816. // If a read only id exists process note
  817. if (roID) {
  818. processReq();
  819. } else {
  820. // If read only id doesn't, then fetch the read only id from the database and then
  821. // process note.
  822. // XXX Soon to be depracated due to a new API in etherpad that makes for a
  823. // much cleaner solution.
  824. db.open('mongodb://' + app.set( 'dbHost' ) + '/etherpad/etherpad', function( err, epl ) {
  825. epl.findOne( { key: 'pad2readonly:' + note._id }, function(err, record) {
  826. if ( record ) {
  827. roID = record.value.replace(/"/g, '');
  828. } else {
  829. roID = false;
  830. }
  831. processReq();
  832. })
  833. })
  834. }
  835. function processReq() {
  836. // Find lecture
  837. Lecture.findById( lectureId, function( err, lecture ) {
  838. if( ! lecture ) {
  839. req.flash( 'error', 'That notes page is orphaned!' );
  840. res.redirect( '/' );
  841. }
  842. // Find notes based on lecture id, which will be displayed in a dropdown
  843. // on the page
  844. Note.find( { 'lecture' : lecture._id }, function( err, otherNotes ) {
  845. /*
  846. sendJson(res, {
  847. 'host' : serverHost,
  848. 'note' : note.sanitized,
  849. 'lecture' : lecture.sanitized,
  850. 'otherNotes' : otherNotes.map(function(note) {
  851. return note.sanitized;
  852. }),
  853. 'RO' : req.RO,
  854. 'roID' : roID,
  855. });
  856. */
  857. if( !req.RO ) {
  858. // User is logged in and sees full notepad
  859. res.render( 'notes/index', {
  860. 'layout' : 'noteLayout',
  861. 'host' : serverHost,
  862. 'note' : note,
  863. 'lecture' : lecture,
  864. 'otherNotes' : otherNotes,
  865. 'RO' : false,
  866. 'roID' : roID,
  867. 'stylesheets' : [ 'dropdown.css', 'fc2.css' ],
  868. 'javascripts' : [ 'dropdown.js', 'counts.js', 'backchannel.js', 'jquery.tmpl.min.js' ]
  869. });
  870. } else {
  871. // User is not logged in and sees notepad that is public
  872. res.render( 'notes/public', {
  873. 'layout' : 'noteLayout',
  874. 'host' : serverHost,
  875. 'note' : note,
  876. 'otherNotes' : otherNotes,
  877. 'roID' : roID,
  878. 'lecture' : lecture,
  879. 'stylesheets' : [ 'dropdown.css', 'fc2.css' ],
  880. 'javascripts' : [ 'dropdown.js', 'counts.js', 'backchannel.js', 'jquery.tmpl.min.js' ]
  881. });
  882. }
  883. });
  884. });
  885. }
  886. });
  887. // Static pages and redirects
  888. /*
  889. app.get( '/about', loadUser, function( req, res ) {
  890. res.redirect( 'http://blog.finalsclub.org/about.html' );
  891. });
  892. app.get( '/press', loadUser, function( req, res ) {
  893. res.render( 'static/press' );
  894. });
  895. app.get( '/conduct', loadUser, function( req, res ) {
  896. res.render( 'static/conduct' );
  897. });
  898. app.get( '/legal', loadUser, function( req, res ) {
  899. res.redirect( 'http://blog.finalsclub.org/legal.html' );
  900. });
  901. app.get( '/contact', loadUser, function( req, res ) {
  902. res.redirect( 'http://blog.finalsclub.org/contact.html' );
  903. });
  904. app.get( '/privacy', loadUser, function( req, res ) {
  905. res.render( 'static/privacy' );
  906. });
  907. */
  908. // Authentication routes
  909. // These are used for logging in, logging out, registering
  910. // and other user authentication purposes
  911. // Render login page
  912. /*
  913. app.get( '/login', function( req, res ) {
  914. log3("get login page")
  915. res.render( 'login' );
  916. });
  917. */
  918. app.get( '/checkuser', checkAjax, loadUser, function( req, res ) {
  919. sendJson(res, {user: req.user.sanitized});
  920. });
  921. // Recieve login form
  922. app.post( '/login', checkAjax, function( req, res ) {
  923. var email = req.body.email;
  924. var password = req.body.password;
  925. log3("post login ...")
  926. // Find user from email
  927. User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
  928. log3(err)
  929. log3(user)
  930. // If user exists, check if activated, if not notify them and send them to
  931. // the login form
  932. if( user ) {
  933. if( ! user.activated ) {
  934. // (undocumented) markdown-esque link functionality in req.flash
  935. req.session.activateCode = user._id;
  936. sendJson(res, {status: 'error', message: 'This account isn\'t activated.'} );
  937. } else {
  938. // If user is activated, check if their password is correct
  939. if( user.authenticate( password ) ) {
  940. log3("pass ok")
  941. var sid = req.sessionID;
  942. user.session = sid;
  943. // Set the session then save the user to the database
  944. user.save( function() {
  945. var redirect = req.session.redirect;
  946. // login complete, remember the user's email for next time
  947. req.session.email = email;
  948. // alert the successful login
  949. sendJson(res, {status: 'ok', message:'Successfully logged in!'} );
  950. // redirect to profile if we don't have a stashed request
  951. //res.redirect( redirect || '/profile' );
  952. });
  953. } else {
  954. // Notify user of bad login
  955. sendJson(res, {status: 'error', message: 'Invalid login!'} );
  956. //res.render( 'login' );
  957. }
  958. }
  959. } else {
  960. // Notify user of bad login
  961. log3("bad login")
  962. sendJson(res, {status: 'error', message: 'Invalid login!'} );
  963. //res.render( 'login' );
  964. }
  965. });
  966. });
  967. // Recieve reset password request form
  968. app.post( '/resetpass', checkAjax, function( req, res ) {
  969. log3("post resetpw");
  970. var email = req.body.email
  971. // Search for user
  972. User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
  973. if( user ) {
  974. // If user exists, create reset code
  975. var resetPassCode = hat(64);
  976. user.setResetPassCode(resetPassCode);
  977. // Construct url that the user can then click to reset password
  978. var resetPassUrl = 'http://' + serverHost + ((app.address().port != 80)? ':'+app.address().port: '') + '/resetpw/' + resetPassCode;
  979. // Save user to database
  980. user.save( function( err ) {
  981. log3('save '+user.email);
  982. // Construct email and send it to the user
  983. var message = {
  984. 'to' : user.email,
  985. 'subject' : 'Your FinalsClub.org Password has been Reset!',
  986. 'template' : 'userPasswordReset',
  987. 'locals' : {
  988. 'resetPassCode' : resetPassCode,
  989. 'resetPassUrl' : resetPassUrl
  990. }
  991. };
  992. mailer.send( message, function( err, result ) {
  993. if( err ) {
  994. // XXX: Add route to resend this email
  995. console.log( 'Error sending user password reset email!' );
  996. } else {
  997. console.log( 'Successfully sent user password reset email.' );
  998. }
  999. });
  1000. // Render request success page
  1001. sendJson(res, {status: 'ok', message: 'Your password has been reset. An email has been sent to ' + email })
  1002. });
  1003. } else {
  1004. // Notify of error
  1005. sendJson(res, {status: 'error', message: 'We were unable to reset the password using that email address. Please try again.' })
  1006. }
  1007. });
  1008. });
  1009. // Recieve reset password form
  1010. app.post( '/resetpw/:id', checkAjax, function( req, res ) {
  1011. log3("post resetpw.code");
  1012. var resetPassCode = req.params.id
  1013. var email = req.body.email
  1014. var pass1 = req.body.pass1
  1015. var pass2 = req.body.pass2
  1016. // Find user by email
  1017. User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
  1018. var valid = false;
  1019. // If user exists, and the resetPassCode is valid, pass1 and pass2 match, then
  1020. // save user with new password and display success message.
  1021. if( user ) {
  1022. var valid = user.resetPassword(resetPassCode, pass1, pass2);
  1023. if (valid) {
  1024. user.save( function( err ) {
  1025. sendJson(res, {status: 'ok', message: 'Your password has been reset. You can now login with your the new password you just created.'})
  1026. });
  1027. }
  1028. }
  1029. // If there was a problem, notify user
  1030. if (!valid) {
  1031. sendJson(res, {status: 'error', message: 'We were unable to reset the password. Please try again.' })
  1032. }
  1033. });
  1034. });
  1035. // Display registration page
  1036. /*
  1037. app.get( '/register', function( req, res ) {
  1038. log3("get reg page");
  1039. // Populate school dropdown list
  1040. School.find( {} ).sort( 'name', '1' ).run( function( err, schools ) {
  1041. res.render( 'register', { 'schools' : schools } );
  1042. })
  1043. });
  1044. */
  1045. // Recieve registration form
  1046. app.post( '/register', checkAjax, function( req, res ) {
  1047. var sid = req.sessionId;
  1048. // Create new user from User schema
  1049. var user = new User;
  1050. // Populate user from form
  1051. user.email = req.body.email.toLowerCase();
  1052. user.password = req.body.password;
  1053. user.session = sid;
  1054. // If school is set to other, then fill in school as what the user entered
  1055. user.school = req.body.school === 'Other' ? req.body.otherSchool : req.body.school;
  1056. user.name = req.body.name;
  1057. user.affil = req.body.affil;
  1058. user.activated = false;
  1059. // Validate email
  1060. if ( ( user.email === '' ) || ( !isValidEmail( user.email ) ) ) {
  1061. return sendJson(res, {status: 'error', message: 'Please enter a valid email'} );
  1062. }
  1063. // Check if password is greater than 6 characters, otherwise notify user
  1064. if ( req.body.password.length < 6 ) {
  1065. return sendJson(res, {status: 'error', message: 'Please enter a password longer than eight characters'} );
  1066. }
  1067. // Pull out hostname from email
  1068. var hostname = user.email.split( '@' ).pop();
  1069. // Check if email is from one of the special domains
  1070. if( /^(finalsclub.org)$/.test( hostname ) ) {
  1071. user.admin = true;
  1072. }
  1073. // Save user to database
  1074. user.save( function( err ) {
  1075. // If error, check if it is because the user already exists, if so
  1076. // get the user information and let them know
  1077. if ( err ) {
  1078. if( /dup key/.test( err.message ) ) {
  1079. // attempting to register an existing address
  1080. User.findOne({ 'email' : user.email }, function(err, result ) {
  1081. if (result.activated) {
  1082. // If activated, make sure they know how to contact the admin
  1083. return sendJson(res, {status: 'error', message: 'There is already someone registered with this email, if this is in error contact info@finalsclub.org for help'} );
  1084. } else {
  1085. // If not activated, direct them to the resendActivation page
  1086. return sendJson(res, {status: 'error', message: 'There is already someone registered with this email, if this is you, please check your email for the activation code'} );
  1087. }
  1088. });
  1089. } else {
  1090. // If any other type of error, prompt them to enter the registration again
  1091. return sendJson(res, {status: 'error', message: 'An error occurred during registration.'} );
  1092. }
  1093. } else {
  1094. // send user activation email
  1095. sendUserActivation( user );
  1096. // Check if the hostname matches any in the approved schools
  1097. School.findOne( { 'hostnames' : hostname }, function( err, school ) {
  1098. if( school ) {
  1099. // If there is a match, send associated welcome message
  1100. sendUserWelcome( user, true );
  1101. log3('school recognized '+school.name);
  1102. // If no users exist for the school, create empty array
  1103. if (!school.users) school.users = [];
  1104. // Add user to the school
  1105. school.users.push( user._id );
  1106. // Save school to the database
  1107. school.save( function( err ) {
  1108. log3('school.save() done');
  1109. // Notify user that they have been added to the school
  1110. sendJson(res, {status: 'ok', message: 'You have automatically been added to the ' + school.name + ' network. Please check your email for the activation link'} );
  1111. });
  1112. // Construct admin email about user registration
  1113. var message = {
  1114. 'to' : ADMIN_EMAIL,
  1115. 'subject' : 'FC User Registration : User added to ' + school.name,
  1116. 'template' : 'userSchool',
  1117. 'locals' : {
  1118. 'user' : user
  1119. }
  1120. }
  1121. } else {
  1122. // If there isn't a match, send associated welcome message
  1123. sendUserWelcome( user, false );
  1124. // Tell user to check for activation link
  1125. sendJson(res, {status: 'ok', message: 'Your account has been created, please check your email for the activation link'} );
  1126. // Construct admin email about user registration
  1127. var message = {
  1128. 'to' : ADMIN_EMAIL,
  1129. 'subject' : 'FC User Registration : Email did not match any schools',
  1130. 'template' : 'userNoSchool',
  1131. 'locals' : {
  1132. 'user' : user
  1133. }
  1134. }
  1135. }
  1136. // Send email to admin
  1137. mailer.send( message, function( err, result ) {
  1138. if ( err ) {
  1139. console.log( 'Error sending user has no school email to admin\nError Message: '+err.Message );
  1140. } else {
  1141. console.log( 'Successfully sent user has no school email to admin.' );
  1142. }
  1143. })
  1144. });
  1145. }
  1146. });
  1147. });
  1148. // Display resendActivation request page
  1149. app.get( '/resendActivation', function( req, res ) {
  1150. var activateCode = req.session.activateCode;
  1151. // Check if user exists by activateCode set in their session
  1152. User.findById( activateCode, function( err, user ) {
  1153. if( ( ! user ) || ( user.activated ) ) {
  1154. res.redirect( '/' );
  1155. } else {
  1156. // Send activation and redirect to login
  1157. sendUserActivation( user );
  1158. req.flash( 'info', 'Your activation code has been resent.' );
  1159. res.redirect( '/login' );
  1160. }
  1161. });
  1162. });
  1163. // Display activation page
  1164. app.get( '/activate/:code', checkAjax, function( req, res ) {
  1165. var code = req.params.code;
  1166. // XXX could break this out into a middleware
  1167. if( ! code ) {
  1168. return sendJson(res, {status:'error', message: 'Invalid activation code!'} );
  1169. }
  1170. // Find user by activation code
  1171. User.findById( code, function( err, user ) {
  1172. if( err || ! user ) {
  1173. // If not found, notify user of invalid code
  1174. sendJson(res, {status:'error', message:'Invalid activation code!'} );
  1175. } else {
  1176. // If valid, then activate user
  1177. user.activated = true;
  1178. // Regenerate our session and log in as the new user
  1179. req.session.regenerate( function() {
  1180. user.session = req.sessionID;
  1181. // Save user to database
  1182. user.save( function( err ) {
  1183. if( err ) {
  1184. sendJson(res, {status: 'error', message: 'Unable to activate account.'} );
  1185. } else {
  1186. sendJson(res, {status: 'info', message: 'Account successfully activated. Please complete your profile.'} );
  1187. }
  1188. });
  1189. });
  1190. }
  1191. });
  1192. });
  1193. // Logut user
  1194. app.get( '/logout', checkAjax, function( req, res ) {
  1195. sys.puts("logging out");
  1196. var sid = req.sessionID;
  1197. // Find user by session id
  1198. User.findOne( { 'session' : sid }, function( err, user ) {
  1199. if( user ) {
  1200. // Empty out session id
  1201. user.session = '';
  1202. // Save user to database
  1203. user.save( function( err ) {
  1204. sendJson(res, {status: 'ok', message: 'Successfully logged out'});
  1205. });
  1206. } else {
  1207. sendJson(res, {status: 'ok', message: ''});
  1208. }
  1209. });
  1210. });
  1211. // Recieve profile edit page form
  1212. app.post( '/profile', checkAjax, loadUser, loggedIn, function( req, res ) {
  1213. var user = req.user;
  1214. var fields = req.body;
  1215. var error = false;
  1216. var wasComplete = user.isComplete;
  1217. if( ! fields.name ) {
  1218. return sendJson(res, {status: 'error', message: 'Please enter a valid name!'} );
  1219. } else {
  1220. user.name = fields.name;
  1221. }
  1222. if( [ 'Student', 'Teachers Assistant' ].indexOf( fields.affiliation ) == -1 ) {
  1223. return sendJson(res, {status: 'error', message: 'Please select a valid affiliation!'} );
  1224. } else {
  1225. user.affil = fields.affiliation;
  1226. }
  1227. if( fields.existingPassword || fields.newPassword || fields.newPasswordConfirm ) {
  1228. // changing password
  1229. if( ( ! user.hashed ) || user.authenticate( fields.existingPassword ) ) {
  1230. if( fields.newPassword === fields.newPasswordConfirm ) {
  1231. // test password strength?
  1232. user.password = fields.newPassword;
  1233. } else {
  1234. return sendJson(res, {status: 'error', message: 'Mismatch in new password!'} );
  1235. }
  1236. } else {
  1237. return sendJson(res, {status: 'error', message: 'Please supply your existing password.'} );
  1238. }
  1239. }
  1240. user.major = fields.major;
  1241. user.bio = fields.bio;
  1242. user.showName = ( fields.showName ? true : false );
  1243. user.save( function( err ) {
  1244. if( err ) {
  1245. sendJson(res, {status: 'error', message: 'Unable to save user profile!'} );
  1246. } else {
  1247. if( ( user.isComplete ) && ( ! wasComplete ) ) {
  1248. sendJson(res, {status: 'ok', message: 'Your account is now fully activated. Thank you for joining FinalsClub!'} );
  1249. } else {
  1250. sendJson(res, {status:'ok', message:'Your profile was successfully updated!'} );
  1251. }
  1252. }
  1253. });
  1254. });
  1255. // Old Notes
  1256. function loadSubject( req, res, next ) {
  1257. if( url.parse( req.url ).pathname.match(/subject/) ) {
  1258. ArchivedSubject.findOne({id: req.params.id }, function(err, subject) {
  1259. if ( err || !subject) {
  1260. sendJson(res, {status: 'not_found', message: 'Subject with this ID does not exist'} )
  1261. } else {
  1262. req.subject = subject;
  1263. next()
  1264. }
  1265. })
  1266. } else {
  1267. next()
  1268. }
  1269. }
  1270. function loadOldCourse( req, res, next ) {
  1271. if( url.parse( req.url ).pathname.match(/course/) ) {
  1272. ArchivedCourse.findOne({id: req.params.id }, function(err, course) {
  1273. if ( err || !course ) {
  1274. sendJson(res, {status: 'not_found', message: 'Course with this ID does not exist'} )
  1275. } else {
  1276. req.course = course;
  1277. next()
  1278. }
  1279. })
  1280. } else {
  1281. next()
  1282. }
  1283. }
  1284. var featuredCourses = [
  1285. {name: 'The Human Mind', 'id': 1563},
  1286. {name: 'Justice', 'id': 797},
  1287. {name: 'Protest Literature', 'id': 1681},
  1288. {name: 'Animal Cognition', 'id': 681},
  1289. {name: 'Positive Psychology', 'id': 1793},
  1290. {name: 'Social Psychology', 'id': 660},
  1291. {name: 'The Book from Gutenberg to the Internet', 'id': 1439},
  1292. {name: 'Cyberspace in Court', 'id': 1446},
  1293. {name: 'Nazi Cinema', 'id': 2586},
  1294. {name: 'Media and the American Mind', 'id': 2583},
  1295. {name: 'Social Thought in Modern America', 'id': 2585},
  1296. {name: 'Major British Writers II', 'id': 869},
  1297. {name: 'Civil Procedure', 'id': 2589},
  1298. {name: 'Evidence', 'id': 2590},
  1299. {name: 'Management of Industrial and Nonprofit Organizations', 'id': 2591},
  1300. ];
  1301. app.get( '/learn', loadUser, function( req, res ) {
  1302. res.render( 'archive/learn', { 'courses' : featuredCourses } );
  1303. })
  1304. app.get( '/learn/random', checkAjax, function( req, res ) {
  1305. sendJson(res, {status: 'ok', data: '/archive/course/'+ featuredCourses[Math.floor(Math.random()*featuredCourses.length)].id });
  1306. })
  1307. app.get( '/archive', checkAjax, loadUser, function( req, res ) {
  1308. ArchivedSubject.find({}).sort( 'name', '1' ).run( function( err, subjects ) {
  1309. if ( err || subjects.length === 0) {
  1310. sendJson(res, {status: 'error', message: 'There was a problem gathering the archived courses, please try again later.'} );
  1311. } else {
  1312. sendJson(res, { 'subjects' : subjects, 'user': req.user.sanitized } );
  1313. }
  1314. })
  1315. })
  1316. app.get( '/archive/subject/:id', checkAjax, loadUser, loadSubject, function( req, res ) {
  1317. ArchivedCourse.find({subject_id: req.params.id}).sort('name', '1').run(function(err, courses) {
  1318. if ( err || courses.length === 0 ) {
  1319. sendJson(res, {status: 'not_found', message: 'There are no archived courses'} );
  1320. } else {
  1321. sendJson(res, { 'courses' : courses, 'subject': req.subject, 'user': req.user.sanitized } );
  1322. }
  1323. })
  1324. })
  1325. app.get( '/archive/course/:id', checkAjax, loadUser, loadOldCourse, function( req, res ) {
  1326. ArchivedNote.find({course_id: req.params.id}).sort('name', '1').run(function(err, notes) {
  1327. if ( err || notes.length === 0) {
  1328. sendJson(res, {status: 'not_found', message: 'There are no notes in this course'} );
  1329. } else {
  1330. notes = notes.map(function(note) { return note.sanitized });
  1331. sendJson(res, { 'notes': notes, 'course' : req.course, 'user': req.user.sanitized } );
  1332. }
  1333. })
  1334. })
  1335. app.get( '/archive/note/:id', checkAjax, loadUser, function( req, res ) {
  1336. console.log( "id="+req.params.id)
  1337. ArchivedNote.findById(req.params.id, function(err, note) {
  1338. if ( err || !note ) {
  1339. sendJson(res, {status: 'not_found', message: 'This is not a valid id for a note'} );
  1340. } else {
  1341. ArchivedCourse.findOne({id: note.course_id}, function(err, course) {
  1342. if ( err || !course ) {
  1343. sendJson(res, {status: 'not_found', message: 'There is no course for this note'} )
  1344. } else {
  1345. sendJson(res, { 'layout' : 'notesLayout', 'note' : note, 'course': course, 'user': req.user.sanitized } );
  1346. }
  1347. })
  1348. }
  1349. })
  1350. })
  1351. app.get( '*', function(req, res) {
  1352. res.sendfile('public/index.html');
  1353. });
  1354. // socket.io server
  1355. // The finalsclub backchannel server uses socket.io to handle communication between the server and
  1356. // the browser which facilitates near realtime interaction. This allows the user to post questions
  1357. // and comments and other users to get those almost immediately after they are posted, without
  1358. // reloading the page or pressing a button to refresh.
  1359. //
  1360. // The server code itself is fairly simple, mainly taking incomming messages from client browsers,
  1361. // saving the data to the database, and then sending it out to everyone else connected.
  1362. //
  1363. // Data types:
  1364. // Posts - Posts are the main items in backchannel, useful for questions or discussion points
  1365. // [[ example object needed with explanation E.G:
  1366. /*
  1367. Post: { postID: '999-1',
  1368. userID: '1234',
  1369. userName: 'Bob Jones',
  1370. userAffil: 'Instructor',
  1371. body: 'This is the text content of the post.',
  1372. comments: { {<commentObj>, <commentObj>, ...},
  1373. public: true,
  1374. votes: [ <userID>, <userID>, ...],
  1375. reports: [ <userID>, <userID>, ...]
  1376. }
  1377. Comment: { body: 'foo bar', userName: 'Bob Jones', userAffil: 'Instructor' }
  1378. if anonymous: userName => 'Anonymous', userAffil => 'N/A'
  1379. */
  1380. //
  1381. //
  1382. //
  1383. // Comments - Comments are replies to posts, for clarification or answering questions
  1384. // [[ example object needed]]
  1385. // Votes - Votes signifyg a users approval of a post
  1386. // [[ example object needed]]
  1387. // Flags - Flagging a post signifies that it is against the rules, 2 flags moves it to the bottomw
  1388. // [[ example object needed]]
  1389. //
  1390. //
  1391. // Post Schema
  1392. // body - Main content of the post
  1393. // userId - Not currently used, but would contain the users id that made the post
  1394. // userName - Users name that made post
  1395. // userAffil - Users affiliation to their school
  1396. // public - Boolean which denotes if the post is public to everyone, or private to school users only
  1397. // date - Date post was made, updates when any comments are made for the post
  1398. // comments - An array of comments which contain a body, userName, and userAffil
  1399. // votes - An array of user ids which are the users that voted
  1400. // [[ example needed ]]
  1401. // reports - An array of user ids which are the users that reported the post
  1402. // [[ reports would be "this post is flagged as inappropriate"? ]]
  1403. // [[ bruml: consistent terminology needed ]]
  1404. //
  1405. // Posts and comments can be made anonymously. When a post is anonymous, the users info is stripped
  1406. // from the post and the userName is set to Anonymous and the userAffil to N/A. This is to allow
  1407. // users the ability to make posts or comments that they might not otherwise due to not wanting
  1408. // the content of the post/comment to be attributed to them.
  1409. //
  1410. // Each time a user connects to the server, it passes through authorization which checks for a cookie
  1411. // that is set by Express. If a session exists and it is for a valid logged in user, then handshake.user
  1412. // is set to the users data, otherwise it is set to false. handshake.user is used later on to check if a
  1413. // user is logged in, and if so display information that otherwise might not be visible to them if they
  1414. // aren't apart of a particular school.
  1415. //
  1416. // After the authorization step, the client browser sends the lecture id which is rendered into the html
  1417. // page on page load from Express. This is then used to assign a 'room' for the user which is grouped
  1418. // by lecture. All posts are grouped by lecture, and only exist for that lecture. After the user is
  1419. // grouped into a 'room', they are sent a payload of all existing posts for that lecture, which are then
  1420. // rendered in the browser.
  1421. //
  1422. // Everything else from this point on is handled in an event form and requires a user initiating it. The
  1423. // events are as follows.
  1424. //
  1425. // Post event
  1426. // A user makes a new post. A payload of data containing the post and lecture id is sent to the server.
  1427. // The server recieves the data, assembles a new post object for the database and then fills it with
  1428. // the appropriate data. If a user selected for the post to be anonymous, the userName and userAffil are
  1429. // replaced. If the user chose for the post to be private, then public will be set to false and it
  1430. // will be filtered from being sent to users not logged into and not having access to the school. Once
  1431. // the post has been created and saved into the database, it is sent to all connected users to that
  1432. // particular lecture, unless it is private, than only logged in users will get it.
  1433. //
  1434. // Vote event
  1435. // A user votes for a post. A payload of data containing the post id and lecture id are sent along with
  1436. // the user id. A new vote is created by first fetching the parent post, then adding the user id to the
  1437. // votes array, and then the post is subsequently saved back to the database and sent to all connected
  1438. // users unless the post is private, which then it will be only sent to logged in users.
  1439. //
  1440. // Report event
  1441. // Similar to the vote event, reports are sent as a payload of a post id, lecture id, and user id, which
  1442. // are then used to fetch the parent post, add the user id to the reports array, and then saved to the db.
  1443. // Then the report is sent out to all connected users unless it is a private post, which will be only sent
  1444. // to logged in users. On the client, once a post has more two (2) or more reports, it will be moved to the
  1445. // bottom of the interface.
  1446. //
  1447. // Comment event
  1448. // A user posts a comment to a post. A payload of data containing the post id, lecture id, comment body,
  1449. // user name, and user affiliation are sent to the server, which are then used to find the parent post
  1450. // and then a new comment object is assembled. When new comments are made, it updates the posts date
  1451. // which allows the post to be sorted by date and the posts with the freshest comments would be pushed
  1452. // to the top of the interface. The comment can be anonymous, which then will have the user
  1453. // name and affiliation stripped before saving to the database. The comment then will be sent out to all
  1454. // connected users unless the post is private, then only logged in users will recieve the comment.
  1455. var io = require( 'socket.io' ).listen( app );
  1456. var Post = mongoose.model( 'Post' );
  1457. io.set('authorization', function ( handshake, next ) {
  1458. var rawCookie = handshake.headers.cookie;
  1459. if (rawCookie) {
  1460. handshake.cookie = parseCookie(rawCookie);
  1461. handshake.sid = handshake.cookie['connect.sid'];
  1462. if ( handshake.sid ) {
  1463. app.set( 'sessionStore' ).get( handshake.sid, function( err, session ) {
  1464. if( err ) {
  1465. handshake.user = false;
  1466. return next(null, true);
  1467. } else {
  1468. // bake a new session object for full r/w
  1469. handshake.session = new Session( handshake, session );
  1470. User.findOne( { session : handshake.sid }, function( err, user ) {
  1471. if( user ) {
  1472. handshake.user = user;
  1473. return next(null, true);
  1474. } else {
  1475. handshake.user = false;
  1476. return next(null, true);
  1477. }
  1478. });
  1479. }
  1480. })
  1481. }
  1482. } else {
  1483. data.user = false;
  1484. return next(null, true);
  1485. }
  1486. });
  1487. var backchannel = new Backchannel(app, io.of('/backchannel'), {
  1488. // TODO: if lecture belongs to course (find pinker's courseId) pass a 'no-answers' true/false
  1489. subscribe: function(lecture, send) {
  1490. Post.find({'lecture': lecture}, function(err, posts) {
  1491. send(posts);
  1492. });
  1493. },
  1494. post: function(fillPost) {
  1495. var post = new Post;
  1496. fillPost(post, function(send) {
  1497. post.save(function(err) {
  1498. send();
  1499. });
  1500. });
  1501. },
  1502. items: function(postId, addItem) {
  1503. Post.findById(postId, function( err, post ) {
  1504. addItem(post, function(send) {
  1505. post.save(function(err) {
  1506. send();
  1507. });
  1508. })
  1509. })
  1510. }
  1511. });
  1512. var counters = {};
  1513. var counts = io
  1514. .of( '/counts' )
  1515. .on( 'connection', function( socket ) {
  1516. // pull out user/session information etc.
  1517. var handshake = socket.handshake;
  1518. var userID = handshake.user._id;
  1519. var watched = [];
  1520. var noteID = null;
  1521. var timer = null;
  1522. socket.on( 'join', function( note ) {
  1523. if (handshake.user === false) {
  1524. noteID = note;
  1525. // XXX: replace by addToSet (once it's implemented in mongoose)
  1526. Note.findById( noteID, function( err, note ) {
  1527. if( note ) {
  1528. if( note.collaborators.indexOf( userID ) == -1 ) {
  1529. note.collaborators.push( userID );
  1530. note.save();
  1531. }
  1532. }
  1533. });
  1534. }
  1535. });
  1536. socket.on( 'watch', function( l ) {
  1537. var sendCounts = function() {
  1538. var send = {};
  1539. Note.find( { '_id' : { '$in' : watched } }, function( err, notes ) {
  1540. async.forEach(
  1541. notes,
  1542. function( note, callback ) {
  1543. var id = note._id;
  1544. var count = note.collaborators.length;
  1545. send[ id ] = count;
  1546. callback();
  1547. }, function() {
  1548. socket.emit( 'counts', send );
  1549. timer = setTimeout( sendCounts, 5000 );
  1550. }
  1551. );
  1552. });
  1553. }
  1554. Note.find( { 'lecture' : l }, [ '_id' ], function( err, notes ) {
  1555. notes.forEach( function( note ) {
  1556. watched.push( note._id );
  1557. });
  1558. });
  1559. sendCounts();
  1560. });
  1561. socket.on( 'disconnect', function() {
  1562. clearTimeout( timer );
  1563. if (handshake.user === false) {
  1564. // XXX: replace with $pull once it's available
  1565. if( noteID ) {
  1566. Note.findById( noteID, function( err, note ) {
  1567. if( note ) {
  1568. var index = note.collaborators.indexOf( userID );
  1569. if( index != -1 ) {
  1570. note.collaborators.splice( index, 1 );
  1571. }
  1572. note.save();
  1573. }
  1574. });
  1575. }
  1576. }
  1577. });
  1578. });
  1579. // Exception Catch-All
  1580. process.on('uncaughtException', function (e) {
  1581. console.log("!!!!!! UNCAUGHT EXCEPTION\n" + e.stack);
  1582. });
  1583. // Launch
  1584. // mongoose now exepects a mongo url
  1585. mongoose.connect( 'mongodb://localhost/fc' ); // FIXME: make relative to hostname
  1586. var mailer = new Mailer( app.set('awsAccessKey'), app.set('awsSecretKey') );
  1587. app.listen( serverPort, function() {
  1588. console.log( "Express server listening on port %d in %s mode", app.address().port, app.settings.env );
  1589. // if run as root, downgrade to the owner of this file
  1590. if (process.getuid() === 0) {
  1591. require('fs').stat(__filename, function(err, stats) {
  1592. if (err) { return console.log(err); }
  1593. process.setuid(stats.uid);
  1594. });
  1595. }
  1596. });
  1597. function isValidEmail(email) {
  1598. var re = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
  1599. return email.match(re);
  1600. }
  1601. // Facebook connect