Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 318 lines (261 sloc) 10.147 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
#!/usr/bin/env node

/*
* Jingo, wiki engine
* http://github.com/claudioc/jingo
*
* Copyright 2013 Claudio Cicali <claudio.cicali@gmail.com>
* Released under the MIT license
*/

var express = require('express')
  , http = require('http')
  , path = require('path')
  , passport = require('passport')
  , Fs = require('fs')
  , Git = require('./lib/gitmech')
  , Tools = require('./lib/tools')
  , Config = require('./lib/config')
  , Components = require('./lib/components')
  , expValidator = require('express-validator')
  , gravatar = require('gravatar')
  , Url = require('url')
  , GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
  , LocalStrategy = require('passport-local').Strategy
  , Flash = require('connect-flash')
  , program = require('commander');

program.version('0.6.1')
       .option('-c, --config <path>', 'Specify the config file')
       .option('-#, --hash-string <string>', 'Create an hash for a string')
       .option('-l, --local', 'Listen on localhost only')
       .option('-s, --sample-config', 'Dumps a config file template and exits')
       .parse(process.argv);

if (program.sampleConfig) {
  console.log(Config.sample());
  process.exit(0);
}

if (program.hashString) {
  console.log(Tools.hashify(program.hashString));
  process.exit(0);
}

if (!program.config || !Fs.existsSync(program.config)) {
  program.help();
  process.exit(-1);
}

Config.load(program.config);

try {
  Git.setup(Config.get("application.repository"), Config.get("application.docSubdir", ""));
} catch(e) {
  console.log(e.message)
  program.help()
  process.exit(-1);
}

// Global variables to be accessed from the routes module
global.app = express();
app.locals.Git = Git;
app.locals.Components = Components;
app.locals.appTitle = Config.get("application.title", "Jingo");
app.locals.port = Config.get("server.port", process.env.PORT || 6067);
app.locals.hostname = Config.get("server.hostname", "localhost");
app.locals.features = Config.get("features", {});

// For backward compatibility with version < 0.5, we set markitup as the
// default rich editor. For new installations, the default is codemirror
if (typeof app.locals.features.codemirror == 'undefined' &&
    typeof app.locals.features.markitup == 'undefined') {
  app.locals.features.markitup = true;
}

// This should never happen, of course
if (app.locals.features.markitup &&
    app.locals.features.codemirror) {
  app.locals.features.markitup = false;
}

// baseUrl is used as the public url
app.locals.baseUrl = Config.get("server.baseUrl", ("http://" + app.locals.hostname + ":" + app.locals.port));
app.locals.authorization = Config.get("authorization", { anonRead: false, validMatches: ".+" });
app.locals.secret = Config.get("application.secret", "jingo-secret-67");

var refspec = Config.get("application.remote") ? Config.get("application.remote").split(/\s+/) : "";
if (!refspec) {
  app.locals.remote = "";
  app.locals.branch = "";
} else {
  app.locals.remote = refspec[0].trim();
  app.locals.branch = refspec[1] ? refspec[1].trim() : "master";
}

app.locals.pushInterval = Config.get("application.pushInterval") ? parseInt(Config.get("application.pushInterval"), 10) * 1000 : 30000;
app.locals.coalesce = function(value, def) {
  return typeof value === 'undefined' ? def : value;
}
app.locals.pretty = true; // Pretty HTML output from Jade

var auth = app.locals.authentication = Config.get("authentication", { google: { enabled: true }, alone: { enabled: false } });

auth.google = auth.google || {enabled: false};
auth.alone = auth.alone || {enabled: false};

if ( !auth.google.enabled && !auth.alone.enabled ) {
  console.log("Error: no authentication method provided. Cannot continue.");
  process.exit(-1);
}

if (auth.google.enabled && (!auth.google.clientId || !auth.google.clientSecret)) {
  console.log("Error: invalid or missing authentication credentials for Google (clientId and/or clientSecret).");
  process.exit(-1);
}

Components.init(Git);

var routes = require("./routes");

