Пример #1
0
module.exports = function(config) {
  var app = express();

  var nunjucksEnv = new nunjucks.Environment([
    new nunjucks.FileSystemLoader(path.join(__dirname, 'views'), true),
    new nunjucks.FileSystemLoader(path.join(__dirname, '../bower_components'), true),
    // Weird path because we're inside the bower module you're supposed to use
    new nunjucks.FileSystemLoader(path.join(__dirname, '../..'), true)
  ], {
    autoescape: true
  });

  nunjucksEnv.addFilter('instantiate', function (input) {
    var tmpl = new nunjucks.Template(input);
    return tmpl.render(this.getVariables());
  });

  var login = new WebmakerLogin({
    loginURL: config.LOGIN_URL,
    secretKey: config.SECRET_KEY
  });

  nunjucksEnv.express(app);

  app.use(express.logger('dev'));
  app.use(express.compress());
  app.use(express.json());
  app.use(express.urlencoded());

  app.use(login.cookieParser());
  app.use(login.cookieSession());

  // Setup locales with i18n
  app.use(i18n.middleware({
    supported_languages: ['en-US'],
    default_lang: 'en-US',
    mappings: require('webmaker-locale-mapping'),
    translation_directory: path.resolve(__dirname, '../locale')
  }));

  app.use(express.static(__dirname + '/..'));

  app.locals({
    bower_path: '',
    languages: i18n.getSupportLanguages()
  });

  app.get('/', function(req, res) {
    res.render('index.nunjucks');
  });

  app.post('/verify', login.handlers.verify);
  app.post('/authenticate', login.handlers.authenticate);
  app.post('/create', login.handlers.create);
  app.post('/logout', login.handlers.logout);
  app.post('/check-username', login.handlers.exists);

  return app;
};
module.exports = function localize(server, options) {
  let excludeLocaleInUrl = options.excludeLocaleInUrl || [];

  server.use(webmakerI18N.middleware({
    supported_languages: options.supported_languages,
    default_lang: "en-US",
    translation_directory: path.resolve(root, options.locale_dest)
  }));

  // Redirect routes without the locale in the url to one with it.
  server.use(function(req, res, next) {
    // Do not redirect to a url with the locale if the route is in the `exclude` list
    if(excludeLocaleInUrl.indexOf(req.path) !== -1) {
      return next();
    }

    let locale = (req.localeInfo && req.localeInfo.lang) ? req.localeInfo.lang : "en-US";

    if(req.originalUrl.indexOf(locale) === 1) {
      return next();
    }

    let langPrefs = req.localeInfo.otherLangPrefs.slice();
    langPrefs.unshift(req.localeInfo.lang);
    let urlLocale = req.originalUrl.match(/^\/([^\/]*)(\/|$)/)[1];
    let bestLanguage = bestlang(langPrefs, webmakerI18N.getSupportLanguages(), "en-US");
    let localizedUrl;

    if(knownLocales.indexOf(urlLocale) !== -1) {
      localizedUrl = req.originalUrl.replace(urlLocale, bestLanguage);
    } else {
      localizedUrl = path.join("/", bestLanguage, req.originalUrl);
    }

    res.redirect(307, localizedUrl);
  });

  let allLanguages = webmakerI18N.getAllLocaleCodes();
  let languages = {};
  webmakerI18N.getSupportLanguages().forEach(function(locale) {
    languages[locale] = allLanguages[locale];
  });

  server.locals.languages = languages;

  server.get("/strings/:lang?", webmakerI18N.stringsRoute("en-US"));
};
Пример #3
0
app.configure(function(){
  app.set('port', process.env.PORT || 3000);

  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');

  app.use(express.logger(function(tokens, req, res) {
    if (res.statusCode >= 400) // or whatever you want logged
      return express.logger.dev(tokens, req, res);
    return null;
  }));

  app.use(express.bodyParser());
  app.use(webmakerAuth.cookieParser());

  app.use(webmakerAuth.cookieSession());

  bundles.configure(app);

  // Setup locales with i18n
  app.use(i18n.middleware({
    supported_languages: ["*"],
    default_lang: "en-US",
    mappings: require("webmaker-locale-mapping"),
    translation_directory: path.resolve( __dirname, "locale" )
  }));

  app.use(express.favicon());

  if (process.env.HSTS_DISABLED != 'true') {
    // Use HSTS
    app.use(helmet.hsts());
  }

  if (process.env.DISABLE_XFO_HEADERS_DENY != 'true') {
    // No xframes allowed
    app.use(helmet.xframe('deny'));
  }

  if (process.env.IEXSS_PROTECTION_DISABLED != 'true') {
  // Use XSS protection
    app.use(helmet.iexss());
  }

  app.use(function(req, res, next) {
    res.removeHeader("x-powered-by");
    next();
  });

  app.use(express.methodOverride());

  app.use(app.router);

  app.use(connectFonts.setup({
    fonts: [require('connect-fonts-sourcesanspro')],
    allow_origin: process.env.ASSET_HOST,
    ua: 'all',
    maxage: MAX_FONT_AGE_MS
  }));

  // enable cors for test relevant assets
  app.use("/test_assets/ceci/", cors());
  app.use("/test_assets/ceci/", express.static(path.join(__dirname, 'public', 'ceci')));
  app.use("/test_assets/vendor/", cors());
  app.use("/test_assets/vendor/", express.static(path.join(__dirname, 'public', 'vendor')));

  app.use(lessMiddleware({
    src: __dirname + '/public',
    compress: true
  }));

  app.use('/', cors());
  app.use('/', express.static(path.join(__dirname, 'public')));

  enableRedirects(app);
});
Пример #4
0
  http.configure(function () {
    nunjucksEnv.express(http);

    http.disable("x-powered-by");

    if (!env.get("DISABLE_HTTP_LOGGING")) {
      http.use(express.logger());
    }

    http.use(helmet.iexss());
    http.use(helmet.contentTypeOptions());
    http.use(helmet.xframe());

    if (!!env.get("FORCE_SSL")) {
      http.use(helmet.hsts());
      http.enable("trust proxy");
    }

    http.use(express.json());
    http.use(express.urlencoded());
    http.use(webmakerAuth.cookieParser());
    http.use(webmakerAuth.cookieSession());

    // Setup locales with i18n
    http.use(i18n.middleware({
      supported_languages: env.get("SUPPORTED_LANGS"),
      default_lang: "en-US",
      mappings: require("webmaker-locale-mapping"),
      translation_directory: path.resolve(__dirname, "../../locale")
    }));

    http.locals({
      // audience and webmakerorg are duplicated because of i18n
      AUDIENCE: env.get("WEBMAKERORG"),
      WEBMAKERORG: env.get("WEBMAKERORG"),
      profile: env.get("PROFILE"),
      bower_path: "bower_components",
      personaHostname: env.get("PERSONA_HOSTNAME", "https://login.persona.org"),
      languages: i18n.getSupportLanguages()
    });

    // need to make sure router is after i18n.middleware
    http.use(http.router);

    var optimize = env.get("NODE_ENV") !== "development",
      tmpDir = path.join(require("os").tmpDir(), "mozilla.login.webmaker.org.build");

    // convert requests for ltr- or rtl-specific CSS back to the real filename,
    // as the rtltr-for-less package was a hack that was never meant to hit production.
    http.use(function rtltrRedirect(req, res, next) {
      var path = req.path;
      if (path.match(/css\/\w+\.(ltr|rtl)\.css/)) {
        res.redirect(path.replace(/\.(ltr|rtl)/, ""));
      } else {
        next();
      }
    });

    http.use(lessMiddleWare({
      once: optimize,
      debug: !optimize,
      dest: tmpDir,
      src: path.resolve(__dirname, "public"),
      compress: optimize,
      yuicompress: optimize,
      optimization: optimize ? 0 : 2
    }));

    http.use(express.static(tmpDir));
  });
