Meteor.startup(function () {
    if (! Meteor.settings.uploadDir) {
        console.log('Please set the upload directory in your settings file.');
        process.exit(1);
    }

    // create accounts
    if (typeof initialUsers !== "undefined" && typeof defaultPassword !== "undefined") {
        _.each(initialUsers, function (user) {
            if (! Meteor.users.findOne({username: user.username})) {

                var password = defaultPassword;
                if (user.password) {
                    password = user.password;
                }
                // Create the user
                var id = Accounts.createUser({username: user.username, password: password,
                                              profile: {name: user.name}});

                // By default, users can upload and aren't admins, but this can be overridden in
                // the initialUsers object
                var additional = {canUpload: true, isAdmin: false, grade: user.grade};
                if (user.canUpload !== undefined) {
                    additional.canUpload = user.canUpload;
                }
                if (user.isAdmin !== undefined) {
                    additional.isAdmin = user.isAdmin;
                }
                if (additional.canUpload) {
                    additional.htmlFiles = [];
                }
                // add the additional fields into the database
                Meteor.users.update({_id: id}, {$set : additional});
            }
        });
    }

});

Meteor.publish('userData', function () {
    if (this.userId) {
        return Meteor.users.find({},
                                 {fields: {'username': 1, 'grade': 1, 'profile': 1,
                                           'isAdmin': 1, 'canUpload': 1,
                                           'htmlFiles': 1}});
    } else {
        this.ready();
    }
});

function authorizeFilesChange(userId, doc) {
    if (! userId) {
        return false;
    }
    var user = Meteor.users.findOne(userId);
    if (!user || !user.canUpload) {
        return false;
    }

    if (!doc.owner || (doc.owner !== userId && !user.isAdmin)) {
        return false;
    }

    return true;
}

Files.allow({
    'insert': authorizeFilesChange,
    'update': authorizeFilesChange,
});



// read from mongo
WebApp.connectHandlers.use(function (req, res, next) {

    // gross way of getting our cookie value
    var match = /simple-portfolio-server=([-_A-Za-z0-9]+)/.exec(req.headers.cookie);
    if (match) {
        var hashedToken = Accounts._hashLoginToken(match[1]);
        var loggedInUser = Meteor.users.findOne({'services.resume.loginTokens.hashedToken': hashedToken});
        if (loggedInUser) {

            // looking for URLs of form /username/filename
            var urlParts = req.url.split('/');
            if (urlParts.length === 3) {
                var username = urlParts[1];
                var filename = urlParts[2];
                var user = Meteor.users.findOne({username: username})
                if (user) {
                    var files = Files.find({owner: user._id, "original.name": filename}).fetch();
                    // the user might have uploaded multiple versions. Use the latest one
                    files = _.sortBy(files, function(item) {return -item.uploadedAt});
                    if (files.length > 0) {
                        var filepath = Npm.require("path").join(Meteor.settings.uploadDir,
                                                                files[0].copies.files.key);
                        Meteor.npmRequire("send")(req, filepath).pipe(res);
                        return;
                    }
                    res.writeHead(404, {'Content-Type': 'text/event-stream'});
                    res.end();
                    return;
                }
            }
        }
    }

    next();

});

Meteor.methods({
    addHtmlFile: function (fileName, ownerId) {
        if (Meteor.userId() && Meteor.user().canUpload && (Meteor.userId() == ownerId || Meteor.user().isAdmin)) {
            Meteor.users.update({_id:ownerId}, {$addToSet:{'htmlFiles': fileName}})
        }
    }
});

@@ -2766,16 +2766,55 @@
 ilename%0A
+            if (req.url !== '/') %7B%0A    
         
@@ -2860,24 +2860,28 @@
             
+ 
+   
 if (urlParts
@@ -2905,32 +2905,36 @@
                 
+    
 var username = u
@@ -2953,32 +2953,36 @@
                 
+   
+ 
 var filename = u
@@ -2993,16 +2993,20 @@
 rts%5B2%5D;%0A
+    
         
@@ -3075,32 +3075,36 @@
                 
+    
 if (user) %7B%0A    
@@ -3111,32 +3111,36 @@
                 
+ 
+   
 var files = File
@@ -3217,24 +3217,28 @@
             
+    
 // the user 
@@ -3311,24 +3311,28 @@
             
+   
+ 
 files = _.so
@@ -3402,24 +3402,28 @@
             
+    
 if (files.le
@@ -3430,24 +3430,28 @@
 ngth %3E 0) %7B%0A
+    
             
@@ -3589,24 +3589,28 @@
             
+    
 files%5B0%5D.cop
@@ -3625,16 +3625,20 @@
 s.key);%0A
+    
         
@@ -3725,32 +3725,36 @@
             
+    
 return;%0A
             
@@ -3733,32 +3733,36 @@
         return;%0A
+    
                 
@@ -3763,32 +3763,68 @@
           %7D%0A    
+                %7D%0A                %7D%0A
                 
@@ -3894,28 +3894,24 @@
             
-    
 res.end();%0A 
@@ -3921,36 +3921,32 @@
             
-    
 return;%0A
             
@@ -3933,34 +3933,16 @@
 return;%0A
-                %7D%0A
         

Return a 404 for anything other than / if authenticated