app.configure(function() {
  app.use(express.errorHandler());
  app.set('port', app.locals.port);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.logger('default'));
  app.use(express.cookieParser(app.locals.secret));
  app.use(express.cookieSession({ secret: "jingo-" + app.locals.secret, cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }})); // a Month
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(expValidator());
  app.use(express.methodOverride());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(Flash());
  app.use(function (req, res, next) {
    res.locals({
      get user() {
        return req.user;
      },
      isAnonymous: function () {
        return !req.user;
      },
      canSearch: function () {
        return !!req.user || app.locals.authorization.anonRead;
      },
      gravatar: function(email) {
        return gravatar;
      },
      hasSidebar: Components.hasSidebar,
      hasFooter: Components.hasFooter,
      hasCustomStyle: Components.hasCustomStyle,
      hasCustomScript: Components.hasCustomScript,
      hasFeature: function(feature) {
        return !!app.locals.features[feature]
      }
    });

    next();
  });

  // Logic to include custom _footer, _sidebar, _script and _style.css
  app.use(function (req, res, next) {

    if (null === req.url.match(/^\/auth\//) &&
        null === req.url.match(/^\/misc\//) &&
        null === req.url.match(/^\/login/)) {
      Components.sidebar(function(content) { res.locals._sidebar = content; });
      Components.footer(function(content) { res.locals._footer = content; });
    }

    res.locals._style = Components.customStyle();
    res.locals._script = Components.customScript();

    next();
  });

  app.use(app.router);
});

function requireAuthentication(req, res, next) {
  if (!res.locals.user) {
    res.redirect("/login");
  } else {
    next();
  }
}

/*
* Passport configuration
*/

if (auth.google.enabled) {

  passport.use(new GoogleStrategy({
      clientID: auth.google.clientId,
      clientSecret: auth.google.clientSecret,
      // I will leave the horrible name as the default to make the painful creation
      // of the client id/secret simpler
      callbackURL: app.locals.baseUrl + '/oauth2callback'
    },

    function(accessToken, refreshToken, profile, done) {
      usedAuthentication("google");
      done(null, profile);
    }
  ));
}

if (auth.alone.enabled) {

  passport.use(new LocalStrategy(

    function(username, password, done) {

      var user = {
        displayName: auth.alone.username,
        email: auth.alone.email || ""
      };

      if (username.toLowerCase() != auth.alone.username.toLowerCase() || Tools.hashify(password) != auth.alone.passwordHash) {
        return done(null, false, { message: 'Incorrect username or password' });
      }

      usedAuthentication("alone");

      return done(null, user);
    }
  ));
}

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  if (user.emails && user.emails.length > 0) { // Google
    user.email = user.emails[0].value;
    delete user.emails;
  }
  user.asGitAuthor = user.displayName + " <" + user.email + ">";
  done(undefined, user);
});

function usedAuthentication(name) {
  for (var a in app.locals.authentication) {
    app.locals.authentication[a].used = (a == name);
  }
}

app.all("/pages/*", requireAuthentication);

if (!app.locals.authorization.anonRead) {
  app.all("/wiki/*", requireAuthentication);
  app.all("/search", requireAuthentication);
}

app.get ("/", routes.index);
app.get ("/wiki", routes.pageList);
app.get ("/wiki/:page", routes.pageShow);
app.get ("/wiki/:page/history", routes.pageHistory);
app.get ("/wiki/:page/:version", routes.pageShow);
app.get ("/wiki/:page/compare/:revisions", routes.pageCompare);

app.get ("/search", routes.search);

app.get ("/pages/new", routes.pageNew);
app.get ("/pages/new/:page", routes.pageNew);
app.post ("/pages", routes.pageCreate);

app.get ("/pages/:page/edit", routes.pageEdit);
app.put ("/pages/:page", routes.pageUpdate);
app.delete ("/pages/:page", routes.pageDestroy);

app.post ("/misc/preview", routes.miscPreview);
app.get ("/misc/syntax-reference", routes.miscSyntaxReference);
app.get ("/misc/existence", routes.miscExistence);

app.post ("/login", passport.authenticate('local', { successRedirect: '/auth/done', failureRedirect: '/login', failureFlash: true }));
app.get ("/login", routes.login);
app.get ("/logout", routes.logout);

app.get ("/auth/google", passport.authenticate('google', {
  scope: ['https://www.googleapis.com/auth/userinfo.email'] }
));

app.get ("/oauth2callback", passport.authenticate('google', { successRedirect: '/auth/done', failureRedirect: '/login' }));

app.get ("/auth/done", routes.authDone);

app.all('*', routes.error404);

var listenAddr = process.env.NW_ADDR || "";
if (Config.get("server.localOnly")) {
  listenAddr = "localhost";
}

http.createServer(app).listen(app.get('port'), listenAddr, function(){
  console.log((new Date()) + " - Jingo%sserver v%s listening on port %s", Config.get("server.localOnly") ? " (local) " : " ", program.version(), app.get('port'));
});

if (app.locals.remote != "") {
  setInterval(function() {
    Git.pull(app.locals.remote, app.locals.branch, function(err) {
      if (err) {
        console.log("Error: " + err);
      } else {
        Git.push(app.locals.remote, app.locals.branch, function(err) {
          if (err) {
            console.log("Error: " + err);
          }
        });
      }
    });
  }, app.locals.pushInterval);
}
Something went wrong with that request. Please try again.