app.js 58 KB

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