Пример #5
0
    // We create another array based on listDropdownLang to use it in the i18n.middleware
    // supported_language which will be modified from the i18n mapping function
    supportedLanguages = listDropdownLang.slice(0);

app.locals({
  GA_ACCOUNT: env.get("GA_ACCOUNT"),
  GA_DOMAIN: env.get("GA_DOMAIN"),
  hostname: env.get("hostname"),
  supportedLanguages: supportedLanguages,
  listDropdownLang: listDropdownLang
});

// Setup locales with i18n
app.use( i18n.middleware({
  supported_languages: supportedLanguages,
  default_lang: "en-US",
  mappings: env.get("LANG_MAPPINGS"),
  translation_directory: path.resolve( __dirname, "locale" )
}));

app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.cookieSession({
  key: "goggles.sid",
  secret: env.get("SESSION_SECRET"),
  cookie: {
    maxAge: 2678400000, // 31 days. Persona saves session data for 1 month
    secure: !!env.get("FORCE_SSL")
  },
Пример #6
0
app.configure( function() {
  var tmpDir = path.normalize( require( "os" ).tmpDir() + "/mozilla.butter/" );

  if ( config.ENABLE_GELF_LOGS ) {
    messina = require( "messina" );
    logger = messina( "popcorn.webmaker.org-" + config.NODE_ENV || "development" );
    logger.init();
    app.use( logger.middleware() );
  } else {
    app.use( express.logger( config.logger ) );
  }

  app.use( function( req, res, next ) {
    var allowed = [ "/static/bower/font-awesome/font/" ];
    for ( var i = 0; i < allowed.length; i++ ) {
      if ( req.url.substring( 0, allowed[ i ].length ) === allowed[ i ] ) {
        res.header( "Access-Control-Allow-Origin", "*" );
      }
    }
    next();
  });
  app.use(helmet.iexss());
  app.use(helmet.contentTypeOptions());
  if ( !!config.FORCE_SSL ) {
    app.use( helmet.hsts() );
    app.enable( "trust proxy" );
  }
  app.use( express.compress() )
    .use( lessMiddleware(rtltrForLess({
      once: config.OPTIMIZE_CSS,
      dest: tmpDir,
      src: WWW_ROOT,
      compress: config.OPTIMIZE_CSS,
      yuicompress: config.OPTIMIZE_CSS,
      optimization: config.OPTIMIZE_CSS ? 0 : 2
    })))
    .use( requirejsMiddleware({
      src: WWW_ROOT,
      dest: tmpDir,
      debug: config.DEBUG,
      once: config.OPTIMIZE_JS,
      modules: {
        "/src/butter.js": {
          include: [ "butter" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js",
          paths: {
            "make-api": path.resolve( __dirname, "node_modules/makeapi-client/src/make-api" )
          }
        },
        "/src/embed.js": {
          include: [ "embed" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js"
        }
      },
      defaults: {
        name: "../external/require/require",
        baseUrl: WWW_ROOT + "/src/",
        findNestedDependencies: true,
        optimize: "none",
        preserveLicenseComments: false,
        wrap: {
          startFile: __dirname + "/tools/wrap.start",
          endFile: __dirname + "/tools/wrap.end"
        }
      }
    }))
    .use( function( req, res, next ) {
      if ( req.url === "/src/layouts/controls.html" ||
           req.url === "/src/layouts/attribution.html" ||
           req.url === "/src/layouts/warn.html") {
        res.set( "Access-Control-Allow-Origin", "*" );
      }

      process.nextTick( next );
    })
    .use( express.static( tmpDir, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) )
    .use( express.static( WWW_ROOT, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) );

    // Setup locales with i18n
    app.use( i18n.middleware({
      supported_languages: config.SUPPORTED_LANGS,
      default_lang: "en-US",
      mappings: require("webmaker-locale-mapping"),
      translation_directory: path.resolve( __dirname, "locale" )
    }));

    app.locals({
      config: {
        app_hostname: APP_HOSTNAME,
        audience: config.AUDIENCE,
        ga_account: config.GA_ACCOUNT,
        ga_domain: config.GA_DOMAIN,
        jwplayer_key: config.JWPLAYER_KEY,
        make_endpoint: config.MAKE_ENDPOINT,
        node_hubble_endpoint: config.NODE_HUBBLE_ENDPOINT,
        sync_limit: config.SYNC_LIMIT
      },
      languages: i18n.getSupportLanguages(),
      newrelic: newrelic,
      bower_path: "/static/bower"
    });
});
var AWS = require("aws-sdk"),
    nunjucks = require("nunjucks"),
    nunjucksEnv = new nunjucks.Environment(
      new nunjucks.FileSystemLoader(__dirname + "/templates/"),
      { autoescape: true }
    ),
    premailer = require('premailer-api'),
    i18n = require('webmaker-i18n'),
    path = require('path');

// Setup locales with i18n
i18n.middleware({
  supported_languages: ['*'],
  default_lang: "en-US",
  translation_directory: path.resolve(__dirname, "locale")
});

nunjucksEnv.addFilter("instantiate", function (input) {
  var tmpl = new nunjucks.Template(input);
  return tmpl.render(this.getVariables());
});

function isLanguageSupport(locale) {
  return i18n.getSupportLanguages().indexOf(locale) !== -1;
};

module.exports = function(options) {
  if (!options.key) {
    throw 'aws "key" required';
  }
  if (!options.secret) {
Пример #8
0
    ], {
      autoescape: true
    }),
    routes = require('./routes')( utils, env, nunjucksEnv, appName ),
    parameters = require('./lib/parameters'),
    messina,
    logger;

require("./lib/extendnunjucks").extend(nunjucksEnv, nunjucks);

nunjucksEnv.express(app);

// Setup locales with i18n
app.use( i18n.middleware({
  supported_languages: env.get( "SUPPORTED_LANGS" ),
  default_lang: "en-US",
  mappings: require("webmaker-locale-mapping"),
  translation_directory: path.resolve( __dirname, "locale" )
}));

app.locals({
  GA_ACCOUNT: env.get("GA_ACCOUNT"),
  GA_DOMAIN: env.get("GA_DOMAIN"),
  supportedLanguages: i18n.getLanguages(),
  listDropdownLang: i18n.getSupportLanguages()
});

// Express settings
app.disable('x-powered-by');
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));

if ( env.get( "ENABLE_GELF_LOGS" ) ) {
Пример #9
0
  http.configure(function () {
    nunjucksEnv.express(http);

    http.disable("x-powered-by");

    if (!!env.get("ENABLE_GELF_LOGS")) {
      messina = require("messina");
      logger = messina("login.webmaker.org-" + env.get("NODE_ENV") || "development");
      logger.init();
      http.use(logger.middleware());
    } else if (!env.get("DISABLE_HTTP_LOGGING")) {
      http.use(express.logger());
    }

    http.use(helmet.iexss());
    http.use(helmet.contentTypeOptions());
    http.use(helmet.xframe());

    if (!!env.get("FORCE_SSL")) {
      http.use(helmet.hsts());
      http.enable("trust proxy");
    }

    http.use(express.json());
    http.use(express.urlencoded());
    http.use(webmakerAuth.cookieParser());
    http.use(webmakerAuth.cookieSession());

    // Setup locales with i18n
    http.use(i18n.middleware({
      supported_languages: env.get("SUPPORTED_LANGS"),
      default_lang: "en-US",
      mappings: require("webmaker-locale-mapping"),
      translation_directory: path.resolve(__dirname, "../../locale")
    }));

    http.locals({
      // audience and webmakerorg are duplicated because of i18n
      AUDIENCE: env.get("WEBMAKERORG"),
      WEBMAKERORG: env.get("WEBMAKERORG"),
      newrelic: newrelic,
      profile: env.get("PROFILE"),
      bower_path: "bower_components",
      personaHostname: env.get("PERSONA_HOSTNAME", "https://login.persona.org"),
      languages: i18n.getSupportLanguages()
    });

    // need to make sure router is after i18n.middleware
    http.use(http.router);

    var optimize = env.get("NODE_ENV") !== "development",
      tmpDir = path.join(require("os").tmpDir(), "mozilla.login.webmaker.org.build");
    http.use(lessMiddleWare(rtltrForLess({
      once: optimize,
      debug: !optimize,
      dest: tmpDir,
      src: path.resolve(__dirname, "public"),
      compress: optimize,
      yuicompress: optimize,
      optimization: optimize ? 0 : 2
    })));
    http.use(express.static(tmpDir));
  });
Пример #10
0
nunjucksEnv.express(app);
app.disable('x-powered-by');

if (env.get('ENABLE_GELF_LOGS')) {
  messina = require('messina');
  logger = messina('webmaker.org-' + env.get('NODE_ENV') || 'development');
  logger.init();
  app.use(logger.middleware());
} else {
  app.use(express.logger('dev'));
}

// Setup locales with i18n
app.use(i18n.middleware({
  supported_languages: env.get('SUPPORTED_LANGS'),
  default_lang: 'en-US',
  mappings: require('webmaker-locale-mapping'),
  translation_directory: path.resolve(__dirname, 'locale')
}));

// Proxy to profile-2
if (env.get('PROFILE_URL')) {
  app.use('/user', proxy(url.parse(env.get('PROFILE_URL'))));
}

app.use(require('prerender-node'));

app.use(helmet.iexss());
app.use(helmet.contentTypeOptions());
app.use(helmet.xframe('allow-from', 'http://optimizely.com'));

if ( !! env.get('FORCE_SSL')) {
Пример #11
0
module.exports = function() {
  var express = require('express');
  var i18n = require('webmaker-i18n');
  var path = require('path');
  var defaultLang = 'en-US';
  var csp = require('./csp');
  var messina = require('messina')('gallery-maker-' + process.env.NODE_ENV);
  var wts = require('webmaker-translation-stats');
  var WebmakerAuth = require('webmaker-auth');
  var nunjucks = require('nunjucks');
  var helmet = require("helmet");
  var MakeapiClient = require('makeapi-client');
  var app = express();
  var csrf = express.csrf();

  var webmakerAuth = new WebmakerAuth({
    loginURL: process.env.LOGIN_URL,
    secretKey: process.env.SECRET_KEY,
    domain: process.env.DOMAIN,
    forceSSL: process.env.FORCE_SSL
  });

  app.use(require('prerender-node'));

  if (process.env.ENABLE_GELF_LOGS) {
    messina.init();
    app.use(messina.middleware());
  } else {
    app.use(express.logger('dev'));
  }

  var nunjucksEnv = new nunjucks.Environment(new nunjucks.FileSystemLoader(path.join(__dirname + '/views')), { autoescape: true });
  var makeClient = new MakeapiClient({
    apiURL: process.env.MAKEAPI_URL,
    hawk: {
      id: process.env.MAKEAPI_ID,
      key: process.env.MAKEAPI_KEY
    }
  });
  app.use(helmet.xssFilter());
  app.use(helmet.nosniff());
  app.use(helmet.xframe());
  app.use(express.compress());
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(webmakerAuth.cookieParser());
  app.use(webmakerAuth.cookieSession());
  app.use(csrf);
  app.disable('x-powered-by');

  // Setup locales with i18n
  app.use( i18n.middleware({
    supported_languages: JSON.parse(process.env.SUPPORTED_LANGS) || [defaultLang],
    default_lang: defaultLang,
    mappings: require('webmaker-locale-mapping'),
    translation_directory: path.resolve(__dirname, '../locale')
  }));

  nunjucksEnv.express( app );

  // CSP
  app.use(csp({
    reportToHost: process.env.CSP_LOGGER,
    eventsLocation: process.env.hostname
  }));

  if ( !!process.env.FORCE_SSL ) {
    app.use(helmet.hsts());
    app.enable("trust proxy");
  }

  app.use(express.static(path.join(__dirname, '../app')));

    // Health check
  var healthcheck = {
    version: require('../package').version,
    http: 'okay'
  };

  app.get('/healthcheck', function (req, res) {
    wts(i18n.getSupportLanguages(), path.join(__dirname, '../locale'), function(err, data) {
      if(err) {
        healthcheck.locales = err.toString();
      } else {
        healthcheck.locales = data;
      }
      res.json(healthcheck);
    });
  });

  // Localized Strings
  app.get('/strings/:lang?', i18n.stringsRoute('en-US'));

  // Serve up virtual configuration "file"
  var config = {
    version: require('../package').version,
    makeapiURL: process.env.MAKEAPI_URL,
    ga_account: process.env.GA_ACCOUNT || 'UA-XXXXX-X',
    ga_domain: process.env.GA_DOMAIN || 'example.com'
  };

  app.get('/config.js', function (req, res) {
    config.lang = req.localeInfo.lang;
    config.direction = req.localeInfo.direction;
    config.csrfToken = req.csrfToken();
    config.defaultLang = defaultLang;
    config.langmap = i18n.getAllLocaleCodes();
    config.supported_languages = i18n.getSupportLanguages();
    res.setHeader('Content-type', 'text/javascript');
    res.send('window.galleryConfig = ' + JSON.stringify(config));
  });

  app.get('/view/:id', function(req, res) {
    makeClient.getList(req.params.id, function(err, data) {
      if ( err ) {
        return res.json(500, err);
      }
      res.render('view.html', {
        list: data
      });
    }, true );
  });

  function auth( req, res, next ) {
    if ( req.session && req.session.user ) {
      return next();
    }
    res.json(403, 'unauthorised');
  }

  app.post('/list', csrf, auth, function(req, res, next) {
   makeClient.createList(req.body, function(err, data) {
      if ( err ) {
        return res.json(500, err);
      }
      res.json(data);
   });
  });

  app.put('/list/:id', csrf, auth, function(req, res, next) {
    makeClient.updateList(req.params.id, {
      userId: req.session.user.id,
      makes: req.body.makes,
      title: req.body.title
    }, function(err, data) {
      if ( err ) {
        return res.json(500, err);
      }
      res.json(data);
    });
  });

  app.delete('/list/:id', csrf, auth, function(req, res, next) {
    makeClient.removeList(req.params.id, req.session.user.id, function(err, data) {
      if ( err ) {
        return res.json(500, err);
      }
      res.json(data);
    });
  });

  app.get('/list/:id', function(req, res, next) {
    makeClient.getList(req.params.id, function(err, data) {
      if ( err ) {
        return res.json(500, err);
      }
      res.json(data);
    }, true );
  });

  app.get('/lists/:user', function(req, res, next) {
    makeClient.getListsByUser(req.params.user, function(err, data) {
      if ( err ) {
        return res.json(500, err);
      }
      res.json(data);
    });
  });

  app.post('/verify', webmakerAuth.handlers.verify);
  app.post('/authenticate', webmakerAuth.handlers.authenticate);
  app.post('/logout', webmakerAuth.handlers.logout);

  return app;
};
Пример #12
0
app.configure(function(){
  app.set('port', process.env.PORT || 3000);

  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');

  app.use(express.logger(function(tokens, req, res) {
    if (res.statusCode >= 400) // or whatever you want logged
      return express.logger.dev(tokens, req, res);
    return null;
  }));

  app.use(express.bodyParser());
  app.use(express.cookieParser());

  app.use(express.cookieSession({
    key: "appmaker.sid",
    secret: process.env.COOKIE_SECRET,
    cookie: {
      maxAge: 60 * 60 * 24 * 31, // 31 days. Persona saves session data for 1 month
      secure: !!process.env.FORCE_SSL
    },
    proxy: true
  }));

  bundles.configure(app);

  // Setup locales with i18n
  app.use(i18n.middleware({
    supported_languages: ["*"],
    default_lang: "en-US",
    mappings: require("webmaker-locale-mapping"),
    translation_directory: path.resolve( __dirname, "locale" )
  }));

  app.use(express.favicon());

  app.use(function(req, res, next) {
    res.removeHeader("x-powered-by");
    next();
  });

  app.use(express.methodOverride());

  app.use(app.router);

  app.use(connectFonts.setup({
    fonts: [require('connect-fonts-sourcesanspro')],
    allow_origin: process.env.ASSET_HOST,
    ua: 'all',
    maxage: MAX_FONT_AGE_MS
  }));

  // enable cors for test relevant assets
  app.use("/test_assets/ceci/", cors());
  app.use("/test_assets/ceci/", express.static(path.join(__dirname, 'public', 'ceci')));
  app.use("/test_assets/vendor/", cors());
  app.use("/test_assets/vendor/", express.static(path.join(__dirname, 'public', 'vendor')));

  app.use(lessMiddleware({
    src: __dirname + '/public',
    compress: true
  }));

  app.use('/', cors());
  app.use('/', express.static(path.join(__dirname, 'public')));

  enableRedirects(app);
});
Пример #13
0
  guard.run( next );
});


app.use( express.compress() );
app.use( express.static( WWW_ROOT ));
app.use( "/bower", express.static( path.join(__dirname, "bower_components" )));

// List of supported languages - Please add them here in an alphabetical order
var supportedLanguages = [ "en-US" ];

// Setup locales with i18n
app.use( i18n.middleware({
  supportedLanguages: supportedLanguages,
  default_lang: "en-US",
  translation_directory: path.resolve( __dirname, "locale" )
}));

app.use( express.json() );
app.use( express.urlencoded() );
app.use( express.cookieParser() );
app.use( express.cookieSession({
  key: "webmaker.sid",
  secret: env.get( "SESSION_SECRET" ),
  cookie: {
    maxAge: 2678400000, // 31 days. Persona saves session data for 1 month
    secure: !!env.get( "FORCE_SSL" )
  },
  proxy: true
}));
Пример #14
0
app.configure( function() {
  var tmpDir = path.normalize( require( "os" ).tmpDir() + "/mozilla.butter/" );

  if ( config.ENABLE_GELF_LOGS ) {
    messina = require( "messina" );
    logger = messina( "popcorn.webmaker.org-" + config.NODE_ENV || "development" );
    logger.init();
    app.use( logger.middleware() );
  } else {
    app.use( express.logger( config.logger ) );
  }

  app.use( "/static/bower", express.static( path.join( __dirname, "/bower_components" ), {
    maxAge: "31556952000" // one year
  }));
  app.use(helmet.iexss());
  app.use(helmet.contentTypeOptions());
  if ( !!config.FORCE_SSL ) {
    app.use( helmet.hsts() );
    app.enable( "trust proxy" );
  }
  app.use( express.compress() )
    .use( lessMiddleware({
      once: config.OPTIMIZE_CSS,
      dest: tmpDir,
      src: WWW_ROOT,
      compress: config.OPTIMIZE_CSS,
      yuicompress: config.OPTIMIZE_CSS,
      optimization: config.OPTIMIZE_CSS ? 0 : 2
    }))
    .use( requirejsMiddleware({
      src: WWW_ROOT,
      dest: tmpDir,
      debug: config.DEBUG,
      once: config.OPTIMIZE_JS,
      modules: {
        "/src/butter.js": {
          include: [ "butter" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js",
          paths: {
            "make-api": path.resolve( __dirname, "node_modules/makeapi-client/src/make-api" ),
            "sso-include": path.resolve( __dirname, "node_modules/webmaker-sso/include" )
          }
        },
        "/src/embed.js": {
          include: [ "embed" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js"
        }
      },
      defaults: {
        name: "../external/require/require",
        baseUrl: WWW_ROOT + "/src/",
        findNestedDependencies: true,
        optimize: "none",
        preserveLicenseComments: false,
        paths: {
          "localized": path.resolve( __dirname, "bower_components/webmaker-i18n/localized" ),
          "jquery": path.resolve( __dirname, "bower_components/jquery/jquery.min" ),
          "jquery-ui": path.resolve( __dirname, "bower_components/jquery-ui/ui/jquery-ui" ),
          "farbtastic": path.resolve( __dirname, "bower_components/farbtastic/farbtastic" ),
          "WebmakerUI": path.resolve( __dirname, "bower_components/webmaker-ui/ui" ),
          "webmaker-ui-fragments": path.resolve( __dirname, "bower_components/webmaker-ui/webmaker-ui-fragments" )
        },
        wrap: {
          startFile: __dirname + "/tools/wrap.start",
          endFile: __dirname + "/tools/wrap.end"
        }
      }
    }))
    .use( express.static( tmpDir, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) )
    .use( express.static( WWW_ROOT, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) );

  // Setup locales with i18n
  app.use( i18n.middleware({
    supported_languages: config.SUPPORTED_LANGS,
    default_lang: "en-US",
    mappings: require("webmaker-locale-mapping"),
    translation_directory: path.resolve( __dirname, "locale" )
  }));

  app.locals({
    config: {
      app_hostname: APP_HOSTNAME,
      audience: config.AUDIENCE,
      ga_account: config.GA_ACCOUNT,
      ga_domain: config.GA_DOMAIN,
      jwplayer_key: config.JWPLAYER_KEY,
      make_endpoint: config.MAKE_ENDPOINT,
      node_hubble_endpoint: config.NODE_HUBBLE_ENDPOINT,
      user_bar: config.USER_BAR,
      sync_limit: config.SYNC_LIMIT
    },
    supportedLanguages: i18n.getLanguages(),
    listDropdownLang: i18n.getSupportLanguages()
  });

  app.use( express.json() )
    .use( express.urlencoded() )
    .use( express.cookieParser() )
    .use( express.cookieSession( config.session ) )
    .use( express.csrf() )
    .use( helmet.xframe() )
    /* Show Zeus who's boss
     * This only affects requests under /api and /persona, not static files
     * because the static file writes the response header before we hit this middleware
     */
    .use( function( req, res, next ) {
      res.header( "Cache-Control", "no-store" );
      return next();
    })
    .use( app.router )
    /*jslint unused: false */
    .use( function( err, req, res, next ) {
      middleware.errorHandler( err, req, res );
    })
    /*jslint unused: false */
    .use( function( req, res, next ) {
      var err = {
        message: req.gettext( "This page doesn't exist" ),
        status: 404
      };

      middleware.errorHandler( err, req, res );
    });

  Project = require( "./lib/project" )( config.database );
  filter = require( "./lib/filter" )( Project.isDBOnline );
});
Пример #15
0
module.exports = function (options) {
  options = options || {};

  const DEFAULT_LANG = 'en-US';

  var path = require('path');
  var nunjucks = require('nunjucks');
  var i18n = require('webmaker-i18n');

  // Is language supported?
  function isLanguageSupported(locale) {
    return i18n.getSupportLanguages().indexOf(locale) !== -1;
  };

  function gettext(locale) {
    var strings = i18n.getStrings(locale);
    return function (string) {
      return strings[string] || string;
    }
  };

  // Configure nunjucks
  var env = nunjucks.configure(__dirname, { autoescape: true });
  env.addFilter('instantiate', function (input) {
    return nunjucks.renderString(input, this.getVariables());
  });
  env.addFilter('gettext', function (input) {
    return this.lookup('gettext')(input);
  });

  // Setup locales with i18n
  i18n.middleware({
    supported_languages: ['*'],
    default_lang: DEFAULT_LANG,
    translation_directory: path.resolve(__dirname, 'locale'),
    mappings: {'id-ID': 'id'}
  });

  var baseHtml = {
    header: nunjucks.render('base/header.html'),
    footer: nunjucks.render('base/footer.html')
  };

  return {
    render: function (template, data, options) {
      options = options || {};
      var locals = data || {};
      var header = '';
      var footer = '';
      var html;
      var subject;
      var locale = options.locale;
      var partial = options.partial;
      // This option is really only used for tests
      var dir = options.dir || 'templates';
      var metaData = require(__dirname + '/' + dir +'/' + template);

      locale = isLanguageSupported(locale) ? locale : DEFAULT_LANG;
      locals.gettext = gettext(locale);
      locals.locale = locale;
      try {
        html = nunjucks.render(dir + '/' + template + '/index.html', data);
        subject = nunjucks.renderString(locals.gettext(metaData.subject), data);
        if (!partial) {
          header = baseHtml.header;
          footer = baseHtml.footer;
        } else {
          // displaying html inline, so replace body tags
          html = html.replace(/<body( .*?)?>/gi, '<div$1>');
          html = html.replace(/<\/(body)>/gi, '</div>');
        }
        return {
          html: header + html  + footer,
          subject: subject
        };
      } catch (err) {
        console.log(err);
      }
    }
  };
};
Пример #16
0
app.configure( function() {
  var tmpDir = path.normalize( require( "os" ).tmpDir() + "/mozilla.butter/" ),
      authLocaleJSON;

  if ( config.ENABLE_GELF_LOGS ) {
    messina = require( "messina" );
    logger = messina( "popcorn.webmaker.org-" + config.NODE_ENV || "development" );
    logger.init();
    app.use( logger.middleware() );
  } else {
    app.use( express.logger( config.logger ) );
  }

  app.use( function( req, res, next ) {
    var allowed = [ "/static/bower/font-awesome/font/" ];
    for ( var i = 0; i < allowed.length; i++ ) {
      if ( req.url.substring( 0, allowed[ i ].length ) === allowed[ i ] ) {
        res.header( "Access-Control-Allow-Origin", "*" );
      }
    }
    next();
  });
  app.use(helmet.iexss());
  app.use(helmet.contentTypeOptions());
  if ( !!config.FORCE_SSL ) {
    app.use( helmet.hsts() );
    app.enable( "trust proxy" );
  }
  app.use( express.compress() )
    .use( lessMiddleware({
      once: config.OPTIMIZE_CSS,
      dest: tmpDir,
      src: WWW_ROOT,
      compress: config.OPTIMIZE_CSS,
      yuicompress: config.OPTIMIZE_CSS,
      optimization: config.OPTIMIZE_CSS ? 0 : 2
    }))
    .use( requirejsMiddleware({
      src: WWW_ROOT,
      dest: tmpDir,
      debug: config.DEBUG,
      once: config.OPTIMIZE_JS,
      modules: {
        "/src/butter.js": {
          include: [ "butter" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js",
          paths: {
            "make-api": path.resolve( __dirname, "node_modules/makeapi-client/src/make-api" )
          }
        },
        "/src/embed.js": {
          include: [ "embed" ],
          mainConfigFile: WWW_ROOT + "/src/popcorn.js"
        }
      },
      defaults: {
        name: "../external/require/require",
        baseUrl: WWW_ROOT + "/src/",
        findNestedDependencies: true,
        optimize: "none",
        preserveLicenseComments: false,
        wrap: {
          startFile: __dirname + "/tools/wrap.start",
          endFile: __dirname + "/tools/wrap.end"
        }
      }
    }))
    .use( function( req, res, next ) {
      if ( req.url === "/src/layouts/controls.html" ||
           req.url === "/src/layouts/attribution.html" ||
           req.url === "/src/layouts/warn.html") {
        res.set( "Access-Control-Allow-Origin", "*" );
      }

      process.nextTick( next );
    })
    .use( express.static( tmpDir, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) )
    .use( express.static( WWW_ROOT, JSON.parse( JSON.stringify( config.staticMiddleware ) ) ) );

  // Setup locales with i18n
  app.use( i18n.middleware({
    supported_languages: config.SUPPORTED_LANGS,
    default_lang: "en-US",
    mappings: require("webmaker-locale-mapping"),
    translation_directory: path.resolve( __dirname, "locale" )
  }));

  // Adding an external JSON file to our existing one for the specified locale
  authLocaleJSON = require( "./public/static/bower/webmaker-auth-client/locale/en_US/create-user-form.json" );
  i18n.addLocaleObject({
    "en-US": authLocaleJSON
  }, function () {});

  app.locals({
    config: {
      app_hostname: APP_HOSTNAME,
      audience: config.AUDIENCE,
      ga_account: config.GA_ACCOUNT,
      ga_domain: config.GA_DOMAIN,
      jwplayer_key: config.JWPLAYER_KEY,
      make_endpoint: config.MAKE_ENDPOINT,
      node_hubble_endpoint: config.NODE_HUBBLE_ENDPOINT,
      sync_limit: config.SYNC_LIMIT
    },
    languages: i18n.getSupportLanguages()
  });

  app.use(function (req, res, next) {
    res.locals({
      currentPath: req.path,
      returnPath: req.param( "page" )
    });
    next();
  });

  app.use( express.json() )
    .use( express.urlencoded() )
    .use( webmakerAuth.cookieParser() )
    .use( webmakerAuth.cookieSession() )
    .use( express.csrf() )
    .use( helmet.xframe() )
    /* Show Zeus who's boss
     * This only affects requests under /api and /persona, not static files
     * because the static file writes the response header before we hit this middleware
     */
    .use( function( req, res, next ) {
      res.header( "Cache-Control", "no-store" );
      return next();
    })
    .use( app.router )
    /*jslint unused: false */
    .use( function( err, req, res, next ) {
      middleware.errorHandler( err, req, res );
    })
    /*jslint unused: false */
    .use( function( req, res, next ) {
      var err = {
        message: req.gettext( "This page doesn't exist" ),
        status: 404
      };

      middleware.errorHandler( err, req, res );
    });

  Project = require( "./lib/project" )( config.database );
  filter = require( "./lib/filter" )( Project.isDBOnline );
});
Пример #17
0
    supportedLanguages = listDropdownLang.slice(0);

app.locals({
  GA_ACCOUNT: env.get("GA_ACCOUNT"),
  GA_DOMAIN: env.get("GA_DOMAIN"),
  hostname: env.get("hostname"),
  supportedLanguages: supportedLanguages,
  listDropdownLang: listDropdownLang
});

// Setup locales with i18n
app.use( i18n.middleware({
  supported_languages: supportedLanguages,
  default_lang: "en-US",
  mappings: {
    'en': 'en-US',
    'ru': 'ru-RU',
    'th': 'th-TH'
  },
  translation_directory: path.resolve( __dirname, "locale" )
}));

app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.cookieSession({
  key: "goggles.sid",
  secret: env.get("SESSION_SECRET"),
  cookie: {
    maxAge: 2678400000, // 31 days. Persona saves session data for 1 month
Пример #18
0
});

nunjucksEnv.express(app);

app.disable('x-powered-by');

app.use(express.logger('dev'));

app.use(express.compress());

app.use(express.json());
app.use(express.urlencoded());

app.use(i18n.middleware({
  supported_languages: ['en-US'],
  default_lang: 'en-US',
  mappings: require('webmaker-locale-mapping'),
  translation_directory: path.resolve(__dirname, '../locale')
}));

app.use(express.static(path.join(__dirname, '../dist')));
app.use(express.static(path.join(__dirname, '../node_modules')));

app.get('/angular-config.js', function(req, res) {
  res.setHeader('Content-type', 'text/javascript');
  res.send('window.angularConfig = ' + JSON.stringify({
    csrf: 'thisisnotacsrftoken',
    lang: 'en-CA'
  }));
});

app.get('/', function(req, res) {
Пример #19
0
module.exports = function (env) {
  var express = require('express');
  var i18n = require('webmaker-i18n');
  var path = require('path');
  var app = express();
  var defaultLang = 'en-US';
  var csp = require('./csp');
  var messina = require('messina')('webmaker-events-2-' + env.get('NODE_ENV'));
  var wts = require('webmaker-translation-stats');
  var WebmakerAuth = require('webmaker-auth');

  var auth = new WebmakerAuth({
    loginURL: env.get('LOGIN_URL'),
    secretKey: env.get('SESSION_SECRET'),
    forceSSL: env.get('FORCE_SSL'),
    domain: env.get('COOKIE_DOMAIN')
  });

  app.use(require('prerender-node'));
  if (env.get('ENABLE_GELF_LOGS')) {
    messina.init();
    app.use(messina.middleware());
  } else {
    app.use(express.logger('dev'));
  }
  app.use(express.compress());
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(auth.cookieParser());
  app.use(auth.cookieSession());

  // Setup locales with i18n
  app.use( i18n.middleware({
    supported_languages: env.get('SUPPORTED_LANGS') || [defaultLang],
    default_lang: defaultLang,
    mappings: require('webmaker-locale-mapping'),
    translation_directory: path.resolve(__dirname, '../locale')
  }));

  // CSP
  app.use(csp({
    reportToHost: env.get('CSP_LOGGER'),
    eventsLocation: env.get('eventsLocation') || 'http://localhost:1989'
  }));

  // Static files
  app.use(express.static(path.join(__dirname, '../app')));

  // Health check
  var healthcheck = {
    version: require('../package').version,
    http: 'okay'
  };

  app.get('/healthcheck', function (req, res) {
    wts(i18n.getSupportLanguages(), path.join(__dirname, '../locale'), function(err, data) {
      if(err) {
        healthcheck.locales = err.toString();
      } else {
        healthcheck.locales = data;
      }
      res.json(healthcheck);
    });
  });

  // Login
  app.post('/verify', auth.handlers.verify);
  app.post('/authenticate', auth.handlers.authenticate);
  app.post('/create', auth.handlers.create);
  app.post('/logout', auth.handlers.logout);
  app.post('/check-username', auth.handlers.exists);

  // Serve up virtual configuration "file"
  var config = {
    version: require('../package').version,
    eventsLocation: env.get('eventsLocation') || 'http://localhost:1989',
    accountSettingsUrl: env.get('accountSettingsUrl') || 'https://login.webmaker.org/account',
    myMakesUrl: env.get('myMakesUrl') || 'https://webmaker.org/me',
    webmakerUrl: env.get('WEBMAKER_URL') || 'https://webmaker.org',
    ga_account: env.get('GA_ACCOUNT') || 'UA-XXXXX-X',
    ga_domain: env.get('GA_DOMAIN') || 'example.com'
  };

  app.get('/config.js', function (req, res) {
    config.lang = req.localeInfo.lang;
    config.direction = req.localeInfo.direction;
    config.defaultLang = defaultLang;
    config.langmap = i18n.getAllLocaleCodes();
    config.supported_languages = i18n.getSupportLanguages();
    res.setHeader('Content-type', 'text/javascript');
    res.send('window.eventsConfig = ' + JSON.stringify(config));
  });

 // Localized Strings
 app.get('/strings/:lang?', i18n.stringsRoute('en-US'));

  return app;
};