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;
35 everyauth.everymodule.logoutPath('/bye');
37 // configure facebook authentication
39 .appId('foobieblechreplacethisXXX')
40 .appSecret('foobiederpreplacethisXXX')
41 .myHostname('http://localhost:8000')
44 .redirectPath('/schools')
45 .findOrCreateUser(function(session, accessToken, accessTokExtra, fbUserMetadata, req) {
46 console.log('req.session');
47 console.log(req.session);
48 var userPromise = this.Promise();
49 User.findOne( {'email': fbUserMetadata.email }, function( err, euser ) {
50 console.log("Found a fc user for this fb email");
51 if (err) return userPromise.fail(err);
52 // if a user exists with that email, call them logged in
53 // FIXME: change this to different query on 'fbid'
55 //hsession = new Session( handshake, session );
56 // save thhat this cookie/session-id is right for this user
57 req.session.regenerate( function() {
58 euser.session = req.sessionID;
60 console.log( req.sessionID );
64 if (euser) return userPromise.fulfill(euser);
68 //.callbackPath('/fbsucc')
74 // Used for initial testing
75 var log3 = function() {}
78 var app = module.exports = express.createServer();
80 // Load Mongoose Schemas
81 // The actual schemas are located in models.j
82 var User = mongoose.model( 'User' );
83 var School = mongoose.model( 'School' );
84 var Course = mongoose.model( 'Course' );
85 var Lecture = mongoose.model( 'Lecture' );
86 var Note = mongoose.model( 'Note' );
88 // More schemas used for legacy data
89 var ArchivedCourse = mongoose.model( 'ArchivedCourse' );
90 var ArchivedNote = mongoose.model( 'ArchivedNote' );
91 var ArchivedSubject = mongoose.model( 'ArchivedSubject' );
93 // XXX Not sure if necessary
94 var ObjectId = mongoose.SchemaTypes.ObjectId;
97 // Use the environment variable DEV_EMAIL for testing
98 var ADMIN_EMAIL = process.env.DEV_EMAIL || 'info@finalsclub.org';
100 // Set server hostname and port from environment variables,
101 // then check if set.
102 // XXX Can be cleaned up
103 var serverHost = process.env.SERVER_HOST;
104 var serverPort = process.env.SERVER_PORT;
107 console.log( 'Using server hostname defined in environment: %s', serverHost );
109 serverHost = os.hostname();
110 console.log( 'No hostname defined, defaulting to os.hostname(): %s', serverHost );
113 // Express configuration depending on environment
114 // development is intended for developing locally or
115 // when not in production, otherwise production is used
116 // when the site will be run live for regular usage.
117 app.configure( 'development', function() {
118 // In development mode, all errors and stack traces will be
119 // dumped to the console and on page for easier troubleshooting
121 app.set( 'errorHandler', express.errorHandler( { dumpExceptions: true, showStack: true } ) );
123 // Set database connection information from environment
124 // variables otherwise use localhost.
125 app.set( 'dbHost', process.env.MONGO_HOST || 'localhost' );
126 app.set( 'dbUri', 'mongodb://' + app.set( 'dbHost' ) + '/fc' );
128 // Set Amazon access and secret keys from environment
129 // variables. These keys are intended to be secret, so
130 // are not included in the source code, but set on the server
132 app.set( 'awsAccessKey', process.env.AWS_ACCESS_KEY_ID );
133 app.set( 'awsSecretKey', process.env.AWS_SECRET_ACCESS_KEY );
135 // If a port wasn't set earlier, set to 3000
141 // Production configuration settings
142 app.configure( 'production', function() {
143 // At the moment we have errors outputting everything
144 // so if there are any issues it is easier to track down.
145 // Once the site is more stable it will be prudent to
146 // use less error tracing.
147 app.set( 'errorHandler', express.errorHandler( { dumpExceptions: true, showStack: true } ) );
149 // Disable view cache due to stale views.
150 // XXX Disable view caching temp
151 app.disable( 'view cache' )
153 // Against setting the database connection information
154 // XXX Can be cleaned up or combined
155 app.set( 'dbHost', process.env.MONGO_HOST || 'localhost' );
156 app.set( 'dbUri', 'mongodb://' + app.set( 'dbHost' ) + '/fc' );
158 // XXX Can be cleaned up or combined
159 app.set( 'awsAccessKey', process.env.AWS_ACCESS_KEY_ID );
160 app.set( 'awsSecretKey', process.env.AWS_SECRET_ACCESS_KEY );
162 // Set to port 80 if not set through environment variables
168 // General Express configuration settings
169 app.configure(function(){
170 // Views are rendered from public/index.html and main.js except for the pad that surrounds EPL and BC
171 // FIXME: make all views exist inside of public/index.html
172 // Views are housed in the views folder
173 app.set( 'views', __dirname + '/views' );
174 // All templates use jade for rendering
175 app.set( 'view engine', 'jade' );
177 // Bodyparser is required to handle form submissions
178 // without manually parsing them.
179 app.use( express.bodyParser() );
181 app.use( express.cookieParser() );
183 // Sessions are stored in mongodb which allows them
184 // to be persisted even between server restarts.
185 app.set( 'sessionStore', new mongoStore( {
187 'url' : app.set( 'dbUri' )
190 // This is where the actual Express session handler
191 // is defined, with a mongoStore being set as the
192 // session storage versus in memory storage that is
194 app.use( express.session( {
195 // A secret 'password' for encrypting and decrypting
197 // XXX Should be handled differently
198 'secret' : 'finalsclub',
199 // The max age of the cookies that is allowed
200 // 60 (seconds) * 60 (minutes) * 24 (hours) * 30 (days) * 1000 (milliseconds)
201 'maxAge' : new Date(Date.now() + (60 * 60 * 24 * 30 * 1000)),
202 'store' : app.set( 'sessionStore' )
205 // methodOverride is used to handle PUT and DELETE HTTP
206 // requests that otherwise aren't handled by default.
207 app.use( express.methodOverride() );
208 // Static files are loaded when no dynamic views match.
209 app.use( express.static( __dirname + '/public' ) );
211 // EveryAuth fb connect
212 app.use( everyauth.middleware() );
214 // Sets the routers middleware to load after everything set
215 // before it, but before static files.
216 app.use( app.router );
218 app.use(express.logger({ format: ':method :url' }));
219 // This is the command to use the default express error logger/handler
220 app.use(express.errorHandler({ dumpExceptions: true }));
224 // Mailer functions and helpers
225 // These are helper functions that make for cleaner code.
227 // sendUserActivation is for when a user registers and
228 // first needs to activate their account to use it.
229 function sendUserActivation( user ) {
233 'subject' : 'Activate your FinalsClub.org Account',
235 // Templates are in the email folder and use ejs
236 'template' : 'userActivation',
237 // Locals are used inside ejs so dynamic information
238 // can be rendered properly.
241 'serverHost' : serverHost
245 // Email is sent here
246 mailer.send( message, function( err, result ) {
248 // XXX: Add route to resend this email
249 console.log( 'Error sending user activation email\nError Message: '+err.Message );
251 console.log( 'Successfully sent user activation email.' );
256 // sendUserWelcome is for when a user registers and
257 // a welcome email is sent.
258 function sendUserWelcome( user, school ) {
259 // If a user is not apart of a supported school, they are
260 // sent a different template than if they are apart of a
262 var template = school ? 'userWelcome' : 'userWelcomeNoSchool';
266 'subject' : 'Welcome to FinalsClub',
268 'template' : template,
271 'serverHost' : serverHost
275 mailer.send( message, function( err, result ) {
277 // XXX: Add route to resend this email
278 console.log( 'Error sending user welcome email\nError Message: '+err.Message );
280 console.log( 'Successfully sent user welcome email.' );
286 // These functions are used later in the routes to help
287 // load information and variables, as well as handle
288 // various instances like checking if a user is logged in
290 function loggedIn( req, res, next ) {
291 // If req.user is set, then pass on to the next function
292 // or else alert the user with an error message.
296 req.flash( 'error', 'You must be logged in to access that feature!' );
301 // This loads the user if logged in
302 function loadUser( req, res, next ) {
303 var sid = req.sessionID;
305 console.log( 'got request from session ID: %s', sid );
307 // Find a user based on their stored session id
308 User.findOne( { session : sid }, function( err, user ) {
313 // If a user is found then set req.user the contents of user
314 // and make sure req.user.loggedIn is true.
318 req.user.loggedIn = true;
320 log3( 'authenticated user: '+req.user._id+' / '+req.user.email+'');
322 // Check if a user is activated. If not, then redirec
323 // to the homepage and tell them to check their email
324 // for the activation email.
325 if( req.user.activated ) {
326 // Is the user's profile complete? If not, redirect to their profile
327 if( ! req.user.isComplete ) {
328 if( url.parse( req.url ).pathname != '/profile' ) {
329 req.flash( 'info', 'Your profile is incomplete. Please complete your profile to fully activate your account.' );
331 res.redirect( '/profile' );
339 req.flash( 'info', 'This account has not been activated. Check your email for the activation URL.' );
343 } else if('a'==='b'){
344 console.log('never. in. behrlin.');
346 // If no user record was found, then we store the requested
347 // path they intended to view and redirect them after they
348 // login if it is requred.
349 var path = url.parse( req.url ).pathname;
350 req.session.redirect = path;
352 // Set req.user to an empty object so it doesn't throw errors
353 // later on that it isn't defined.
363 // loadSchool is used to load a school by it's id
364 function loadSchool( req, res, next ) {
366 var schoolName = req.params.name;
367 console.log( 'loading a school by id' );
369 School.findOne({'name': schoolName}).run( function( err, school ) {
374 // If a school is found, the user is checked to see if they are
375 // authorized to see or interact with anything related to that
377 school.authorize( user, function( authorized ){
378 req.school.authorized = authorized;
382 // If no school is found, display an appropriate error.
383 sendJson(res, {status: 'not_found', message: 'Invalid school specified!'} );
388 function loadSchoolSlug( req, res, next ) {
390 var schoolSlug = req.params.slug;
392 console.log("loading a school by slug");
393 //console.log(schoolSlug);
395 School.findOne({ 'slug': schoolSlug }, function( err, school ) {
396 console.log( school );
400 // If a school is found, the user is checked to see if they are
401 // authorized to see or interact with anything related to that
404 //school.authorize( user, function( authorized ){
405 //req.school.authorized = authorized;
409 // If no school is found, display an appropriate error.
410 sendJson(res, {status: 'not_found', message: 'Invalid school specified!'} );
415 // loadSchool is used to load a course by it's id
416 function loadCourse( req, res, next ) {
418 var courseId = req.params.id;
420 Course.findById( courseId, function( err, course ) {
421 if( course && !course.deleted ) {
424 // If a course is found, the user is checked to see if they are
425 // authorized to see or interact with anything related to that
427 course.authorize( user, function( authorized ) {
428 req.course.authorized = authorized;
433 // If no course is found, display an appropriate error.
434 sendJson(res, {status: 'not_found', message: 'Invalid course specified!'} );
439 // loadLecture is used to load a lecture by it's id
440 function loadLecture( req, res, next ) {
442 var lectureId = req.params.id;
444 Lecture.findById( lectureId, function( err, lecture ) {
445 if( lecture && !lecture.deleted ) {
446 req.lecture = lecture;
448 // If a lecture is found, the user is checked to see if they are
449 // authorized to see or interact with anything related to that
451 lecture.authorize( user, function( authorized ) {
452 req.lecture.authorized = authorized;
457 // If no lecture is found, display an appropriate error.
458 sendJson(res, {status: 'not_found', message: 'Invalid lecture specified!'} );
463 // loadNote is used to load a note by it's id
464 // This is a lot more complicated than the above
465 // due to public/private handling of notes.
466 function loadNote( req, res, next ) {
467 var user = req.user ? req.user : false;
468 var noteId = req.params.id;
470 Note.findById( noteId, function( err, note ) {
471 // If a note is found, and user is set, check if
472 // user is authorized to interact with that note.
473 if( note && user && !note.deleted ) {
474 note.authorize( user, function( auth ) {
476 // If authorzied, then set req.note to be used later
480 } else if ( note.public ) {
481 // If not authorized, but the note is public, then
482 // designate the note read only (RO) and store req.note
488 // If the user is not authorized and the note is private
489 // then display and error.
490 sendJson(res, {status: 'error', message: 'You do not have permission to access that note.'} );
493 } else if ( note && note.public && !note.deleted ) {
494 // If note is found, but user is not set because they are not
495 // logged in, and the note is public, set the note to read only
496 // and store the note for later.
501 } else if ( note && !note.public && !note.deleted ) {
502 // If the note is found, but user is not logged in and the note is
503 // not public, then ask them to login to view the note. Once logged
504 // in they will be redirected to the note, at which time authorization
505 // handling will be put in effect above.
506 //req.session.redirect = '/note/' + note._id;
507 sendJson(res, {status: 'error', message: 'You must be logged in to view that note.'} );
510 sendJson(res, {status: 'error', message: 'Invalid note specified!'} );
515 function checkAjax( req, res, next ) {
519 res.sendfile( 'public/index.html' );
523 // Dynamic Helpers are loaded automatically into views
524 app.dynamicHelpers( {
525 // express-messages is for flash messages for easy
526 // errors and information display
527 'messages' : require( 'express-messages' ),
529 // By default the req object isn't sen't to views
530 // during rendering, this allows you to use the
531 // user object if available in views.
532 'user' : function( req, res ) {
536 // Same, this allows session to be available in views.
537 'session' : function( req, res ) {
542 function sendJson( res, obj ) {
543 res.header('Cache-Control', 'no-cache, no-store');
548 // The following are the main CRUD routes that are used
549 // to make up this web app.
554 app.get( '/', loadUser, function( req, res ) {
557 res.render( 'index' );
562 // Used to display all available schools and any courses
564 // Public with some private information
565 app.get( '/schools', checkAjax, loadUser, function( req, res ) {
566 sys.puts('loading schools');
567 console.log(req.user);
571 // Find all schools and sort by name
572 // XXX mongoose's documentation on sort is extremely poor, tread carefully
573 School.find( {} ).sort( 'name', '1' ).run( function( err, schools ) {
575 // If schools are found, loop through them gathering any courses that are
576 // associated with them and then render the page with that information.
577 var schools_todo = schools.length;
578 schools.map(function (school) {
579 Course.find( { 'school': school.id } ).run(function (err, courses) {
580 school.courses_length = courses.length
582 if (schools_todo <= 0) {
583 sendJson(res, { 'user': user.sanitized, 'schools': schools.map( function(s) {
587 description: s.description,
590 courses: s.courses_length
599 // If no schools have been found, display none
600 //res.render( 'schools', { 'schools' : [] } );
601 sendJson(res, { 'schools' : [] , 'user': user.sanitized });
606 app.get( '/school/:name', checkAjax, loadUser, loadSchool, function( req, res ) {
607 var school = req.school;
610 console.log( 'loading a school by school/:id now name' );
612 //school.authorize( user, function( authorized ) {
613 // This is used to display interface elements for those users
614 // that are are allowed to see th)m, for instance a 'New Course' button.
615 //var sanitizedSchool = school.sanitized;
616 var sanitizedSchool = {
619 description: school.description,
622 //sanitizedSchool.authorized = authorized;
623 // Find all courses for school by it's id and sort by name
624 Course.find( { 'school' : school._id } ).sort( 'name', '1' ).run( function( err, courses ) {
625 // If any courses are found, set them to the appropriate school, otherwise
628 if( courses.length > 0 ) {
629 courses = courses.filter(function(course) {
630 if (!course.deleted) return course;
631 }).map(function(course) {
632 return course.sanitized;
637 sanitizedSchool.courses = courses;
640 // This tells async (the module) that each iteration of forEach is
641 // done and will continue to call the rest until they have all been
642 // completed, at which time the last function below will be called.
643 sendJson(res, { 'school': sanitizedSchool, 'user': user.sanitized })
648 // FIXME: version of the same using school slugs instead of ids
649 // TODO: merge this with the :id funciton or depricate it
650 app.get( '/schoolslug/:slug', checkAjax, loadUser, loadSchoolSlug, function( req, res ) {
651 var school = req.school;
653 console.log( 'loading a schoolslug/:slug' );
655 school.authorize( user, function( authorized ) {
656 // This is used to display interface elements for those users
657 // that are are allowed to see th)m, for instance a 'New Course' button.
658 var sanitizedSchool = school.sanitized;
659 sanitizedSchool.authorized = authorized;
660 // Find all courses for school by it's id and sort by name
661 Course.find( { 'school' : school._id } ).sort( 'name', '1' ).run( function( err, courses ) {
662 // If any courses are found, set them to the appropriate school, otherwise
664 if( courses.length > 0 ) {
665 sanitizedSchool.courses = courses.filter(function(course) {
666 if (!course.deleted) return course;
667 }).map(function(course) {
668 return course.sanitized;
671 sanitizedSchool.courses = [];
673 // This tells async (the module) that each iteration of forEach is
674 // done and will continue to call the rest until they have all been
675 // completed, at which time the last function below will be called.
676 sendJson(res, { 'school': sanitizedSchool, 'user': user.sanitized })
682 // Recieves new course form
683 app.post( '/school/:id', checkAjax, loadUser, loadSchool, function( req, res ) {
684 var school = req.school;
685 // Creates new course from Course Schema
686 var course = new Course;
687 // Gathers instructor information from form
688 var instructorEmail = req.body.email.toLowerCase();
689 var instructorName = req.body.instructorName;
691 if( ( ! school ) || ( ! school.authorized ) ) {
692 return sendJson(res, {status: 'error', message: 'There was a problem trying to create a course'})
695 if ( !instructorName ) {
696 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
699 if ( ( instructorEmail === '' ) || ( !isValidEmail( instructorEmail ) ) ) {
700 return sendJson(res, {status: 'error', message:'Please enter a valid email'} );
703 // Fill out the course with information from the form
704 course.number = req.body.number;
705 course.name = req.body.name;
706 course.description = req.body.description;
707 course.school = school._id;
708 course.creator = req.user._id;
709 course.subject = req.body.subject;
710 course.department = req.body.department;
712 // Check if a user exists with the instructorEmail, if not then create
713 // a new user and send them an instructor welcome email.
714 User.findOne( { 'email' : instructorEmail }, function( err, user ) {
718 user.name = instructorName
719 user.email = instructorEmail;
720 user.affil = 'Instructor';
721 user.school = school.name;
723 user.activated = false;
725 // Once the new user information has been completed, save the user
726 // to the database then email them the instructor welcome email.
727 user.save(function( err ) {
728 // If there was an error saving the instructor, prompt the user to fill out
729 // the information again.
731 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
736 'subject' : 'A non-profit open education initiative',
738 'template' : 'instructorInvite',
743 'serverHost' : serverHost
747 mailer.send( message, function( err, result ) {
749 console.log( 'Error inviting instructor to course!' );
751 console.log( 'Successfully invited instructor to course.' );
755 // After emails are sent, set the courses instructor to the
756 // new users id and then save the course to the database.
757 course.instructor = user._id;
758 course.save( function( err ) {
760 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
762 // Once the course has been completed email the admin with information
763 // on the course and new instructor
767 'subject' : school.name+' has a new course: '+course.name,
769 'template' : 'newCourse',
774 'serverHost' : serverHost
778 mailer.send( message, function( err, result ) {
780 console.log( 'Error sending new course email to info@finalsclub.org' )
782 console.log( 'Successfully invited instructor to course')
785 // Redirect the user to the schools page where they can see
787 // XXX Redirect to the new course instead
788 return sendJson(res, {status: 'ok', message: 'Course created'} )
794 // If the user exists, then check if they are already and instructor
795 if (user.affil === 'Instructor') {
796 // If they are an instructor, then save the course with the appropriate
797 // information and email the admin.
798 course.instructor = user._id;
799 course.save( function( err ) {
801 // XXX better validation
802 return sendJson(res, {status: 'error', message: 'Invalid parameters!'} )
807 'subject' : school.name+' has a new course: '+course.name,
809 'template' : 'newCourse',
814 'serverHost' : serverHost
818 mailer.send( message, function( err, result ) {
820 console.log( 'Error sending new course email to info@finalsclub.org' )
822 console.log( 'Successfully invited instructor to course')
825 // XXX Redirect to the new course instead
826 return sendJson(res, {status: 'ok', message: 'Course created'} )
830 // The existing user isn't an instructor, so the user is notified of the error
831 // and the course isn't created.
832 sendJson(res, {status: 'error', message: 'The existing user\'s email you entered is not an instructor'} )
838 // Individual Course Listing
839 // Public with private information
840 app.get( '/course/:id', checkAjax, loadUser, loadCourse, function( req, res ) {
841 var userId = req.user._id;
842 var course = req.course;
844 // Check if the user is subscribed to the course
845 // XXX Not currently used for anything
846 //var subscribed = course.subscribed( userId );
848 // Find lectures associated with this course and sort by name
849 Lecture.find( { 'course' : course._id } ).sort( 'name', '1' ).run( function( err, lectures ) {
850 // Get course instructor information using their id
851 User.findById( course.instructor, function( err, instructor ) {
852 // Render course and lectures
853 var sanitizedInstructor = instructor.sanitized;
854 var sanitizedCourse = course.sanitized;
855 if (!course.authorized) {
856 delete sanitizedInstructor.email;
858 sanitizedCourse.authorized = course.authorized;
860 sendJson(res, { 'course' : sanitizedCourse, 'instructor': sanitizedInstructor, 'lectures' : lectures.map(function(lecture) { return lecture.sanitized })} );
865 // Recieve New Lecture Form
866 app.post( '/course/:id', checkAjax, loadUser, loadCourse, function( req, res ) {
867 var course = req.course;
868 // Create new lecture from Lecture schema
869 var lecture = new Lecture;
871 if( ( ! course ) || ( ! course.authorized ) ) {
872 return sendJson(res, {status: 'error', message: 'There was a problem trying to create a lecture'})
875 // Populate lecture with form data
876 lecture.name = req.body.name;
877 lecture.date = req.body.date;
878 lecture.course = course._id;
879 lecture.creator = req.user._id;
881 // Save lecture to database
882 lecture.save( function( err ) {
884 // XXX better validation
885 sendJson(res, {status: 'error', message: 'Invalid parameters!'} );
887 sendJson(res, {status: 'ok', message: 'Created new lecture'} );
893 app.get( '/course/:id/edit', loadUser, loadCourse, function( req, res) {
894 var course = req.course;
898 res.render( 'course/new', {course: course} )
900 req.flash( 'error', 'You don\'t have permission to do that' )
901 res.redirect( '/schools' );
905 // Recieve Course Edit Form
906 app.post( '/course/:id/edit', loadUser, loadCourse, function( req, res ) {
907 var course = req.course;
911 var courseChanges = req.body;
912 course.number = courseChanges.number;
913 course.name = courseChanges.name;
914 course.description = courseChanges.description;
915 course.department = courseChanges.department;
917 course.save(function(err) {
919 req.flash( 'error', 'There was an error saving the course' );
921 res.redirect( '/course/'+ course._id.toString());
924 req.flash( 'error', 'You don\'t have permission to do that' )
925 res.redirect( '/schools' );
930 app.get( '/course/:id/delete', loadUser, loadCourse, function( req, res) {
931 var course = req.course;
935 course.delete(function( err ) {
936 if ( err ) req.flash( 'info', 'There was a problem removing course: ' + err )
937 else req.flash( 'info', 'Successfully removed course' )
938 res.redirect( '/schools' );
941 req.flash( 'error', 'You don\'t have permission to do that' )
942 res.redirect( '/schools' );
946 // Subscribe to course
947 // XXX Not currently used for anything
948 app.get( '/course/:id/subscribe', loadUser, loadCourse, function( req, res ) {
949 var course = req.course;
950 var userId = req.user._id;
952 course.subscribe( userId, function( err ) {
954 req.flash( 'error', 'Error subscribing to course!' );
957 res.redirect( '/course/' + course._id );
961 // Unsubscribe from course
962 // XXX Not currently used for anything
963 app.get( '/course/:id/unsubscribe', loadUser, loadCourse, function( req, res ) {
964 var course = req.course;
965 var userId = req.user._id;
967 course.unsubscribe( userId, function( err ) {
969 req.flash( 'error', 'Error unsubscribing from course!' );
972 res.redirect( '/course/' + course._id );
979 // Display individual lecture and related notes
980 app.get( '/lecture/:id', checkAjax, loadUser, loadLecture, function( req, res ) {
981 var lecture = req.lecture;
983 // Grab the associated course
984 // XXX this should be done with DBRefs eventually
985 Course.findById( lecture.course, function( err, course ) {
987 // If course is found, find instructor information to be displayed on page
988 User.findById( course.instructor, function( err, instructor ) {
989 // Pull out our notes
990 Note.find( { 'lecture' : lecture._id } ).sort( 'name', '1' ).run( function( err, notes ) {
991 if ( !req.user.loggedIn || !req.lecture.authorized ) {
992 // Loop through notes and only return those that are public if the
993 // user is not logged in or not authorized for that lecture
994 notes = notes.filter(function( note ) {
995 if ( note.public ) return note;
998 var sanitizedInstructor = instructor.sanitized;
999 var sanitizedLecture = lecture.sanitized;
1000 if (!lecture.authorized) {
1001 delete sanitizedInstructor.email;
1003 sanitizedLecture.authorized = lecture.authorized;
1006 'lecture' : sanitizedLecture,
1007 'course' : course.sanitized,
1008 'instructor' : sanitizedInstructor,
1009 'notes' : notes.map(function(note) {
1010 return note.sanitized;
1016 sendJson(res, { status: 'not_found', msg: 'This course is orphaned' })
1022 // Recieve new note form
1023 app.post( '/lecture/:id', checkAjax, loadUser, loadLecture, function( req, res ) {
1024 var lecture = req.lecture;
1026 if( ( ! lecture ) || ( ! lecture.authorized ) ) {
1027 return sendJson(res, {status: 'error', message: 'There was a problem trying to create a note pad'})
1030 // Create note from Note schema
1031 var note = new Note;
1033 // Populate note from form data
1034 note.name = req.body.name;
1035 note.date = req.body.date;
1036 note.lecture = lecture._id;
1037 note.public = req.body.private ? false : true;
1038 note.creator = req.user._id;
1040 // Save note to database
1041 note.save( function( err ) {
1043 // XXX better validation
1044 sendJson(res, {status: 'error', message: 'There was a problem trying to create a note pad'})
1046 sendJson(res, {status: 'ok', message: 'Successfully created a new note pad'})
1052 // Display individual note page
1053 app.get( '/note/:id', /*checkAjax,*/ loadUser, loadNote, function( req, res ) {
1054 var note = req.note;
1055 // Set read only id for etherpad-lite or false for later check
1056 var roID = note.roID || false;
1058 var lectureId = note.lecture;
1060 // Count the amount of visits, but only once per session
1061 if ( req.session.visited ) {
1062 if ( req.session.visited.indexOf( note._id.toString() ) == -1 ) {
1063 req.session.visited.push( note._id );
1067 req.session.visited = [];
1068 req.session.visited.push( note._id );
1072 // If a read only id exists process note
1076 // If read only id doesn't, then fetch the read only id from the database and then
1078 // XXX Soon to be depracated due to a new API in etherpad that makes for a
1079 // much cleaner solution.
1080 db.open('mongodb://' + app.set( 'dbHost' ) + '/etherpad/etherpad', function( err, epl ) {
1081 epl.findOne( { key: 'pad2readonly:' + note._id }, function(err, record) {
1083 roID = record.value.replace(/"/g, '');
1092 function processReq() {
1094 Lecture.findById( lectureId, function( err, lecture ) {
1096 req.flash( 'error', 'That notes page is orphaned!' );
1098 res.redirect( '/' );
1100 // Find notes based on lecture id, which will be displayed in a dropdown
1102 Note.find( { 'lecture' : lecture._id }, function( err, otherNotes ) {
1105 'host' : serverHost,
1106 'note' : note.sanitized,
1107 'lecture' : lecture.sanitized,
1108 'otherNotes' : otherNotes.map(function(note) {
1109 return note.sanitized;
1116 // User is logged in and sees full notepad
1118 res.render( 'notes/index', {
1119 'layout' : 'noteLayout',
1120 'host' : serverHost,
1122 'lecture' : lecture,
1123 'otherNotes' : otherNotes,
1126 'stylesheets' : [ 'dropdown.css', 'fc2.css' ],
1127 'javascripts' : [ 'dropdown.js', 'counts.js', 'backchannel.js', 'jquery.tmpl.min.js' ]
1130 // User is not logged in and sees notepad that is public
1131 res.render( 'notes/public', {
1132 'layout' : 'noteLayout',
1133 'host' : serverHost,
1135 'otherNotes' : otherNotes,
1137 'lecture' : lecture,
1138 'stylesheets' : [ 'dropdown.css', 'fc2.css' ],
1139 'javascripts' : [ 'dropdown.js', 'counts.js', 'backchannel.js', 'jquery.tmpl.min.js' ]
1147 // Static pages and redirects
1149 app.get( '/about', loadUser, function( req, res ) {
1150 res.redirect( 'http://blog.finalsclub.org/about.html' );
1153 app.get( '/press', loadUser, function( req, res ) {
1154 res.render( 'static/press' );
1157 app.get( '/conduct', loadUser, function( req, res ) {
1158 res.render( 'static/conduct' );
1161 app.get( '/legal', loadUser, function( req, res ) {
1162 res.redirect( 'http://blog.finalsclub.org/legal.html' );
1165 app.get( '/contact', loadUser, function( req, res ) {
1166 res.redirect( 'http://blog.finalsclub.org/contact.html' );
1169 app.get( '/privacy', loadUser, function( req, res ) {
1170 res.render( 'static/privacy' );
1175 // Authentication routes
1176 // These are used for logging in, logging out, registering
1177 // and other user authentication purposes
1179 // Render login page
1181 app.get( '/login', function( req, res ) {
1182 log3("get login page")
1184 res.render( 'login' );
1188 app.get( '/checkuser', checkAjax, loadUser, function( req, res ) {
1189 sendJson(res, {user: req.user.sanitized});
1192 // Recieve login form
1193 app.post( '/login', checkAjax, function( req, res ) {
1194 var email = req.body.email;
1195 var password = req.body.password;
1196 log3("post login ...")
1198 // Find user from email
1199 User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
1203 // If user exists, check if activated, if not notify them and send them to
1206 if( ! user.activated ) {
1207 // (undocumented) markdown-esque link functionality in req.flash
1208 req.session.activateCode = user._id;
1209 sendJson(res, {status: 'error', message: 'This account isn\'t activated.'} );
1212 // If user is activated, check if their password is correct
1213 if( user.authenticate( password ) ) {
1216 var sid = req.sessionID;
1220 // Set the session then save the user to the database
1221 user.save( function() {
1222 var redirect = req.session.redirect;
1224 // login complete, remember the user's email for next time
1225 req.session.email = email;
1227 // alert the successful login
1228 sendJson(res, {status: 'ok', message:'Successfully logged in!'} );
1230 // redirect to profile if we don't have a stashed request
1231 //res.redirect( redirect || '/profile' );
1234 // Notify user of bad login
1235 sendJson(res, {status: 'error', message: 'Invalid login!'} );
1237 //res.render( 'login' );
1241 // Notify user of bad login
1243 sendJson(res, {status: 'error', message: 'Invalid login!'} );
1245 //res.render( 'login' );
1250 // Recieve reset password request form
1251 app.post( '/resetpass', checkAjax, function( req, res ) {
1252 log3("post resetpw");
1253 var email = req.body.email
1257 User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
1260 // If user exists, create reset code
1261 var resetPassCode = hat(64);
1262 user.setResetPassCode(resetPassCode);
1264 // Construct url that the user can then click to reset password
1265 var resetPassUrl = 'http://' + serverHost + ((app.address().port != 80)? ':'+app.address().port: '') + '/resetpw/' + resetPassCode;
1267 // Save user to database
1268 user.save( function( err ) {
1269 log3('save '+user.email);
1271 // Construct email and send it to the user
1275 'subject' : 'Your FinalsClub.org Password has been Reset!',
1277 'template' : 'userPasswordReset',
1279 'resetPassCode' : resetPassCode,
1280 'resetPassUrl' : resetPassUrl
1284 mailer.send( message, function( err, result ) {
1286 // XXX: Add route to resend this email
1288 console.log( 'Error sending user password reset email!' );
1290 console.log( 'Successfully sent user password reset email.' );
1295 // Render request success page
1296 sendJson(res, {status: 'ok', message: 'Your password has been reset. An email has been sent to ' + email })
1300 sendJson(res, {status: 'error', message: 'We were unable to reset the password using that email address. Please try again.' })
1305 // Recieve reset password form
1306 app.post( '/resetpw/:id', checkAjax, function( req, res ) {
1307 log3("post resetpw.code");
1308 var resetPassCode = req.params.id
1309 var email = req.body.email
1310 var pass1 = req.body.pass1
1311 var pass2 = req.body.pass2
1313 // Find user by email
1314 User.findOne( { 'email' : email.toLowerCase() }, function( err, user ) {
1316 // If user exists, and the resetPassCode is valid, pass1 and pass2 match, then
1317 // save user with new password and display success message.
1319 var valid = user.resetPassword(resetPassCode, pass1, pass2);
1321 user.save( function( err ) {
1322 sendJson(res, {status: 'ok', message: 'Your password has been reset. You can now login with your the new password you just created.'})
1326 // If there was a problem, notify user
1328 sendJson(res, {status: 'error', message: 'We were unable to reset the password. Please try again.' })
1333 // Display registration page
1335 app.get( '/register', function( req, res ) {
1336 log3("get reg page");
1338 // Populate school dropdown list
1339 School.find( {} ).sort( 'name', '1' ).run( function( err, schools ) {
1340 res.render( 'register', { 'schools' : schools } );
1345 // Recieve registration form
1346 app.post( '/register', checkAjax, function( req, res ) {
1347 var sid = req.sessionId;
1349 // Create new user from User schema
1350 var user = new User;
1352 // Populate user from form
1353 user.email = req.body.email.toLowerCase();
1354 user.password = req.body.password;
1356 // If school is set to other, then fill in school as what the user entered
1357 user.school = req.body.school === 'Other' ? req.body.otherSchool : req.body.school;
1358 user.name = req.body.name;
1359 user.affil = req.body.affil;
1360 user.activated = false;
1363 if ( ( user.email === '' ) || ( !isValidEmail( user.email ) ) ) {
1364 return sendJson(res, {status: 'error', message: 'Please enter a valid email'} );
1367 // Check if password is greater than 6 characters, otherwise notify user
1368 if ( req.body.password.length < 6 ) {
1369 return sendJson(res, {status: 'error', message: 'Please enter a password longer than eight characters'} );
1372 // Pull out hostname from email
1373 var hostname = user.email.split( '@' ).pop();
1375 // Check if email is from one of the special domains
1376 if( /^(finalsclub.org)$/.test( hostname ) ) {
1380 // Save user to database
1381 user.save( function( err ) {
1382 // If error, check if it is because the user already exists, if so
1383 // get the user information and let them know
1385 if( /dup key/.test( err.message ) ) {
1386 // attempting to register an existing address
1387 User.findOne({ 'email' : user.email }, function(err, result ) {
1388 if (result.activated) {
1389 // If activated, make sure they know how to contact the admin
1390 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'} );
1392 // If not activated, direct them to the resendActivation page
1393 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'} );
1397 // If any other type of error, prompt them to enter the registration again
1398 return sendJson(res, {status: 'error', message: 'An error occurred during registration.'} );
1401 // send user activation email
1402 sendUserActivation( user );
1404 // Check if the hostname matches any in the approved schools
1405 School.findOne( { 'hostnames' : hostname }, function( err, school ) {
1407 // If there is a match, send associated welcome message
1408 sendUserWelcome( user, true );
1409 log3('school recognized '+school.name);
1410 // If no users exist for the school, create empty array
1411 if (!school.users) school.users = [];
1412 // Add user to the school
1413 school.users.push( user._id );
1415 // Save school to the database
1416 school.save( function( err ) {
1417 log3('school.save() done');
1418 // Notify user that they have been added to the school
1419 sendJson(res, {status: 'ok', message: 'You have automatically been added to the ' + school.name + ' network. Please check your email for the activation link'} );
1421 // Construct admin email about user registration
1425 'subject' : 'FC User Registration : User added to ' + school.name,
1427 'template' : 'userSchool',
1433 // If there isn't a match, send associated welcome message
1434 sendUserWelcome( user, false );
1435 // Tell user to check for activation link
1436 sendJson(res, {status: 'ok', message: 'Your account has been created, please check your email for the activation link'} );
1437 // Construct admin email about user registration
1441 'subject' : 'FC User Registration : Email did not match any schools',
1443 'template' : 'userNoSchool',
1449 // Send email to admin
1450 mailer.send( message, function( err, result ) {
1453 console.log( 'Error sending user has no school email to admin\nError Message: '+err.Message );
1455 console.log( 'Successfully sent user has no school email to admin.' );
1465 // Display resendActivation request page
1466 app.get( '/resendActivation', function( req, res ) {
1467 var activateCode = req.session.activateCode;
1469 // Check if user exists by activateCode set in their session
1470 User.findById( activateCode, function( err, user ) {
1471 if( ( ! user ) || ( user.activated ) ) {
1472 res.redirect( '/' );
1474 // Send activation and redirect to login
1475 sendUserActivation( user );
1477 req.flash( 'info', 'Your activation code has been resent.' );
1479 res.redirect( '/login' );
1484 // Display activation page
1485 app.get( '/activate/:code', checkAjax, function( req, res ) {
1486 var code = req.params.code;
1488 // XXX could break this out into a middleware
1490 return sendJson(res, {status:'error', message: 'Invalid activation code!'} );
1493 // Find user by activation code
1494 User.findById( code, function( err, user ) {
1495 if( err || ! user ) {
1496 // If not found, notify user of invalid code
1497 sendJson(res, {status:'error', message:'Invalid activation code!'} );
1499 // If valid, then activate user
1500 user.activated = true;
1502 // Regenerate our session and log in as the new user
1503 req.session.regenerate( function() {
1504 user.session = req.sessionID;
1506 // Save user to database
1507 user.save( function( err ) {
1509 sendJson(res, {status: 'error', message: 'Unable to activate account.'} );
1511 sendJson(res, {status: 'info', message: 'Account successfully activated. Please complete your profile.'} );
1520 app.get( '/logout', checkAjax, function( req, res ) {
1521 sys.puts("logging out");
1522 var sid = req.sessionID;
1524 // Find user by session id
1525 User.findOne( { 'session' : sid }, function( err, user ) {
1527 // Empty out session id
1530 // Save user to database
1531 user.save( function( err ) {
1532 sendJson(res, {status: 'ok', message: 'Successfully logged out'});
1535 sendJson(res, {status: 'ok', message: ''});
1540 // Recieve profile edit page form
1541 app.post( '/profile', checkAjax, loadUser, loggedIn, function( req, res ) {
1542 var user = req.user;
1543 var fields = req.body;
1546 var wasComplete = user.isComplete;
1548 if( ! fields.name ) {
1549 return sendJson(res, {status: 'error', message: 'Please enter a valid name!'} );
1551 user.name = fields.name;
1554 if( [ 'Student', 'Teachers Assistant' ].indexOf( fields.affiliation ) == -1 ) {
1555 return sendJson(res, {status: 'error', message: 'Please select a valid affiliation!'} );
1557 user.affil = fields.affiliation;
1560 if( fields.existingPassword || fields.newPassword || fields.newPasswordConfirm ) {
1561 // changing password
1562 if( ( ! user.hashed ) || user.authenticate( fields.existingPassword ) ) {
1563 if( fields.newPassword === fields.newPasswordConfirm ) {
1564 // test password strength?
1566 user.password = fields.newPassword;
1568 return sendJson(res, {status: 'error', message: 'Mismatch in new password!'} );
1571 return sendJson(res, {status: 'error', message: 'Please supply your existing password.'} );
1575 user.major = fields.major;
1576 user.bio = fields.bio;
1578 user.showName = ( fields.showName ? true : false );
1580 user.save( function( err ) {
1582 sendJson(res, {status: 'error', message: 'Unable to save user profile!'} );
1584 if( ( user.isComplete ) && ( ! wasComplete ) ) {
1585 sendJson(res, {status: 'ok', message: 'Your account is now fully activated. Thank you for joining FinalsClub!'} );
1587 sendJson(res, {status:'ok', message:'Your profile was successfully updated!'} );
1596 function loadSubject( req, res, next ) {
1597 if( url.parse( req.url ).pathname.match(/subject/) ) {
1598 ArchivedSubject.findOne({id: req.params.id }, function(err, subject) {
1599 if ( err || !subject) {
1600 sendJson(res, {status: 'not_found', message: 'Subject with this ID does not exist'} )
1602 req.subject = subject;
1611 function loadOldCourse( req, res, next ) {
1612 if( url.parse( req.url ).pathname.match(/course/) ) {
1613 ArchivedCourse.findOne({id: req.params.id }, function(err, course) {
1614 if ( err || !course ) {
1615 sendJson(res, {status: 'not_found', message: 'Course with this ID does not exist'} )
1617 req.course = course;
1626 var featuredCourses = [
1627 {name: 'The Human Mind', 'id': 1563},
1628 {name: 'Justice', 'id': 797},
1629 {name: 'Protest Literature', 'id': 1681},
1630 {name: 'Animal Cognition', 'id': 681},
1631 {name: 'Positive Psychology', 'id': 1793},
1632 {name: 'Social Psychology', 'id': 660},
1633 {name: 'The Book from Gutenberg to the Internet', 'id': 1439},
1634 {name: 'Cyberspace in Court', 'id': 1446},
1635 {name: 'Nazi Cinema', 'id': 2586},
1636 {name: 'Media and the American Mind', 'id': 2583},
1637 {name: 'Social Thought in Modern America', 'id': 2585},
1638 {name: 'Major British Writers II', 'id': 869},
1639 {name: 'Civil Procedure', 'id': 2589},
1640 {name: 'Evidence', 'id': 2590},
1641 {name: 'Management of Industrial and Nonprofit Organizations', 'id': 2591},
1644 app.get( '/learn', loadUser, function( req, res ) {
1645 res.render( 'archive/learn', { 'courses' : featuredCourses } );
1648 app.get( '/learn/random', checkAjax, function( req, res ) {
1649 sendJson(res, {status: 'ok', data: '/archive/course/'+ featuredCourses[Math.floor(Math.random()*featuredCourses.length)].id });
1652 app.get( '/archive', checkAjax, loadUser, function( req, res ) {
1653 ArchivedSubject.find({}).sort( 'name', '1' ).run( function( err, subjects ) {
1654 if ( err || subjects.length === 0) {
1655 sendJson(res, {status: 'error', message: 'There was a problem gathering the archived courses, please try again later.'} );
1657 sendJson(res, { 'subjects' : subjects, 'user': req.user.sanitized } );
1662 app.get( '/archive/subject/:id', checkAjax, loadUser, loadSubject, function( req, res ) {
1663 ArchivedCourse.find({subject_id: req.params.id}).sort('name', '1').run(function(err, courses) {
1664 if ( err || courses.length === 0 ) {
1665 sendJson(res, {status: 'not_found', message: 'There are no archived courses'} );
1667 sendJson(res, { 'courses' : courses, 'subject': req.subject, 'user': req.user.sanitized } );
1672 app.get( '/archive/course/:id', checkAjax, loadUser, loadOldCourse, function( req, res ) {
1673 ArchivedNote.find({course_id: req.params.id}).sort('name', '1').run(function(err, notes) {
1674 if ( err || notes.length === 0) {
1675 sendJson(res, {status: 'not_found', message: 'There are no notes in this course'} );
1677 notes = notes.map(function(note) { return note.sanitized });
1678 sendJson(res, { 'notes': notes, 'course' : req.course, 'user': req.user.sanitized } );
1683 app.get( '/archive/note/:id', checkAjax, loadUser, function( req, res ) {
1684 console.log( "id="+req.params.id)
1685 ArchivedNote.findById(req.params.id, function(err, note) {
1686 if ( err || !note ) {
1687 sendJson(res, {status: 'not_found', message: 'This is not a valid id for a note'} );
1689 ArchivedCourse.findOne({id: note.course_id}, function(err, course) {
1690 if ( err || !course ) {
1691 sendJson(res, {status: 'not_found', message: 'There is no course for this note'} )
1693 sendJson(res, { 'layout' : 'notesLayout', 'note' : note, 'course': course, 'user': req.user.sanitized } );
1701 app.get( '*', function(req, res) {
1702 res.sendfile('public/index.html');
1707 // The finalsclub backchannel server uses socket.io to handle communication between the server and
1708 // the browser which facilitates near realtime interaction. This allows the user to post questions
1709 // and comments and other users to get those almost immediately after they are posted, without
1710 // reloading the page or pressing a button to refresh.
1712 // The server code itself is fairly simple, mainly taking incomming messages from client browsers,
1713 // saving the data to the database, and then sending it out to everyone else connected.
1716 // Posts - Posts are the main items in backchannel, useful for questions or discussion points
1717 // [[ example object needed with explanation E.G:
1719 Post: { postID: '999-1',
1721 userName: 'Bob Jones',
1722 userAffil: 'Instructor',
1723 body: 'This is the text content of the post.',
1724 comments: { {<commentObj>, <commentObj>, ...},
1726 votes: [ <userID>, <userID>, ...],
1727 reports: [ <userID>, <userID>, ...]
1729 Comment: { body: 'foo bar', userName: 'Bob Jones', userAffil: 'Instructor' }
1731 if anonymous: userName => 'Anonymous', userAffil => 'N/A'
1736 // Comments - Comments are replies to posts, for clarification or answering questions
1737 // [[ example object needed]]
1738 // Votes - Votes signifyg a users approval of a post
1739 // [[ example object needed]]
1740 // Flags - Flagging a post signifies that it is against the rules, 2 flags moves it to the bottomw
1741 // [[ example object needed]]
1745 // body - Main content of the post
1746 // userId - Not currently used, but would contain the users id that made the post
1747 // userName - Users name that made post
1748 // userAffil - Users affiliation to their school
1749 // public - Boolean which denotes if the post is public to everyone, or private to school users only
1750 // date - Date post was made, updates when any comments are made for the post
1751 // comments - An array of comments which contain a body, userName, and userAffil
1752 // votes - An array of user ids which are the users that voted
1753 // [[ example needed ]]
1754 // reports - An array of user ids which are the users that reported the post
1755 // [[ reports would be "this post is flagged as inappropriate"? ]]
1756 // [[ bruml: consistent terminology needed ]]
1758 // Posts and comments can be made anonymously. When a post is anonymous, the users info is stripped
1759 // from the post and the userName is set to Anonymous and the userAffil to N/A. This is to allow
1760 // users the ability to make posts or comments that they might not otherwise due to not wanting
1761 // the content of the post/comment to be attributed to them.
1763 // Each time a user connects to the server, it passes through authorization which checks for a cookie
1764 // that is set by Express. If a session exists and it is for a valid logged in user, then handshake.user
1765 // is set to the users data, otherwise it is set to false. handshake.user is used later on to check if a
1766 // user is logged in, and if so display information that otherwise might not be visible to them if they
1767 // aren't apart of a particular school.
1769 // After the authorization step, the client browser sends the lecture id which is rendered into the html
1770 // page on page load from Express. This is then used to assign a 'room' for the user which is grouped
1771 // by lecture. All posts are grouped by lecture, and only exist for that lecture. After the user is
1772 // grouped into a 'room', they are sent a payload of all existing posts for that lecture, which are then
1773 // rendered in the browser.
1775 // Everything else from this point on is handled in an event form and requires a user initiating it. The
1776 // events are as follows.
1779 // A user makes a new post. A payload of data containing the post and lecture id is sent to the server.
1780 // The server recieves the data, assembles a new post object for the database and then fills it with
1781 // the appropriate data. If a user selected for the post to be anonymous, the userName and userAffil are
1782 // replaced. If the user chose for the post to be private, then public will be set to false and it
1783 // will be filtered from being sent to users not logged into and not having access to the school. Once
1784 // the post has been created and saved into the database, it is sent to all connected users to that
1785 // particular lecture, unless it is private, than only logged in users will get it.
1788 // A user votes for a post. A payload of data containing the post id and lecture id are sent along with
1789 // the user id. A new vote is created by first fetching the parent post, then adding the user id to the
1790 // votes array, and then the post is subsequently saved back to the database and sent to all connected
1791 // users unless the post is private, which then it will be only sent to logged in users.
1794 // Similar to the vote event, reports are sent as a payload of a post id, lecture id, and user id, which
1795 // are then used to fetch the parent post, add the user id to the reports array, and then saved to the db.
1796 // Then the report is sent out to all connected users unless it is a private post, which will be only sent
1797 // to logged in users. On the client, once a post has more two (2) or more reports, it will be moved to the
1798 // bottom of the interface.
1801 // A user posts a comment to a post. A payload of data containing the post id, lecture id, comment body,
1802 // user name, and user affiliation are sent to the server, which are then used to find the parent post
1803 // and then a new comment object is assembled. When new comments are made, it updates the posts date
1804 // which allows the post to be sorted by date and the posts with the freshest comments would be pushed
1805 // to the top of the interface. The comment can be anonymous, which then will have the user
1806 // name and affiliation stripped before saving to the database. The comment then will be sent out to all
1807 // connected users unless the post is private, then only logged in users will recieve the comment.
1809 var io = require( 'socket.io' ).listen( app );
1811 var Post = mongoose.model( 'Post' );
1813 io.set('authorization', function ( handshake, next ) {
1814 var rawCookie = handshake.headers.cookie;
1816 handshake.cookie = parseCookie(rawCookie);
1817 handshake.sid = handshake.cookie['connect.sid'];
1819 if ( handshake.sid ) {
1820 app.set( 'sessionStore' ).get( handshake.sid, function( err, session ) {
1822 handshake.user = false;
1823 return next(null, true);
1825 // bake a new session object for full r/w
1826 handshake.session = new Session( handshake, session );
1828 User.findOne( { session : handshake.sid }, function( err, user ) {
1830 handshake.user = user;
1831 return next(null, true);
1833 handshake.user = false;
1834 return next(null, true);
1842 return next(null, true);
1846 var backchannel = new Backchannel(app, io.of('/backchannel'), {
1847 // TODO: if lecture belongs to course (find pinker's courseId) pass a 'no-answers' true/false
1848 subscribe: function(lecture, send) {
1849 Post.find({'lecture': lecture}, function(err, posts) {
1853 post: function(fillPost) {
1854 var post = new Post;
1855 fillPost(post, function(send) {
1856 post.save(function(err) {
1861 items: function(postId, addItem) {
1862 Post.findById(postId, function( err, post ) {
1863 addItem(post, function(send) {
1864 post.save(function(err) {
1879 .on( 'connection', function( socket ) {
1880 // pull out user/session information etc.
1881 var handshake = socket.handshake;
1882 var userID = handshake.user._id;
1889 socket.on( 'join', function( note ) {
1890 if (handshake.user === false) {
1892 // XXX: replace by addToSet (once it's implemented in mongoose)
1893 Note.findById( noteID, function( err, note ) {
1895 if( note.collaborators.indexOf( userID ) == -1 ) {
1896 note.collaborators.push( userID );
1904 socket.on( 'watch', function( l ) {
1905 var sendCounts = function() {
1908 Note.find( { '_id' : { '$in' : watched } }, function( err, notes ) {
1911 function( note, callback ) {
1913 var count = note.collaborators.length;
1919 socket.emit( 'counts', send );
1921 timer = setTimeout( sendCounts, 5000 );
1927 Note.find( { 'lecture' : l }, [ '_id' ], function( err, notes ) {
1928 notes.forEach( function( note ) {
1929 watched.push( note._id );
1936 socket.on( 'disconnect', function() {
1937 clearTimeout( timer );
1939 if (handshake.user === false) {
1940 // XXX: replace with $pull once it's available
1942 Note.findById( noteID, function( err, note ) {
1944 var index = note.collaborators.indexOf( userID );
1947 note.collaborators.splice( index, 1 );
1958 // Exception Catch-All
1960 process.on('uncaughtException', function (e) {
1961 console.log("!!!!!! UNCAUGHT EXCEPTION\n" + e.stack);
1967 // mongoose now exepects a mongo url
1968 mongoose.connect( 'mongodb://localhost/fc' ); // FIXME: make relative to hostname
1970 var mailer = new Mailer( app.set('awsAccessKey'), app.set('awsSecretKey') );
1972 everyauth.helpExpress(app);
1974 app.listen( serverPort, function() {
1975 console.log( "Express server listening on port %d in %s mode", app.address().port, app.settings.env );
1977 // if run as root, downgrade to the owner of this file
1978 if (process.getuid() === 0) {
1979 require('fs').stat(__filename, function(err, stats) {
1980 if (err) { return console.log(err); }
1981 process.setuid(stats.uid);
1986 function isValidEmail(email) {
1987 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])?/;
1988 return email.match(re);