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.
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.
12 var sys = require( 'sys' );
13 var os = require( 'os' );
14 var url = require( 'url' );
15 var express = require( 'express' );
16 var mongoStore = require( 'connect-mongo' );
17 var async = require( 'async' );
18 var db = require( './db.js' );
19 var mongoose = require( './models.js' ).mongoose;
20 var Mailer = require( './mailer.js' );
21 var hat = require('hat');
22 var connect = require( 'connect' );
23 var Session = connect.middleware.session.Session;
24 var parseCookie = connect.utils.parseCookie;
25 var Backchannel = require('./bc/backchannel');
27 // ********************************
28 // For facebook oauth and connect
29 // ********************************
30 var everyauth = require('everyauth');
31 var FacebookClient = require('facebook-client').FacebookClient;
32 var facebook = new FacebookClient();
34 everyauth.debug = true;
36 // configure facebook authentication
38 .appId('118001624986867')
39 .appSecret('c74910f00dea3d083a00572a445af3ae')
40 .scope('user_likes,user_photos,user_photo_video_tags,email')
42 .redirectPath('/profile')
43 .findOrCreateUser(function(req) {
45 console.log(req.user);
46 User.findOne( { }, function( err, user ) {
49 // if a user exists with that email, call them logged in
50 // FIXME: change this to different query on 'fbid'
52 // save the fact that this cookie/session-id is right for this user
53 var sid = req.sessionID;
55 user.save( function() {
56 //req.session.email = 'fuckles';
57 sendJson(res, {status: 'ok', message:'Successfully logged in via Fb'});
62 //.callbackPath('/fbsucc')
68 // Used for initial testing
69 var log3 = function() {}
72 var app = module.exports = express.createServer();
74 // Load Mongoose Schemas
75 // The actual schemas are located in models.j
76 var User = mongoose.model( 'User' );
77 var School = mongoose.model( 'School' );
78 var Course = mongoose.model( 'Course' );
79 var Lecture = mongoose.model( 'Lecture' );
80 var Note = mongoose.model( 'Note' );
82 // More schemas used for legacy data
83 var ArchivedCourse = mongoose.model( 'ArchivedCourse' );
84 var ArchivedNote = mongoose.model( 'ArchivedNote' );
85 var ArchivedSubject = mongoose.model( 'ArchivedSubject' );
87 // XXX Not sure if necessary
88 var ObjectId = mongoose.SchemaTypes.ObjectId;
91 // Use the environment variable DEV_EMAIL for testing
92 var ADMIN_EMAIL = process.env.DEV_EMAIL || 'info@finalsclub.org';
94 // Set server hostname and port from environment variables,
96 // XXX Can be cleaned up
97 var serverHost = process.env.SERVER_HOST;
98 var serverPort = process.env.SERVER_PORT;
101 console.log( 'Using server hostname defined in environment: %s', serverHost );
103 serverHost = os.hostname();
104 console.log( 'No hostname defined, defaulting to os.hostname(): %s', serverHost );
107 // Express configuration depending on environment
108 // development is intended for developing locally or
109 // when not in production, otherwise production is used
110 // when the site will be run live for regular usage.
111 app.configure( 'development', function() {
112 // In development mode, all errors and stack traces will be
113 // dumped to the console and on page for easier troubleshooting
115 app.set( 'errorHandler', express.errorHandler( { dumpExceptions: true, showStack: true } ) );
117 // Set database connection information from environment
118 // variables otherwise use localhost.
119 app.set( 'dbHost', process.env.MONGO_HOST || 'localhost' );
120 app.set( 'dbUri', 'mongodb://' + app.set( 'dbHost' ) + '/fc' );
122 // Set Amazon access and secret keys from environment
123 // variables. These keys are intended to be secret, so
124 // are not included in the source code, but set on the server
126 app.set( 'awsAccessKey', process.env.AWS_ACCESS_KEY_ID );
127 app.set( 'awsSecretKey', process.env.AWS_SECRET_ACCESS_KEY );
129 // If a port wasn't set earlier, set to 3000
135 // Production configuration settings
136 app.configure( 'production', function() {
137 // At the moment we have errors outputting everything
138 // so if there are any issues it is easier to track down.
139 // Once the site is more stable it will be prudent to
140 // use less error tracing.
141 app.set( 'errorHandler', express.errorHandler( { dumpExceptions: true, showStack: true } ) );
143 // Disable view cache due to stale views.
144 // XXX Disable view caching temp
145 app.disable( 'view cache' )
147 // Against setting the database connection information
148 // XXX Can be cleaned up or combined
149 app.set( 'dbHost', process.env.MONGO_HOST || 'localhost' );
150 app.set( 'dbUri', 'mongodb://' + app.set( 'dbHost' ) + '/fc' );
152 // XXX Can be cleaned up or combined
153 app.set( 'awsAccessKey', process.env.AWS_ACCESS_KEY_ID );
154 app.set( 'awsSecretKey', process.env.AWS_SECRET_ACCESS_KEY );
156 // Set to port 80 if not set through environment variables
162 // General Express configuration settings
163 app.configure(function(){
164 // Views are rendered from public/index.html and main.js except for the pad that surrounds EPL and BC
165 // FIXME: make all views exist inside of public/index.html
166 // Views are housed in the views folder
167 app.set( 'views', __dirname + '/views' );
168 // All templates use jade for rendering
169 app.set( 'view engine', 'jade' );
171 // Bodyparser is required to handle form submissions
172 // without manually parsing them.
173 app.use( express.bodyParser() );
175 app.use( express.cookieParser() );
177 // Sessions are stored in mongodb which allows them
178 // to be persisted even between server restarts.
179 app.set( 'sessionStore', new mongoStore( {
181 'url' : app.set( 'dbUri' )
184 // This is where the actual Express session handler
185 // is defined, with a mongoStore being set as the
186 // session storage versus in memory storage that is
188 app.use( express.session( {
189 // A secret 'password' for encrypting and decrypting
191 // XXX Should be handled differently
192 'secret' : 'finalsclub',
193 // The max age of the cookies that is allowed
194 // 60 (seconds) * 60 (minutes) * 24 (hours) * 30 (days) * 1000 (milliseconds)
195 'maxAge' : new Date(Date.now() + (60 * 60 * 24 * 30 * 1000)),
196 'store' : app.set( 'sessionStore' )
199 // methodOverride is used to handle PUT and DELETE HTTP
200 // requests that otherwise aren't handled by default.
201 app.use( express.methodOverride() );
202 // Static files are loaded when no dynamic views match.
203 app.use( express.static( __dirname + '/public' ) );
205 // EveryAuth fb connect
206 app.use( everyauth.middleware() );
208 // Sets the routers middleware to load after everything set
209 // before it, but before static files.
210 app.use( app.router );
212 app.use(express.logger({ format: ':method :url' }));
213 // This is the command to use the default express error logger/handler
214 app.use(express.errorHandler({ dumpExceptions: true }));
218 // Mailer functions and helpers
219 // These are helper functions that make for cleaner code.
221 // sendUserActivation is for when a user registers and
222 // first needs to activate their account to use it.
223 function sendUserActivation( user ) {
227 'subject' : 'Activate your FinalsClub.org Account',
229 // Templates are in the email folder and use ejs
230 'template' : 'userActivation',
231 // Locals are used inside ejs so dynamic information
232 // can be rendered properly.
235 'serverHost' : serverHost
239 // Email is sent here
240 mailer.send( message, function( err, result ) {
242 // XXX: Add route to resend this email
243 console.log( 'Error sending user activation email\nError Message: '+err.Message );
245 console.log( 'Successfully sent user activation email.' );
250 // sendUserWelcome is for when a user registers and
251 // a welcome email is sent.
252 function sendUserWelcome( user, school ) {
253 // If a user is not apart of a supported school, they are
254 // sent a different template than if they are apart of a
256 var template = school ? 'userWelcome' : 'userWelcomeNoSchool';
260 'subject' : 'Welcome to FinalsClub',
262 'template' : template,
265 'serverHost' : serverHost
269 mailer.send( message, function( err, result ) {
271 // XXX: Add route to resend this email
272 console.log( 'Error sending user welcome email\nError Message: '+err.Message );
274 console.log( 'Successfully sent user welcome email.' );
280 // These functions are used later in the routes to help
281 // load information and variables, as well as handle
282 // various instances like checking if a user is logged in
284 function loggedIn( req, res, next ) {
285 // If req.user is set, then pass on to the next function
286 // or else alert the user with an error message.
290 req.flash( 'error', 'You must be logged in to access that feature!' );
295 // This loads the user if logged in
296 function loadUser( req, res, next ) {
297 var sid = req.sessionID;
299 console.log( 'got request from session ID: %s', sid );
301 // Find a user based on their stored session id
302 User.findOne( { session : sid }, function( err, user ) {
307 // If a user is found then set req.user the contents of user
308 // and make sure req.user.loggedIn is true.
312 req.user.loggedIn = true;
314 log3( 'authenticated user: '+req.user._id+' / '+req.user.email+'');
316 // Check if a user is activated. If not, then redirec
317 // to the homepage and tell them to check their email
318 // for the activation email.
319 if( req.user.activated ) {
320 // Is the user's profile complete? If not, redirect to their profile
321 if( ! req.user.isComplete ) {
322 if( url.parse( req.url ).pathname != '/profile' ) {
323 req.flash( 'info', 'Your profile is incomplete. Please complete your profile to fully activate your account.' );
325 res.redirect( '/profile' );
333 req.flash( 'info', 'This account has not been activated. Check your email for the activation URL.' );
337 } else if('a'==='b'){
338 console.log('never. in. behrlin.');
340 // If no user record was found, then we store the requested
341 // path they intended to view and redirect them after they
342 // login if it is requred.
343 var path = url.parse( req.url ).pathname;
344 req.session.redirect = path;
346 // Set req.user to an empty object so it doesn't throw errors
347 // later on that it isn't defined.
357 // loadSchool is used to load a school by it's id
358 function loadSchool( req, res, next ) {
360 var schoolId = req.params.id;
361 console.log( 'loading a school by id' );
363 School.findById( schoolId, function( err, school ) {
367 // If a school is found, the user is checked to see if they are
368 // authorized to see or interact with anything related to that
370 school.authorize( user, function( authorized ){
371 req.school.authorized = authorized;
375 // If no school is found, display an appropriate error.
376 sendJson(res, {status: 'not_found', message: 'Invalid school specified!'} );
381 function loadSchoolSlug( req, res, next ) {
383 var schoolSlug = req.params.slug;
385 console.log("loading a school by slug");
386 //console.log(schoolSlug);
388 School.findOne({ 'slug': schoolSlug }, function( err, school ) {
389 console.log( school );
393 // If a school is found, the user is checked to see if they are
394 // authorized to see or interact with anything related to that
397 //school.authorize( user, function( authorized ){
398 //req.school.authorized = authorized;
402 // If no school is found, display an appropriate error.
403 sendJson(res, {status: 'not_found', message: 'Invalid school specified!'} );
408 // loadSchool is used to load a course by it's id
409 function loadCourse( req, res, next ) {
411 var courseId = req.params.id;
413 Course.findById( courseId, function( err, course ) {
414 if( course && !course.deleted ) {
417 // If a course is found, the user is checked to see if they are
418 // authorized to see or interact with anything related to that
420 course.authorize( user, function( authorized ) {
421 req.course.authorized = authorized;
426 // If no course is found, display an appropriate error.
427 sendJson(res, {status: 'not_found', message: 'Invalid course specified!'} );
432 // loadLecture is used to load a lecture by it's id
433 function loadLecture( req, res, next ) {
435 var lectureId = req.params.id;
437 Lecture.findById( lectureId, function( err, lecture ) {
438 if( lecture && !lecture.deleted ) {
439 req.lecture = lecture;
441 // If a lecture is found, the user is checked to see if they are
442 // authorized to see or interact with anything related to that
444 lecture.authorize( user, function( authorized ) {
445 req.lecture.authorized = authorized;
450 // If no lecture is found, display an appropriate error.
451 sendJson(res, {status: 'not_found', message: 'Invalid lecture specified!'} );
456 // loadNote is used to load a note by it's id
457 // This is a lot more complicated than the above
458 // due to public/private handling of notes.
459 function loadNote( req, res, next ) {
460 var user = req.user ? req.user : false;
461 var noteId = req.params.id;
463 Note.findById( noteId, function( err, note ) {
464 // If a note is found, and user is set, check if
465 // user is authorized to interact with that note.
466 if( note && user && !note.deleted ) {
467 note.authorize( user, function( auth ) {
469 // If authorzied, then set req.note to be used later
473 } else if ( note.public ) {
474 // If not authorized, but the note is public, then
475 // designate the note read only (RO) and store req.note
481 // If the user is not authorized and the note is private
482 // then display and error.
483 sendJson(res, {status: 'error', message: 'You do not have permission to access that note.'} );
486 } else if ( note && note.public && !note.deleted ) {
487 // If note is found, but user is not set because they are not
488 // logged in, and the note is public, set the note to read only
489 // and store the note for later.
494 } else if ( note && !note.public && !note.deleted ) {
495 // If the note is found, but user is not logged in and the note is
496 // not public, then ask them to login to view the note. Once logged
497 // in they will be redirected to the note, at which time authorization
498 // handling will be put in effect above.
499 //req.session.redirect = '/note/' + note._id;
500 sendJson(res, {status: 'error', message: 'You must be logged in to view that note.'} );
503 sendJson(res, {status: 'error', message: 'Invalid note specified!'} );
508 function checkAjax( req, res, next ) {
512 res.sendfile( 'public/index.html' );
516 // Dynamic Helpers are loaded automatically into views
517 app.dynamicHelpers( {
518 // express-messages is for flash messages for easy
519 // errors and information display
520 'messages' : require( 'express-messages' ),
522 // By default the req object isn't sen't to views
523 // during rendering, this allows you to use the
524 // user object if available in views.
525 'user' : function( req, res ) {
529 // Same, this allows session to be available in views.
530 'session' : function( req, res ) {
535 function sendJson( res, obj ) {
536 res.header('Cache-Control', 'no-cache, no-store');
541 // The following are the main CRUD routes that are used
542 // to make up this web app.
547 app.get( '/', loadUser, function( req, res ) {
550 res.render( 'index' );
555 // Used to display all available schools and any courses
557 // Public with some private information
558 app.get( '/schools', checkAjax, loadUser, function( req, res ) {
562 // Find all schools and sort by name
563 // XXX mongoose's documentation on sort is extremely poor, tread carefully
564 School.find( {} ).sort( 'name', '1' ).run( function( err, schools ) {
566 // If schools are found, loop through them gathering any courses that are
567 // associated with them and then render the page with that information.
568 sendJson(res, { 'user': user.sanitized, 'schools' : schools.map(function(school) {
569 var s = school.sanitized;
570 s['courses'] = Course.find( { 'school' : s._id } ).sort( 'name', '1' ).run(function( err, courses) {
571 return courses.map( function(c) { return c.sanitized; } );
576 // If no schools have been found, display none
577 //res.render( 'schools', { 'schools' : [] } );
578 sendJson(res, { 'schools' : [] , 'user': user.sanitized });
583 app.get( '/school/:slug', checkAjax, loadUser, loadSchoolSlug, function( req, res ) {
584 var school = req.school;
586 console.log( 'loading a school by school/:id now slug' );
588 school.authorize( user, function( authorized ) {
589 // This is used to display interface elements for those users
590 // that are are allowed to see th)m, for instance a 'New Course' button.
591 var sanitizedSchool = school.sanitized;
592 sanitizedSchool.authorized = authorized;
593 // Find all courses for school by it's id and sort by name
594 Course.find( { 'school' : school._id } ).sort( 'name', '1' ).run( function( err, courses ) {
595 // If any courses are found, set them to the appropriate school, otherwise
597 if( courses.length > 0 ) {
598 sanitizedSchool.courses = courses.filter(function(course) {
599 if (!course.deleted) return course;
600 }).map(function(course) {
601 return course.sanitized;
604 sanitizedSchool.courses = [];
606 // This tells async (the module) that each iteration of forEach is
607 // done and will continue to call the rest until they have all been
608 // completed, at which time the last function below will be called.
609 sendJson(res, { 'school': sanitizedSchool, 'user': user.sanitized })
614 // FIXME: version of the same using school slugs instead of ids
615 // TODO: merge this with the :id funciton or depricate it
616 app.get( '/schoolslug/:slug', checkAjax, loadUser, loadSchoolSlug, function( req, res ) {
617 var school = req.school;
619 console.log( 'loading a schoolslug/:slug' );
621 school.authorize( user, function( authorized ) {
622 // This is used to display interface elements for those users
623 // that are are allowed to see th)m, for instance a 'New Course' button.
624 var sanitizedSchool = school.sanitized;
625 sanitizedSchool.authorized = authorized;
626 // Find all courses for school by it's id and sort by name
627 Course.find( { 'school' : school._id } ).sort( 'name', '1' ).run( function( err, courses ) {
628 // If any courses are found, set them to the appropriate school, otherwise
630 if( courses.length > 0 ) {
631 sanitizedSchool.courses = courses.filter(function(course) {
632 if (!course.deleted) return course;
633 }).map(function(course) {
634 return course.sanitized;
637 sanitizedSchool.courses = [];
639 // This tells async (the module) that each iteration of forEach is
640 // done and will continue to call the rest until they have all been
641 // completed, at which time the last function below will be called.
642 sendJson(res, { 'school': sanitizedSchool, 'user': user.sanitized })
648 // Recieves new course form
649 app.post( '/school/:id', checkAjax, loadUser, loadSchool, function( req, res ) {
650 var school = req.school;
651 // Creates new course from Course Schema
652 var course = new Course;
653 // Gathers instructor information from form
654 var instructorEmail = req.body.email.toLowerCase();
655 var instructorName = req.body.instructorName;
657 if( ( ! school ) || ( ! school.authorized ) ) {
658 return sendJson(res, {status: 'error', message: 'There was a problem trying to create a course'})
661 if ( !instructorName ) {
662 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
665 if ( ( instructorEmail === '' ) || ( !isValidEmail( instructorEmail ) ) ) {
666 return sendJson(res, {status: 'error', message:'Please enter a valid email'} );
669 // Fill out the course with information from the form
670 course.number = req.body.number;
671 course.name = req.body.name;
672 course.description = req.body.description;
673 course.school = school._id;
674 course.creator = req.user._id;
675 course.subject = req.body.subject;
676 course.department = req.body.department;
678 // Check if a user exists with the instructorEmail, if not then create
679 // a new user and send them an instructor welcome email.
680 User.findOne( { 'email' : instructorEmail }, function( err, user ) {
684 user.name = instructorName
685 user.email = instructorEmail;
686 user.affil = 'Instructor';
687 user.school = school.name;
689 user.activated = false;
691 // Once the new user information has been completed, save the user
692 // to the database then email them the instructor welcome email.
693 user.save(function( err ) {
694 // If there was an error saving the instructor, prompt the user to fill out
695 // the information again.
697 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
702 'subject' : 'A non-profit open education initiative',
704 'template' : 'instructorInvite',
709 'serverHost' : serverHost
713 mailer.send( message, function( err, result ) {
715 console.log( 'Error inviting instructor to course!' );
717 console.log( 'Successfully invited instructor to course.' );
721 // After emails are sent, set the courses instructor to the
722 // new users id and then save the course to the database.
723 course.instructor = user._id;
724 course.save( function( err ) {
726 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
728 // Once the course has been completed email the admin with information
729 // on the course and new instructor
733 'subject' : school.name+' has a new course: '+course.name,
735 'template' : 'newCourse',
740 'serverHost' : serverHost
744 mailer.send( message, function( err, result ) {
746 console.log( 'Error sending new course email to info@finalsclub.org' )
748 console.log( 'Successfully invited instructor to course')
751 // Redirect the user to the schools page where they can see
753 // XXX Redirect to the new course instead
754 return sendJson(res, {status: 'ok', message: 'Course created'} )
760 // If the user exists, then check if they are already and instructor
761 if (user.affil === 'Instructor') {
762 // If they are an instructor, then save the course with the appropriate
763 // information and email the admin.
764 course.instructor = user._id;
765 course.save( function( err ) {
767 // XXX better validation
768 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
773 'subject' : school.name+' has a new course: '+course.name,
775 'template' : 'newCourse',
780 'serverHost' : serverHost
784 mailer.send( message, function( err, result ) {
786 console.log( 'Error sending new course email to info@finalsclub.org' )
788 console.log( 'Successfully invited instructor to course')
791 // XXX Redirect to the new course instead
792 return sendJson(res, {status: 'ok', message: 'Course created'} )
796 // The existing user isn't an instructor, so the user is notified of the error
797 // and the course isn't created.
798 sendJson(res, {status: 'error', message: 'The existing user\'s email you entered is not an instructor'} )
804 // Individual Course Listing
805 // Public with private information
806 app.get( '/course/:id', checkAjax, loadUser, loadCourse, function( req, res ) {
807 var userId = req.user._id;
808 var course = req.course;
810 // Check if the user is subscribed to the course
811 // XXX Not currently used for anything
812 //var subscribed = course.subscribed( userId );
814 // Find lectures associated with this course and sort by name
815 Lecture.find( { 'course' : course._id } ).sort( 'name', '1' ).run( function( err, lectures ) {
816 // Get course instructor information using their id
817 User.findById( course.instructor, function( err, instructor ) {
818 // Render course and lectures
819 var sanitizedInstructor = instructor.sanitized;
820 var sanitizedCourse = course.sanitized;
821 if (!course.authorized) {
822 delete sanitizedInstructor.email;
824 sanitizedCourse.authorized = course.authorized;
826 sendJson(res, { 'course' : sanitizedCourse, 'instructor': sanitizedInstructor, 'lectures' : lectures.map(function(lecture) { return lecture.sanitized })} );
831 // Recieve New Lecture Form
832 app.post( '/course/:id', checkAjax, loadUser, loadCourse, function( req, res ) {
833 var course = req.course;
834 // Create new lecture from Lecture schema
835 var lecture = new Lecture;
837 if( ( ! course ) || ( ! course.authorized ) ) {
838 return sendJson(res, {status: 'error', message: 'There was a problem trying to create a lecture'})
841 // Populate lecture with form data
842 lecture.name = req.body.name;
843 lecture.date = req.body.date;
844 lecture.course = course._id;
845 lecture.creator = req.user._id;
847 // Save lecture to database
848 lecture.save( function( err ) {
850 // XXX better validation
851 sendJson(res, {status: 'error', message: 'Invalid parameters!'} );
853 sendJson(res, {status: 'ok', message: 'Created new lecture'} );
859 app.get( '/course/:id/edit', loadUser, loadCourse, function( req, res) {
860 var course = req.course;
864 res.render( 'course/new', {course: course} )
866 req.flash( 'error', 'You don\'t have permission to do that' )
867 res.redirect( '/schools' );
871 // Recieve Course Edit Form
872 app.post( '/course/:id/edit', loadUser, loadCourse, function( req, res ) {
873 var course = req.course;
877 var courseChanges = req.body;
878 course.number = courseChanges.number;
879 course.name = courseChanges.name;
880 course.description = courseChanges.description;
881 course.department = courseChanges.department;
883 course.save(function(err) {
885 req.flash( 'error', 'There was an error saving the course' );
887 res.redirect( '/course/'+ course._id.toString());
890 req.flash( 'error', 'You don\'t have permission to do that' )
891 res.redirect( '/schools' );
896 app.get( '/course/:id/delete', loadUser, loadCourse, function( req, res) {
897 var course = req.course;
901 course.delete(function( err ) {
902 if ( err ) req.flash( 'info', 'There was a problem removing course: ' + err )
903 else req.flash( 'info', 'Successfully removed course' )
904 res.redirect( '/schools' );
907 req.flash( 'error', 'You don\'t have permission to do that' )
908 res.redirect( '/schools' );
912 // Subscribe to course
913 // XXX Not currently used for anything
914 app.get( '/course/:id/subscribe', loadUser, loadCourse, function( req, res ) {
915 var course = req.course;
916 var userId = req.user._id;
918 course.subscribe( userId, function( err ) {
920 req.flash( 'error', 'Error subscribing to course!' );
923 res.redirect( '/course/' + course._id );
927 // Unsubscribe from course
928 // XXX Not currently used for anything
929 app.get( '/course/:id/unsubscribe', loadUser, loadCourse, function( req, res ) {
930 var course = req.course;
931 var userId = req.user._id;
933 course.unsubscribe( userId, function( err ) {
935 req.flash( 'error', 'Error unsubscribing from course!' );
938 res.redirect( '/course/' + course._id );
945 // Display individual lecture and related notes
946 app.get( '/lecture/:id', checkAjax, loadUser, loadLecture, function( req, res ) {
947 var lecture = req.lecture;
949 // Grab the associated course
950 // XXX this should be done with DBRefs eventually
951 Course.findById( lecture.course, function( err, course ) {
953 // If course is found, find instructor information to be displayed on page
954 User.findById( course.instructor, function( err, instructor ) {
955 // Pull out our notes
956 Note.find( { 'lecture' : lecture._id } ).sort( 'name', '1' ).run( function( err, notes ) {
957 if ( !req.user.loggedIn || !req.lecture.authorized ) {
958 // Loop through notes and only return those that are public if the
959 // user is not logged in or not authorized for that lecture
960 notes = notes.filter(function( note ) {
961 if ( note.public ) return note;
964 var sanitizedInstructor = instructor.sanitized;
965 var sanitizedLecture = lecture.sanitized;
966 if (!lecture.authorized) {
967 delete sanitizedInstructor.email;
969 sanitizedLecture.authorized = lecture.authorized;
972 'lecture' : sanitizedLecture,
973 'course' : course.sanitized,
974 'instructor' : sanitizedInstructor,
975 'notes' : notes.map(function(note) {
976 return note.sanitized;
982 sendJson(res, { status: 'not_found', msg: 'This course is orphaned' })
988 // Recieve new note form
989 app.post( '/lecture/:id', checkAjax, loadUser, loadLecture, function( req, res ) {
990 var lecture = req.lecture;
992 if( ( ! lecture ) || ( ! lecture.authorized ) ) {
993 return sendJson(res, {status: 'error', message: 'There was a problem trying to create a note pad'})
996 // Create note from Note schema
999 // Populate note from form data
1000 note.name = req.body.name;
1001 note.date = req.body.date;
1002 note.lecture = lecture._id;
1003 note.public = req.body.private ? false : true;
1004 note.creator = req.user._id;
1006 // Save note to database
1007 note.save( function( err ) {
1009 // XXX better validation
1010 sendJson(res, {status: 'error', message: 'There was a problem trying to create a note pad'})
1012 sendJson(res, {status: 'ok', message: 'Successfully created a new note pad'})
1018 // Display individual note page
1019 app.get( '/note/:id', /*checkAjax,*/ loadUser, loadNote, function( req, res ) {
1020 var note = req.note;
1021 // Set read only id for etherpad-lite or false for later check
1022 var roID = note.roID || false;
1024 var lectureId = note.lecture;
1026 // Count the amount of visits, but only once per session
1027 if ( req.session.visited ) {
1028 if ( req.session.visited.indexOf( note._id.toString() ) == -1 ) {
1029 req.session.visited.push( note._id );
1033 req.session.visited = [];
1034 req.session.visited.push( note._id );
1038 // If a read only id exists process note
1042 // If read only id doesn't, then fetch the read only id from the database and then
1044 // XXX Soon to be depracated due to a new API in etherpad that makes for a
1045 // much cleaner solution.
1046 db.open('mongodb://' + app.set( 'dbHost' ) + '/etherpad/etherpad', function( err, epl ) {
1047 epl.findOne( { key: 'pad2readonly:' + note._id }, function(err, record) {
1049 roID = record.value.replace(/"/g, '');
1058 function processReq() {
1060 Lecture.findById( lectureId, function( err, lecture ) {
1062 req.flash( 'error', 'That notes page is orphaned!' );
1064 res.redirect( '/' );
1066 // Find notes based on lecture id, which will be displayed in a dropdown
1068 Note.find( { 'lecture' : lecture._id }, function( err, otherNotes ) {
1071 'host' : serverHost,
1072 'note' : note.sanitized,
1073 'lecture' : lecture.sanitized,
1074 'otherNotes' : otherNotes.map(function(note) {
1075 return note.sanitized;
1082 // User is logged in and sees full notepad
1084 res.render( 'notes/index', {
1085 'layout' : 'noteLayout',
1086 'host' : serverHost,
1088 'lecture' : lecture,
1089 'otherNotes' : otherNotes,
1092 'stylesheets' : [ 'dropdown.css', 'fc2.css' ],
1093 'javascripts' : [ 'dropdown.js', 'counts.js', 'backchannel.js', 'jquery.tmpl.min.js' ]
1096 // User is not logged in and sees notepad that is public
1097 res.render( 'notes/public', {
1098 'layout' : 'noteLayout',
1099 'host' : serverHost,
1101 'otherNotes' : otherNotes,
1103 'lecture' : lecture,
1104 'stylesheets' : [ 'dropdown.css', 'fc2.css' ],
1105 'javascripts' : [ 'dropdown.js', 'counts.js', 'backchannel.js', 'jquery.tmpl.min.js' ]
1113 // Static pages and redirects
1115 app.get( '/about', loadUser, function( req, res ) {
1116 res.redirect( 'http://blog.finalsclub.org/about.html' );
1119 app.get( '/press', loadUser, function( req, res ) {
1120 res.render( 'static/press' );
1123 app.get( '/conduct', loadUser, function( req, res ) {
1124 res.render( 'static/conduct' );
1127 app.get( '/legal', loadUser, function( req, res ) {
1128 res.redirect( 'http://blog.finalsclub.org/legal.html' );
1131 app.get( '/contact', loadUser, function( req, res ) {
1132 res.redirect( 'http://blog.finalsclub.org/contact.html' );
1135 app.get( '/privacy', loadUser, function( req, res ) {
1136 res.render( 'static/privacy' );
1141 // Authentication routes
1142 // These are used for logging in, logging out, registering
1143 // and other user authentication purposes
1145 // Render login page
1147 app.get( '/login', function( req, res ) {
1148 log3("get login page")
1150 res.render( 'login' );
1154 app.get( '/checkuser', checkAjax, loadUser, function( req, res ) {
1155 sendJson(res, {user: req.user.sanitized});
1158 // Recieve login form
1159 app.post( '/login', checkAjax, function( req, res ) {
1160 var email = req.body.email;
1161 var password = req.body.password;
1162 log3("post login ...")
1164 // Find user from email
1165 User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
1169 // If user exists, check if activated, if not notify them and send them to
1172 if( ! user.activated ) {
1173 // (undocumented) markdown-esque link functionality in req.flash
1174 req.session.activateCode = user._id;
1175 sendJson(res, {status: 'error', message: 'This account isn\'t activated.'} );
1178 // If user is activated, check if their password is correct
1179 if( user.authenticate( password ) ) {
1182 var sid = req.sessionID;
1186 // Set the session then save the user to the database
1187 user.save( function() {
1188 var redirect = req.session.redirect;
1190 // login complete, remember the user's email for next time
1191 req.session.email = email;
1193 // alert the successful login
1194 sendJson(res, {status: 'ok', message:'Successfully logged in!'} );
1196 // redirect to profile if we don't have a stashed request
1197 //res.redirect( redirect || '/profile' );
1200 // Notify user of bad login
1201 sendJson(res, {status: 'error', message: 'Invalid login!'} );
1203 //res.render( 'login' );
1207 // Notify user of bad login
1209 sendJson(res, {status: 'error', message: 'Invalid login!'} );
1211 //res.render( 'login' );
1216 // Recieve reset password request form
1217 app.post( '/resetpass', checkAjax, function( req, res ) {
1218 log3("post resetpw");
1219 var email = req.body.email
1223 User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
1226 // If user exists, create reset code
1227 var resetPassCode = hat(64);
1228 user.setResetPassCode(resetPassCode);
1230 // Construct url that the user can then click to reset password
1231 var resetPassUrl = 'http://' + serverHost + ((app.address().port != 80)? ':'+app.address().port: '') + '/resetpw/' + resetPassCode;
1233 // Save user to database
1234 user.save( function( err ) {
1235 log3('save '+user.email);
1237 // Construct email and send it to the user
1241 'subject' : 'Your FinalsClub.org Password has been Reset!',
1243 'template' : 'userPasswordReset',
1245 'resetPassCode' : resetPassCode,
1246 'resetPassUrl' : resetPassUrl
1250 mailer.send( message, function( err, result ) {
1252 // XXX: Add route to resend this email
1254 console.log( 'Error sending user password reset email!' );
1256 console.log( 'Successfully sent user password reset email.' );
1261 // Render request success page
1262 sendJson(res, {status: 'ok', message: 'Your password has been reset. An email has been sent to ' + email })
1266 sendJson(res, {status: 'error', message: 'We were unable to reset the password using that email address. Please try again.' })
1271 // Recieve reset password form
1272 app.post( '/resetpw/:id', checkAjax, function( req, res ) {
1273 log3("post resetpw.code");
1274 var resetPassCode = req.params.id
1275 var email = req.body.email
1276 var pass1 = req.body.pass1
1277 var pass2 = req.body.pass2
1279 // Find user by email
1280 User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
1282 // If user exists, and the resetPassCode is valid, pass1 and pass2 match, then
1283 // save user with new password and display success message.
1285 var valid = user.resetPassword(resetPassCode, pass1, pass2);
1287 user.save( function( err ) {
1288 sendJson(res, {status: 'ok', message: 'Your password has been reset. You can now login with your the new password you just created.'})
1292 // If there was a problem, notify user
1294 sendJson(res, {status: 'error', message: 'We were unable to reset the password. Please try again.' })
1299 // Display registration page
1301 app.get( '/register', function( req, res ) {
1302 log3("get reg page");
1304 // Populate school dropdown list
1305 School.find( {} ).sort( 'name', '1' ).run( function( err, schools ) {
1306 res.render( 'register', { 'schools' : schools } );
1311 // Recieve registration form
1312 app.post( '/register', checkAjax, function( req, res ) {
1313 var sid = req.sessionId;
1315 // Create new user from User schema
1316 var user = new User;
1318 // Populate user from form
1319 user.email = req.body.email.toLowerCase();
1320 user.password = req.body.password;
1322 // If school is set to other, then fill in school as what the user entered
1323 user.school = req.body.school === 'Other' ? req.body.otherSchool : req.body.school;
1324 user.name = req.body.name;
1325 user.affil = req.body.affil;
1326 user.activated = false;
1329 if ( ( user.email === '' ) || ( !isValidEmail( user.email ) ) ) {
1330 return sendJson(res, {status: 'error', message: 'Please enter a valid email'} );
1333 // Check if password is greater than 6 characters, otherwise notify user
1334 if ( req.body.password.length < 6 ) {
1335 return sendJson(res, {status: 'error', message: 'Please enter a password longer than eight characters'} );
1338 // Pull out hostname from email
1339 var hostname = user.email.split( '@' ).pop();
1341 // Check if email is from one of the special domains
1342 if( /^(finalsclub.org)$/.test( hostname ) ) {
1346 // Save user to database
1347 user.save( function( err ) {
1348 // If error, check if it is because the user already exists, if so
1349 // get the user information and let them know
1351 if( /dup key/.test( err.message ) ) {
1352 // attempting to register an existing address
1353 User.findOne({ 'email' : user.email }, function(err, result ) {
1354 if (result.activated) {
1355 // If activated, make sure they know how to contact the admin
1356 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'} );
1358 // If not activated, direct them to the resendActivation page
1359 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'} );
1363 // If any other type of error, prompt them to enter the registration again
1364 return sendJson(res, {status: 'error', message: 'An error occurred during registration.'} );
1367 // send user activation email
1368 sendUserActivation( user );
1370 // Check if the hostname matches any in the approved schools
1371 School.findOne( { 'hostnames' : hostname }, function( err, school ) {
1373 // If there is a match, send associated welcome message
1374 sendUserWelcome( user, true );
1375 log3('school recognized '+school.name);
1376 // If no users exist for the school, create empty array
1377 if (!school.users) school.users = [];
1378 // Add user to the school
1379 school.users.push( user._id );
1381 // Save school to the database
1382 school.save( function( err ) {
1383 log3('school.save() done');
1384 // Notify user that they have been added to the school
1385 sendJson(res, {status: 'ok', message: 'You have automatically been added to the ' + school.name + ' network. Please check your email for the activation link'} );
1387 // Construct admin email about user registration
1391 'subject' : 'FC User Registration : User added to ' + school.name,
1393 'template' : 'userSchool',
1399 // If there isn't a match, send associated welcome message
1400 sendUserWelcome( user, false );
1401 // Tell user to check for activation link
1402 sendJson(res, {status: 'ok', message: 'Your account has been created, please check your email for the activation link'} );
1403 // Construct admin email about user registration
1407 'subject' : 'FC User Registration : Email did not match any schools',
1409 'template' : 'userNoSchool',
1415 // Send email to admin
1416 mailer.send( message, function( err, result ) {
1419 console.log( 'Error sending user has no school email to admin\nError Message: '+err.Message );
1421 console.log( 'Successfully sent user has no school email to admin.' );
1431 // Display resendActivation request page
1432 app.get( '/resendActivation', function( req, res ) {
1433 var activateCode = req.session.activateCode;
1435 // Check if user exists by activateCode set in their session
1436 User.findById( activateCode, function( err, user ) {
1437 if( ( ! user ) || ( user.activated ) ) {
1438 res.redirect( '/' );
1440 // Send activation and redirect to login
1441 sendUserActivation( user );
1443 req.flash( 'info', 'Your activation code has been resent.' );
1445 res.redirect( '/login' );
1450 // Display activation page
1451 app.get( '/activate/:code', checkAjax, function( req, res ) {
1452 var code = req.params.code;
1454 // XXX could break this out into a middleware
1456 return sendJson(res, {status:'error', message: 'Invalid activation code!'} );
1459 // Find user by activation code
1460 User.findById( code, function( err, user ) {
1461 if( err || ! user ) {
1462 // If not found, notify user of invalid code
1463 sendJson(res, {status:'error', message:'Invalid activation code!'} );
1465 // If valid, then activate user
1466 user.activated = true;
1468 // Regenerate our session and log in as the new user
1469 req.session.regenerate( function() {
1470 user.session = req.sessionID;
1472 // Save user to database
1473 user.save( function( err ) {
1475 sendJson(res, {status: 'error', message: 'Unable to activate account.'} );
1477 sendJson(res, {status: 'info', message: 'Account successfully activated. Please complete your profile.'} );
1486 app.get( '/logout', checkAjax, function( req, res ) {
1487 var sid = req.sessionID;
1489 // Find user by session id
1490 User.findOne( { 'session' : sid }, function( err, user ) {
1492 // Empty out session id
1495 // Save user to database
1496 user.save( function( err ) {
1497 sendJson(res, {status: 'ok', message: 'Successfully logged out'});
1500 sendJson(res, {status: 'ok', message: ''});
1505 // Recieve profile edit page form
1506 app.post( '/profile', checkAjax, loadUser, loggedIn, function( req, res ) {
1507 var user = req.user;
1508 var fields = req.body;
1511 var wasComplete = user.isComplete;
1513 if( ! fields.name ) {
1514 return sendJson(res, {status: 'error', message: 'Please enter a valid name!'} );
1516 user.name = fields.name;
1519 if( [ 'Student', 'Teachers Assistant' ].indexOf( fields.affiliation ) == -1 ) {
1520 return sendJson(res, {status: 'error', message: 'Please select a valid affiliation!'} );
1522 user.affil = fields.affiliation;
1525 if( fields.existingPassword || fields.newPassword || fields.newPasswordConfirm ) {
1526 // changing password
1527 if( ( ! user.hashed ) || user.authenticate( fields.existingPassword ) ) {
1528 if( fields.newPassword === fields.newPasswordConfirm ) {
1529 // test password strength?
1531 user.password = fields.newPassword;
1533 return sendJson(res, {status: 'error', message: 'Mismatch in new password!'} );
1536 return sendJson(res, {status: 'error', message: 'Please supply your existing password.'} );
1540 user.major = fields.major;
1541 user.bio = fields.bio;
1543 user.showName = ( fields.showName ? true : false );
1545 user.save( function( err ) {
1547 sendJson(res, {status: 'error', message: 'Unable to save user profile!'} );
1549 if( ( user.isComplete ) && ( ! wasComplete ) ) {
1550 sendJson(res, {status: 'ok', message: 'Your account is now fully activated. Thank you for joining FinalsClub!'} );
1552 sendJson(res, {status:'ok', message:'Your profile was successfully updated!'} );
1561 function loadSubject( req, res, next ) {
1562 if( url.parse( req.url ).pathname.match(/subject/) ) {
1563 ArchivedSubject.findOne({id: req.params.id }, function(err, subject) {
1564 if ( err || !subject) {
1565 sendJson(res, {status: 'not_found', message: 'Subject with this ID does not exist'} )
1567 req.subject = subject;
1576 function loadOldCourse( req, res, next ) {
1577 if( url.parse( req.url ).pathname.match(/course/) ) {
1578 ArchivedCourse.findOne({id: req.params.id }, function(err, course) {
1579 if ( err || !course ) {
1580 sendJson(res, {status: 'not_found', message: 'Course with this ID does not exist'} )
1582 req.course = course;
1591 var featuredCourses = [
1592 {name: 'The Human Mind', 'id': 1563},
1593 {name: 'Justice', 'id': 797},
1594 {name: 'Protest Literature', 'id': 1681},
1595 {name: 'Animal Cognition', 'id': 681},
1596 {name: 'Positive Psychology', 'id': 1793},
1597 {name: 'Social Psychology', 'id': 660},
1598 {name: 'The Book from Gutenberg to the Internet', 'id': 1439},
1599 {name: 'Cyberspace in Court', 'id': 1446},
1600 {name: 'Nazi Cinema', 'id': 2586},
1601 {name: 'Media and the American Mind', 'id': 2583},
1602 {name: 'Social Thought in Modern America', 'id': 2585},
1603 {name: 'Major British Writers II', 'id': 869},
1604 {name: 'Civil Procedure', 'id': 2589},
1605 {name: 'Evidence', 'id': 2590},
1606 {name: 'Management of Industrial and Nonprofit Organizations', 'id': 2591},
1609 app.get( '/learn', loadUser, function( req, res ) {
1610 res.render( 'archive/learn', { 'courses' : featuredCourses } );
1613 app.get( '/learn/random', checkAjax, function( req, res ) {
1614 sendJson(res, {status: 'ok', data: '/archive/course/'+ featuredCourses[Math.floor(Math.random()*featuredCourses.length)].id });
1617 app.get( '/archive', checkAjax, loadUser, function( req, res ) {
1618 ArchivedSubject.find({}).sort( 'name', '1' ).run( function( err, subjects ) {
1619 if ( err || subjects.length === 0) {
1620 sendJson(res, {status: 'error', message: 'There was a problem gathering the archived courses, please try again later.'} );
1622 sendJson(res, { 'subjects' : subjects, 'user': req.user.sanitized } );
1627 app.get( '/archive/subject/:id', checkAjax, loadUser, loadSubject, function( req, res ) {
1628 ArchivedCourse.find({subject_id: req.params.id}).sort('name', '1').run(function(err, courses) {
1629 if ( err || courses.length === 0 ) {
1630 sendJson(res, {status: 'not_found', message: 'There are no archived courses'} );
1632 sendJson(res, { 'courses' : courses, 'subject': req.subject, 'user': req.user.sanitized } );
1637 app.get( '/archive/course/:id', checkAjax, loadUser, loadOldCourse, function( req, res ) {
1638 ArchivedNote.find({course_id: req.params.id}).sort('name', '1').run(function(err, notes) {
1639 if ( err || notes.length === 0) {
1640 sendJson(res, {status: 'not_found', message: 'There are no notes in this course'} );
1642 notes = notes.map(function(note) { return note.sanitized });
1643 sendJson(res, { 'notes': notes, 'course' : req.course, 'user': req.user.sanitized } );
1648 app.get( '/archive/note/:id', checkAjax, loadUser, function( req, res ) {
1649 console.log( "id="+req.params.id)
1650 ArchivedNote.findById(req.params.id, function(err, note) {
1651 if ( err || !note ) {
1652 sendJson(res, {status: 'not_found', message: 'This is not a valid id for a note'} );
1654 ArchivedCourse.findOne({id: note.course_id}, function(err, course) {
1655 if ( err || !course ) {
1656 sendJson(res, {status: 'not_found', message: 'There is no course for this note'} )
1658 sendJson(res, { 'layout' : 'notesLayout', 'note' : note, 'course': course, 'user': req.user.sanitized } );
1666 app.get( '*', function(req, res) {
1667 res.sendfile('public/index.html');
1672 // The finalsclub backchannel server uses socket.io to handle communication between the server and
1673 // the browser which facilitates near realtime interaction. This allows the user to post questions
1674 // and comments and other users to get those almost immediately after they are posted, without
1675 // reloading the page or pressing a button to refresh.
1677 // The server code itself is fairly simple, mainly taking incomming messages from client browsers,
1678 // saving the data to the database, and then sending it out to everyone else connected.
1681 // Posts - Posts are the main items in backchannel, useful for questions or discussion points
1682 // [[ example object needed with explanation E.G:
1684 Post: { postID: '999-1',
1686 userName: 'Bob Jones',
1687 userAffil: 'Instructor',
1688 body: 'This is the text content of the post.',
1689 comments: { {<commentObj>, <commentObj>, ...},
1691 votes: [ <userID>, <userID>, ...],
1692 reports: [ <userID>, <userID>, ...]
1694 Comment: { body: 'foo bar', userName: 'Bob Jones', userAffil: 'Instructor' }
1696 if anonymous: userName => 'Anonymous', userAffil => 'N/A'
1701 // Comments - Comments are replies to posts, for clarification or answering questions
1702 // [[ example object needed]]
1703 // Votes - Votes signifyg a users approval of a post
1704 // [[ example object needed]]
1705 // Flags - Flagging a post signifies that it is against the rules, 2 flags moves it to the bottomw
1706 // [[ example object needed]]
1710 // body - Main content of the post
1711 // userId - Not currently used, but would contain the users id that made the post
1712 // userName - Users name that made post
1713 // userAffil - Users affiliation to their school
1714 // public - Boolean which denotes if the post is public to everyone, or private to school users only
1715 // date - Date post was made, updates when any comments are made for the post
1716 // comments - An array of comments which contain a body, userName, and userAffil
1717 // votes - An array of user ids which are the users that voted
1718 // [[ example needed ]]
1719 // reports - An array of user ids which are the users that reported the post
1720 // [[ reports would be "this post is flagged as inappropriate"? ]]
1721 // [[ bruml: consistent terminology needed ]]
1723 // Posts and comments can be made anonymously. When a post is anonymous, the users info is stripped
1724 // from the post and the userName is set to Anonymous and the userAffil to N/A. This is to allow
1725 // users the ability to make posts or comments that they might not otherwise due to not wanting
1726 // the content of the post/comment to be attributed to them.
1728 // Each time a user connects to the server, it passes through authorization which checks for a cookie
1729 // that is set by Express. If a session exists and it is for a valid logged in user, then handshake.user
1730 // is set to the users data, otherwise it is set to false. handshake.user is used later on to check if a
1731 // user is logged in, and if so display information that otherwise might not be visible to them if they
1732 // aren't apart of a particular school.
1734 // After the authorization step, the client browser sends the lecture id which is rendered into the html
1735 // page on page load from Express. This is then used to assign a 'room' for the user which is grouped
1736 // by lecture. All posts are grouped by lecture, and only exist for that lecture. After the user is
1737 // grouped into a 'room', they are sent a payload of all existing posts for that lecture, which are then
1738 // rendered in the browser.
1740 // Everything else from this point on is handled in an event form and requires a user initiating it. The
1741 // events are as follows.
1744 // A user makes a new post. A payload of data containing the post and lecture id is sent to the server.
1745 // The server recieves the data, assembles a new post object for the database and then fills it with
1746 // the appropriate data. If a user selected for the post to be anonymous, the userName and userAffil are
1747 // replaced. If the user chose for the post to be private, then public will be set to false and it
1748 // will be filtered from being sent to users not logged into and not having access to the school. Once
1749 // the post has been created and saved into the database, it is sent to all connected users to that
1750 // particular lecture, unless it is private, than only logged in users will get it.
1753 // A user votes for a post. A payload of data containing the post id and lecture id are sent along with
1754 // the user id. A new vote is created by first fetching the parent post, then adding the user id to the
1755 // votes array, and then the post is subsequently saved back to the database and sent to all connected
1756 // users unless the post is private, which then it will be only sent to logged in users.
1759 // Similar to the vote event, reports are sent as a payload of a post id, lecture id, and user id, which
1760 // are then used to fetch the parent post, add the user id to the reports array, and then saved to the db.
1761 // Then the report is sent out to all connected users unless it is a private post, which will be only sent
1762 // to logged in users. On the client, once a post has more two (2) or more reports, it will be moved to the
1763 // bottom of the interface.
1766 // A user posts a comment to a post. A payload of data containing the post id, lecture id, comment body,
1767 // user name, and user affiliation are sent to the server, which are then used to find the parent post
1768 // and then a new comment object is assembled. When new comments are made, it updates the posts date
1769 // which allows the post to be sorted by date and the posts with the freshest comments would be pushed
1770 // to the top of the interface. The comment can be anonymous, which then will have the user
1771 // name and affiliation stripped before saving to the database. The comment then will be sent out to all
1772 // connected users unless the post is private, then only logged in users will recieve the comment.
1774 var io = require( 'socket.io' ).listen( app );
1776 var Post = mongoose.model( 'Post' );
1778 io.set('authorization', function ( handshake, next ) {
1779 var rawCookie = handshake.headers.cookie;
1781 handshake.cookie = parseCookie(rawCookie);
1782 handshake.sid = handshake.cookie['connect.sid'];
1784 if ( handshake.sid ) {
1785 app.set( 'sessionStore' ).get( handshake.sid, function( err, session ) {
1787 handshake.user = false;
1788 return next(null, true);
1790 // bake a new session object for full r/w
1791 handshake.session = new Session( handshake, session );
1793 User.findOne( { session : handshake.sid }, function( err, user ) {
1795 handshake.user = user;
1796 return next(null, true);
1798 handshake.user = false;
1799 return next(null, true);
1807 return next(null, true);
1811 var backchannel = new Backchannel(app, io.of('/backchannel'), {
1812 subscribe: function(lecture, send) {
1813 Post.find({'lecture': lecture}, function(err, posts) {
1817 post: function(fillPost) {
1818 var post = new Post;
1819 fillPost(post, function(send) {
1820 post.save(function(err) {
1825 items: function(postId, addItem) {
1826 Post.findById(postId, function( err, post ) {
1827 addItem(post, function(send) {
1828 post.save(function(err) {
1843 .on( 'connection', function( socket ) {
1844 // pull out user/session information etc.
1845 var handshake = socket.handshake;
1846 var userID = handshake.user._id;
1853 socket.on( 'join', function( note ) {
1854 if (handshake.user === false) {
1856 // XXX: replace by addToSet (once it's implemented in mongoose)
1857 Note.findById( noteID, function( err, note ) {
1859 if( note.collaborators.indexOf( userID ) == -1 ) {
1860 note.collaborators.push( userID );
1868 socket.on( 'watch', function( l ) {
1869 var sendCounts = function() {
1872 Note.find( { '_id' : { '$in' : watched } }, function( err, notes ) {
1875 function( note, callback ) {
1877 var count = note.collaborators.length;
1883 socket.emit( 'counts', send );
1885 timer = setTimeout( sendCounts, 5000 );
1891 Note.find( { 'lecture' : l }, [ '_id' ], function( err, notes ) {
1892 notes.forEach( function( note ) {
1893 watched.push( note._id );
1900 socket.on( 'disconnect', function() {
1901 clearTimeout( timer );
1903 if (handshake.user === false) {
1904 // XXX: replace with $pull once it's available
1906 Note.findById( noteID, function( err, note ) {
1908 var index = note.collaborators.indexOf( userID );
1911 note.collaborators.splice( index, 1 );
1922 // Exception Catch-All
1924 process.on('uncaughtException', function (e) {
1925 console.log("!!!!!! UNCAUGHT EXCEPTION\n" + e.stack);
1931 // mongoose now exepects a mongo url
1932 mongoose.connect( 'mongodb://localhost/fc' ); // FIXME: make relative to hostname
1934 var mailer = new Mailer( app.set('awsAccessKey'), app.set('awsSecretKey') );
1936 everyauth.helpExpress(app);
1938 app.listen( serverPort, function() {
1939 console.log( "Express server listening on port %d in %s mode", app.address().port, app.settings.env );
1941 // if run as root, downgrade to the owner of this file
1942 if (process.getuid() === 0) {
1943 require('fs').stat(__filename, function(err, stats) {
1944 if (err) { return console.log(err); }
1945 process.setuid(stats.uid);
1950 function isValidEmail(email) {
1951 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])?/;
1952 return email.match(re);