Coder Social home page Coder Social logo

kraken-js's Introduction

kraken-js

kraken.js

Build Status Greenkeeper badge

Kraken builds upon express and enables environment-aware, dynamic configuration, advanced middleware capabilities, security, and app lifecycle events. For more information and examples check out krakenjs.com

Table of Contents

Basic Usage

'use strict';

var express = require('express'),
    kraken = require('kraken-js');

var app = express();
app.use(kraken());
app.listen(8000);

API

kraken([options])

kraken-js is used just like any normal middleware, however it does more than just return a function; it configures a complete express 4 application. See below for a list of features, but to get started just use it like middleware.

app.use(kraken());
// or to specify a mountpath for your application:
// app.use('/mypath', kraken());

// Note: mountpaths can also be configured using the
// `express:mountpath` config setting, but that setting
// will be overridden if specified in code.

Options

Pass the following options to kraken via a config object such as this:

var options = {
    onconfig: function (config, callback) {
        // do stuff
        callback(null, config);
    }
};

// ...

app.use(kraken(options));

Note: All kraken-js configuration settings are optional.

basedir (String, optional)

The working directory for kraken to use. kraken loads configuration files, routes, and registers middleware so this directory is the path against all relative paths are resolved. The default value is the directory of the file that uses kraken, which is generally index.js (or server.js).

onconfig (Function, optional)

Provides an asynchronous hook for loading additional configuration. When invoked, a confit configuration object containing all loaded configuration value passed as the first argument, and a callback as the second. The signature of this handler is function (config, callback) and the callback is a standard error-back which accepts an error as the first argument and the config object as the second, e.g. callback(null, config).

protocols (Object, optional)

Protocol handler implementations for use when processing configuration. For more information on protocols see shortstop and shortstop-handlers. By default, kraken comes with a set of shortstop protocols which are described in the "Config Protocols" section below, but you can add your own by providing an object with the protocol names as the keys and their implementations as properties, for example:

var options = {
    protocols: {
        file: function file(value, callback) {
            fs.readFile(value, 'utf8', callback);
        }
    }
};

onKrakenMount (Function, optional)

Provides a synchronous hook which executes once kraken mounts. It takes an express app instance as the first argument, and options as the second. The signature of this handler is function (app, options).

uncaughtException (Function, optional)

Handler for uncaughtException errors outside of the middleware chain. See the endgame module for defaults.

For uncaught errors in the middleware chain, see shutdown middleware instead.

confit (Object, optional)

In rare cases, it may be useful to pass options directly to the confit module used within lib/config.js. For example, if confit/shortstop is conflicting with environment variables, you can explicitly ignore those environment variables:

var options = {
    confit: {
        envignore: ['troublesome_environment_variable']
    }
};

Config Protocols

kraken comes with the following shortstop protocol handlers by default:

import:

Merge the contents of the specified file into configuration under a given key.

{
    "foo": "import:./myjsonfile"
}

config:

Replace with the value at a given key. Note that the keys in this case are dot (.) delimited.

{
    "foo": {
        "bar": true
    },
    "foobar": "config:foo.bar"
}

path:

The path handler is documented in the shortstop-handlers repo.

file:

The file handler is documented in the shortstop-handlers repo.

base64:

The base64 handler is documented in the shortstop-handlers repo.

env:

The env handler is documented in the shortstop-handlers repo.

require:

The require handler is documented in the shortstop-handlers repo.

exec:

The exec handler is documented in the shortstop-handlers repo.

glob:

The glob handler is documented in the shortstop-handlers repo.

resolve:

The resolve handler is documented in the shortstop-resolve repo.

Features

Configuration

Environment-aware

Using environment suffixes, configuration files are applied and overridden according to the current environment as set by NODE_ENV. The application looks for a ./config directory relative to the basedir and looks for config.json as the baseline config specification. JSON files matching the current env are processed and loaded. Additionally, JSON configuration files may contain comments.

Valid NODE_ENV values are undefined or dev[elopment] (uses development.json), test[ing] (uses test.json), stag[e|ing] (uses staging.json), prod[uction] (uses config.json). Simply add a config file with the name, to have it read only in that environment, e.g. config/development.json.

Middleware

Much like configuration, you shouldn't need to write a lot of code to determine what's in your middleware chain. meddleware is used internally to read, resolve, and register middleware with your express application. You can either specify the middleware in your config.json or {environment}.json, (or) import it from a separate json file using the import protocol mentioned above.

Included Middleware

Kraken comes with common middleware already included in its config.json file. The following is a list of the included middleware and their default configurations which can be overridden in your app's configuration:

  • "shutdown" - internal middleware which handles graceful shutdowns in production environments
    • Priority - 0
    • Enabled - true if not in a development environment
    • Module - "kraken-js/middleware/shutdown"
      • Arguments (Array)
        • Object
          • "timeout" - milliseconds (default: 30000)
          • "template" - template to render (default: null)
          • "shutdownHeaders" - custom headers to write while still disconnecting.
          • "uncaughtException" - custom handler - function (error, req, res, next) - for uncaught errors. Default behavior is to log the error and then trigger shutdown.
  • "compress" - adds compression to server responses
    • Priority - 10
    • Enabled - false (disabled in all environments by default)
    • Module - "compression" (npm)
  • "favicon" - serves the site's favicon
    • Priority - 30
    • Module - "serve-favicon" (npm)
      • Arguments (Array)
        • String - local path to the favicon file (default: "path:./public/favicon.ico")
  • "static" - serves static files from a specific folder
    • Priority - 40
    • Module - "serve-static" (npm)
      • Arguments (Array)
        • String - local path to serve static files from (default: "path:./public")
  • "logger" - logs requests and responses
    • Priority - 50
    • Module - "morgan" (npm)
      • Arguments (Array)
        • String - log format type (default: "combined")
  • "json" - parses JSON request bodies
    • Priority - 60
    • Module - "body-parser" (npm)
      • Method - "json"
  • "urlencoded" - parses URL Encoded request bodies
    • Priority - 70
    • Module - "body-parser" (npm)
      • Method - "urlencoded"
      • Arguments (Array)
        • Object
          • "extended" (Boolean) - parse extended syntax with the qs module (default: true)
  • "multipart" - parses multipart FORM bodies
    • Priority - 80
    • Module - "kraken-js/middleware/multipart" (delegates to formidable)
  • "cookieParser" - parses cookies in request headers
    • Priority - 90
    • Module - "cookie-parser" (npm)
      • Arguments (Array)
        • String - secret used to sign cookies (default: "keyboard cat")
  • "session" - maintains session state
    • Priority - 100
    • Module - "express-session" (npm)
      • Arguments (Array)
        • Object
          • "key" (String) - cookie name (default: "connect.sid")
          • "secret" (String) - secret used to sign session cookie (default: "keyboard cat")
          • "cookie" (Object) - describing options for the session cookie
            • "path" (String) - base path to verify cookie (default: "/")
            • "httpOnly" (Boolean) - value indicating inaccessibility of cookie in the browser (default: true)
            • "maxAge" (Number) - expiration of the session cookie (default: null)
          • "resave" (Boolean) - value indicating whether sessions should be saved even if unmodified (default: true)
          • "saveUninitialized" (Boolean) - value indicating whether to save uninitialized sessions (default: true)
          • "proxy" (Boolean) - value indicating whether to trust the reverse proxy (default: null, inherit from express)
  • "appsec" - secures the application against common vulnerabilities (see Application Security below)
    • Priority - 110
    • Module - "lusca" (github)
      • Arguments (Array)
        • Object
          • "csrf" (Boolean|Object) - value indicating whether to require CSRF tokens for non GET, HEAD, or OPTIONS requests, or an options object to configure CSRF protection (default: true)
          • "xframe" (String) - value for the X-Frame-Options header (default: "SAMEORIGIN")
          • "p3p" (String|Boolean) - the Compact Privacy Policy value or false if not used (default: false)
          • "csp" (Object|Boolean) - options configuring Content Security Policy headers or false if not used (default: false)
  • "router" - routes traffic to the applicable controller
    • Priority - 120
    • Module - "express-enrouten" (npm)
      • Arguments (Array)
        • Object
          • "index" (String) - path to the single file to load (default: "path:./routes")

Additional notes:

  • The session middleware defaults to using the in-memory store. This is not recommended for production applications and the configuration should be updated to use a shared resource (such as Redis or Memcached) for session storage.
  • You can change the routes which are affected by the middleware by providing a top-level option of route. In express deployments, it is common to re-route where static files are served which can be accomplished like so:
// include this in your own config.json and this will merge with the Kraken defaults
// NB: if you use kraken-devtools you must re-route that as well in development.json!
{
    "static": {
        "route": "/static"
    }
}

Extending Default Middleware

In any non-trivial Kraken deployment you will likely need to extend the included middleware. Common middleware which need extension include cookie parsing and session handling. In those particular cases, the secrets used should be updated:

{
    // include this in your own config.json and this will merge with the Kraken defaults
    "middleware": {

        "cookieParser": {
            "module": {
                "arguments": [ "your better secret value" ]
            }
        },

        "session": {
            "module": {
                // NB: arrays like 'arguments' are not merged but rather replaced, so you must
                //     include all required configuration options here.
                "arguments": [
                    {
                        "secret": "a much better secret",
                        "cookie": {
                            "path": "/",
                            "httpOnly": true,
                            "maxAge": null
                        },
                        "resave": true,
                        "saveUninitialized": true,
                        "proxy": null
                    }
                ]
            }
        }

    }
}

Another common update is to pass options to middleware which is configured only with the defaults, such as the compression middleware:

{
    "middleware": {
        "compress": {
            "enabled": true,    // response compression is disabled by default
            "module": {
                "arguments": [
                    {
                        // 512 byte minimum before compressing output
                        "threshold": 512
                    }
                ]
            }
        }
    }
}

More complicated examples include configuring the session middleware to use a shared resource, such as connect-redis. This requires a few extra steps, most notably creating your own middleware to handle the registration (see totherik/redis-example for a complete example):

  1. Overlay the existing session middleware in your configuration:
{
    // in your config.json
    "middleware": {
        "session": {
            "module": {
                // use your own module instead
                "name": "path:./lib/middleware/redis-session",
                "arguments": [
                    // express-session configuration
                    {
                        "secret": "a much better secret",
                        "cookie": {
                            "path": "/",
                            "httpOnly": true,
                            "maxAge": null
                        },
                        "resave": true,
                        "saveUninitialized": true,
                        "store": null    // NB: this will be overlaid in our module
                    },
                    // connect-redis configuration
                    {
                        "host": "localhost",
                        "port": 6379,
                        "prefix": "session:"
                    }
                ]
            }
        }
    }
}
  1. Add your custom middleware for Kraken to configure:
// ./lib/middleware/redis-session.js
'use strict';

var session = require('express-session'),
    RedisStore = require('connect-redis')(session);

/** Creates a REDIS-backed session store.
 *
 * @param {Object} [sessionConfig] Configuration options for express-session
 * @param {Object} [redisConfig] Configuration options for connect-redis
 * @returns {Object} Returns a session middleware which is backed by REDIS
 */
module.exports = function (sessionConfig, redisConfig) {

    // add the 'store' property to our session configuration
    sessionConfig.store = new RedisStore(redisConfig);

    // create the actual middleware
    return session(sessionConfig);
};

Application Security

Kraken uses lusca to secure your applications, so that you don't need to think about it. Techniques like CSRF, XFRAMES, and CSP are enabled automatically while others can be opted into. All are customizable through configuration.

Lifecycle Events

Kraken adds support for additional events to your express app instance:

  • start - the application has safely started and is ready to accept requests
  • shutdown - the application is shutting down, no longer accepting requests
  • stop - the http server is no longer connected or the shutdown timeout has expired

Configuration-based express Settings

Since express instances are themselves config objects, the convention is to set values on the app instance for use by express internally as well as other code across the application. kraken-js allows you to configure express via JSON. Any properties are supported, but kraken-js defaults include:

{
    "express": {
        "env": "", // NOTE: `env` is managed by the framework. This value will be overwritten.
        "x-powered-by": false,
        "trust proxy": false,
        "jsonp callback name": null,
        "json replacer": null,
        "json spaces": 0,
        "case sensitive routing": false,
        "strict routing": false,
        "view cache": true,
        "view engine": null,
        "views": "path:./views",
        "route": "/"
    }
}

Additional notes:

  • The env setting will be set to the environment value as derived by kraken-js, so what is put here will be overwritten at runtime.
  • Set the view engine property to the one of the view engines property names (see the section View Engine Configuration) to enable it for template rendering.
  • The optional view property is a special case in which you can set a path to a module which exports a constructor implementing the view API as defined by the module express/lib/view. If set, kraken-js will attempt to load the specified module and configure express to use it for resolving views.

For example:

{
    "express": {
        "view": "path:./lib/MyCustomViewResolver"
    }
}

View Engine Configuration

kraken-js looks to the view engines config property to understand how to load and initialize renderers. The value of the view engines property is an object mapping the desired file extension to engine config settings. For example:

{
    "view engines": {
        "jade": {
            "module": "consolidate"
        },
        "html": {
            "name": "ejs",
            "module": "ejs",
            "renderer": "renderFile"
        },
        "dust": {
            "module": "adaro",
            "renderer": {
                "method": "dust",
                "arguments": [{
                    "cache": false,
                    "helpers": ["dust-helpers-whatevermodule"]
                }]
            }
        },
        "js": {
            "module": "adaro",
            "renderer": {
                "method": "js",
                "arguments": [{ "cache": false }]
            }
        }
    }
}

The available engine configuration options are:

  • module (String) - This is the node module that provides the renderer implementation. The value can be the name of a module installed via npm, or it can be a module in your project referred to via file path, for example "module": "path:./lib/renderer".
  • name (String, optional) - Set this if the name of the rendering engine is different from the desired file extension. For example, you chose to use ejs, but want to use the "html" file extension for your templates. Additionally, if the renderer function exported by the module is not the file extension and a "renderer" property is not defined, this value will be used.
  • renderer (String|Object, optional) - The renderer property allows you to explicitly identify the property or the factory method exported by the module that should be used when settings the renderer. Set the value to a String to identify that the renderer is exported by that name, or an object with the properties "method" and "arguments" to identify a factory method. For example, using ejs you could set this property to "renderFile" or "__express" as the ejs module exports a renderer directly.

Tests

$ npm test

Coverage

$ npm run-script cover && open coverage/lcov-report/index.html

Reading app configs from within the kraken app

There are two different ways. You can

  • Read it in your onconfig handler as mentioned above.
function (config, callback) {
    var value = config.get('<key>');
    ...
    ...
    callback(null, config);
}
  • Read it off the req object by doing req.app.kraken.get('<config-key>'). So it would look like:
router.get('/', function (req, res) {
    var value = req.app.kraken.get('<key>');
    ...
    ...
});

kraken-js's People

Contributors

airtonix avatar aredridel avatar brunops avatar gabrielcsapo avatar grawk avatar greenkeeper[bot] avatar gvspraveen avatar jasisk avatar jeffharrell avatar kethinov avatar knighton910 avatar kode4food avatar kumarrishav avatar lensam69 avatar patrickjs avatar pvenkatakrishnan avatar sean avatar shaunwarman avatar sixlettervariables avatar snaheth avatar snowinferno avatar subeeshcbabu avatar sumeetkakkar avatar sustenance avatar thefourtheye avatar tlivings avatar tomalex0 avatar totherik avatar xjamundx avatar zrosenbauer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kraken-js's Issues

Configuration chaining

KrakenJS currently supports app config and node environment config.
However, almost all applications I've worked on need more than those 2 levels of config, e.g.:

  • non node environments config, e.g. dev, test, stage, prod, DR. where each one can have multiple copies: testa, testb, testc . I guess the naming is custom.
  • internal vs external config
  • datacenter/region config, e.g. on the same test environment, there are some configs that would be specific to certain datacenter or region
    So a config property can override each other based on its position in the chain.

Is it possible for Kraken to consume the config files under config directory, then in app.json I can configure the config chain?

I understand that this can be done outside of Kraken. nconf works nicely, and it's indeed something that I had at my Kraken-like module at work.
But for what KrakenJS is trying to achieve, I think it's a common pattern and can translate to less plumbing to worry about for application development.

Reversible Routes... addressing the issue of D.R.Y. in routes.

A bit of backstory (because from my experience, most NodeJS people aren't even aware this is a thing)

In django we have the concept of DRY, where we only define our routes once in the project or apps urls.py. There we give each route a regex pattern (defining some matches for kwargs and args), a name, a namespace and a controller to handle this matched route.

if for example I have a route like (using python code as an example):

url("^products/(?P<productID>\d+)/$", views.ProductDetailView.as_view(), name="product-detail"),
url("^auth/google/$", views.SocialAuthRedirectView.as_view(), name="social-auth-google")

In a template if I want to generate an url in my controllers (django calls them views):

import reverse

class SocialAuthRedirectView(RedirectView):
    def get_success_url(self, *args, **kwargs):
        return reverse("social-auth-google")

and in my templates (what you guys call views):

{% extends "base.html" %}

{% block content %}
  <a href='{% url "social-auth-google" %}'> login with google </a>
{% endblock %}

So ignoring that i'm using python here to illustrate a deficiency in most nodejs routing modules... (that of Don't Repeat Yourself), using express-enrouten, how would I achieve the above in nodejs?

I'm really not keen on hardcoding urls in my templates or my js modules. it's really bad practice and makes my modules non-portable.

Release the Kraken!

Add an alias to the start command (npm start) so it fits better with the project name:
release the kraken

image

exress validator

Hi, I am working with Sujana in Paypal professional service.
I am trying to use express validator with Kraken.
I have downloaded express validator. How can I configure it with Kraken?
I am looking at app.json file but not sure what the syntax should be.
Thank you,

Vivian Yu
Developer
[email protected]

Add support for graceful shutdowns

Not totally sure where the behavior belongs, but we want to be able to stop the server from accepting connections and allowing it to drain existing connections before exiting. We can do this a number of ways, but adding a hook for a process signal seems most straightforward:

Add hook for an agreed upon signal (SIGTERM?)
Stop server (prevent new connections)
Add 'Connection: close' to all existing connection responses after server.close().
Once server closes, exit process with appropriate status code

Auto-reload?

I would very much like it if my kraken app would auto-reload when the server source files are changed.

I'm not necessarily suggesting that this be built into Kraken โ€” I just want to know how and where this functionality should fit into my stack. Should it baked into Kraken? Should I look into using something like remy/nodemon?

Any thoughts would be appreciated.

Socket.IO example

Hi,

Are there any plans to create an example app which uses Socket.IO? I've been trying to integrate it myself but I can't seem to get Socket.IO to listen on the express server which Kraken creates. I'm using app.requestStart but /socket.io/socket.io.js isn't available (with a self created express server on another port it works fine).

Thanks.

Clarify application lifecycle docs

The methods are injection points for adding middleware and functionality in a given place on app startup. The docs aren't entirely clear about the fact that they are not runtime.

Requests Served example in README is missing...

Hi guys,

Thanks for releasing Kraken; I watched a talk on YouTube on how PayPal's dev approach was given a 'modern' upgrade and was rather excited to hear you'd be releasing your dev stack.

Just noticed that the Requests Served example on the README is currently missing; since it's early days, no worries. Quick heads up :)

Cheers M.

Config usage documentation

I am very much a Node newbie and I am checking out how to build web apps leveraging Kraken. So far it has been a great experience. I did want to relay a bit of friction I ran into trying to configure my application on startup using the handy config infrastructure.

I added a custom kev/value to config/app.json. I was unsure of how I should retrieve the value. The documentation doesn't have an example. My first inclination was to simply try my key as a property of the config object. config.mykey

I had to dive into the tests and it seems I need to do the Backbone like thing and do a get config.get('mykey')

No big deal. It seems to me that an example in the Configuration section of the read me would be helpful to others to avoid having to dive into the code.

Thanks for the great project.

requestBeforeRoute example not working as expected

I'm trying to integrate password-local with Kraken using the example in the README. The redirect for an incorrect password works fine, but npm dies when the credentials are correct.

Error:

Wed, 27 Nov 2013 21:48:03 GMT uncaughtException passport.initialize() middleware not in use
Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn (/home/nmalcolm/libertas/node_modules/passport/lib/passport/http/request.js:30:30)
    at Context.delegate.success (/home/nmalcolm/libertas/node_modules/passport/lib/passport/middleware/authenticate.js:194:13)
    at Context.actions.success (/home/nmalcolm/libertas/node_modules/passport/lib/passport/context/http/actions.js:21:25)
    at verified (/home/nmalcolm/libertas/node_modules/passport-local/lib/passport-local/strategy.js:83:10)
    at /home/nmalcolm/libertas/controllers/index.js:86:16
    at findByUsername (/home/nmalcolm/libertas/controllers/index.js:45:14)
    at /home/nmalcolm/libertas/controllers/index.js:82:7
    at process._tickCallback (node.js:415:13)
npm ERR! weird error 1
npm ERR! not ok code 0

As you can see below I have used requestBeforeRoute but it's still failing. Is there something I'm missing, or is the feature just a bit janky?

controllers/index.js:

'use strict';

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

module.exports = function (server) {

    server.requestBeforeRoute = function (app) {
        // Register passport-js middleware
        app.use(passport.initialize());
        app.use(passport.session());
    };

    server.get('/', function (req, res) {
        var model = { name: global.application_title, token: res.locals._csrf };
        res.render('index', model);
    });

    server.post('/',
      passport.authenticate('local', { failureRedirect: '/bad.txt' }),
      function(req, res) {
        res.redirect('/good.txt');
    });

};

var users = [
    { id: 1, username: 'bob', password: 'secret', email: '[email protected]' }
  , { id: 2, username: 'joe', password: 'birthday', email: '[email protected]' }
];

function findById(id, fn) {
  var idx = id - 1;
  if (users[idx]) {
    fn(null, users[idx]);
  } else {
    fn(new Error('User ' + id + ' does not exist'));
  }
}

function findByUsername(username, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
      return fn(null, user);
    }
  }
  return fn(null, null);
}


// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});


// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(
  function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // Find the user by username. If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure and set a flash message. Otherwise, return the
      // authenticated `user`.
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
));

Deploying to Heroku

Works locally, but when deployed to heroku I'm getting this error:

$ node index.js
[TypeError: Arguments to path.join must be strings]

Installing generator-kraken and running yo for a fresh install from the heroku console works though.. I'm not sure what exactly generator-kraken does, and if it installs any other deps...

getting start error

I read getting start to start my first kraken-js project.

when i run the project it throws :

my env:

node v0.10.22
win 7 x64

500 Error: Failed to lookup view "index"

    at Function.app.render (E:\ProjectNode\hi\node_modules\express\lib\application.js:493:17)
    at Function.clobbered [as render] (E:\ProjectNode\hi\node_modules\makara\lib\view\js.js:49:20)
    at ServerResponse.res.render (E:\ProjectNode\hi\node_modules\express\lib\response.js:801:7)
    at ServerResponse.app.response.render (E:\ProjectNode\hi\node_modules\kraken-js\lib\patch\stream.js:71:32)
    at E:\ProjectNode\hi\controllers\index.js:9:13
    at callbacks (E:\ProjectNode\hi\node_modules\express\lib\router\index.js:164:37)
    at param (E:\ProjectNode\hi\node_modules\express\lib\router\index.js:138:11)
    at pass (E:\ProjectNode\hi\node_modules\express\lib\router\index.js:145:5)
    at Router._dispatch (E:\ProjectNode\hi\node_modules\express\lib\router\index.js:173:5)
    at Object.router (E:\ProjectNode\hi\node_modules\express\lib\router\index.js:33:10)

Support for CoffeeScript

I've been trying to create controllers with .coffee extensions (and converted the ./index.js file to index.coffee - and updated package.json to reflect that). However, the .coffee controllers seem to be ignored. Is there an easy way to utilize coffeescript in kraken without having to compile all controllers, etc. into js?

Cannot start sample application

I followed the steps mentioned in the ReadMe file and Krakenjs.com to setup and run the HelloWorld app.

But, for some reason, when I try npm start, I am getting the following error:

LM-SJC-00712384:SampleNodeApp schandrashekar$ npm start

[email protected] start /Users/schandrashekar/Documents/Workspace_nodeapp/SampleNodeApp
node index.js

[TypeError: Cannot read property 'prototype' of undefined]

I havent changed anything within the project. Just followed the instructions mentioned.

Plugin Architecture for Middleware

This gap in the kraken design has given me heartburn since day 1, and I'm sure it's one of the reasons people look to hapi.js as opposed to express/connect.

Without this feature we will continue to get PRs adding if statements around each registered middleware.

Some folks have already solved this (e.g. c9 + architect) but I'm thinking we can do something slightly lighter weight than wrapping all middleware in yet another API.

Connect 3.0 multipart & limit removal

Since connect multipart is going away, we need to define a strategy for moving forward, whether it's adding multipart support to kraken or pushing it on to the app owner to handle.

connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0

middleware.json "logger" conflicts with app.json "logger"

Kraken adds a express.logger listener, even though it can be configured by adding a "logger" section to middleware.json, that conflicts with app.json "logger".

Need a way to turn off Kraken logging to express.logger, or resolve the conflict somehow.

Unable to start on Windows

I generated a basic Kraken.js template on Windows by using yo kraken, said yes to RequireJS and filled the other details out. When I attempt to run the project though, I run into this:

D:\localdocs\versioned-projects\web\kraken-test>npm start

> [email protected] start D:\localdocs\versioned-projects\web\kraken-test
> node index.js

Multipart body parsing will be disabled by default in future versions. To enable
, use `middleware:multipart` configuration.
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
{ [Error: listen EACCES] code: 'EACCES', errno: 'EACCES', syscall: 'listen' }

Is this something that can be 'fixed', or would it require changing dependencies etc.?

grunt build fails on Windows 7

The grunt build task is failing on my Windows 7 machine. After creating a project with the yo kraken command, if I immediately run grunt build, I get this output:

Running "jshint:files" (jshint) task
>> 2 files lint free.

Running "less:compile" (less) task
File .build/css/app.css created.

Running "requirejs:compile" (requirejs) task

Tracing dependencies for: app
Uglifying file: c:/Users/cpryce/projects/ktest2/.build/js/app.js
Uglifying file: c:/Users/cpryce/projects/ktest2/.build/js/config.js

app.js
----------------
config.js
app.js


Running "clean:tmp" (clean) task

Running "clean:build" (clean) task

Running "makara:files" (makara) task
Warning: Invalid regular expression: /([\]?)$/: Unterminated character class Use --force to continue.

Aborted due to warnings.

This is possibly an error with the dustjs-i18n.js task in makara. It would seem this line would make an invalid RexExp if the path separator is ''

var regexp = new RegExp('([' + path.sep + ']?)$');

Middleware configuration

Again I am new to Node and Express so I am not idiomatic in my approach. I am getting a lovely error with no stack or line number where it occurred. Googling around it seems I need to setup the express error Handler to spit out details.

app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

I could not figure out how to edit middleware.json to accomplish this.

I tried:

    "middleware": {
    //...
        "errorHandler": {
            "dumpExceptions": true,
            "showStack": true
        }
    }

I was able to get things going by adding the app.use statement to my app.configure callback but my guess is there is a much better way.

Getting new kraken project to 'hello world'?

Thanks for releasing Kraken, I'm looking forward to checking it out after seeing some of your presos on it.

I've created a new project per https://github.com/paypal/kraken-js (yo kraken) but when I run "npm start" I get

% npm start
> [email protected] start /home/ctoomey/devct/nodejs/krakenDemo
> node index.js
[TypeError: Cannot read property 'prototype' of undefined]

Having only played a little bit with node and express, I'm not sure what's missing from the skeletal project that I would need to add to get node started up successfully and serving a simple 'hello world' page when hitting localhost:8000/.

Can you tell me, and consider adding that info to the above page for other newbies like me?

thx,
Chris

P.S. The email address listed, [email protected], is bouncing:

Delivery to the following recipient failed permanently:

 [email protected]

Technical details of permanent failure:
Google tried to deliver your message, but it was rejected by the server for the recipient domain paypal.com by lore.ebay.com. [216.113.175.103].

The error that the other server returned was:
550 #5.1.0 Address rejected.

require.js is missing from public/js/lib

The app that gets generated by 'yo kraken' uses require.js. However in master.dust the script line:

<script data-main="js/app" src="js/lib/require.js"></script>

expects it to be in that directory.

The yo kraken script needs to add require.js to that directory.

Add info about testing to FAQ

@johnnyaboh A paragraph about testing best practices. I'd like to know which libraries are you using to test your kraken apps

CPU-intensive handling

This is probably borderline question and feature request.

How will KrakenJS handle the situation where the application logic is CPU intensive? Where requests keep getting accepted, the event loop grows, and eventually the process runs out of memory.

Is there any plan to add something like toobusy module to identify this situation so Kraken would no longer accept more requests when the process is already 'busy'.

Or would this be considered an OPS problem that shouldn't be handled by Kraken?
Edit: or is it the responsibility of the application to move the CPU-intensive task to a separate process outside of Kraken?

App fails to start if not invoked from the app root.

eg: App lives in ~/dev/myApp/index.js

If I invoke the app from a different directory it fails:

eg:

~dev $ node myApp/index.js

Solution (PR to be submitted later)
This line

this._config = config.create(this._resolve('.'));
could be changed to
this._config = config.create(this._resolve(path.dirname(process.argv[1])));

To reflect the true root of the app, as opposed to the current working directory.

Add additonal kraken:state values

#21 added kraken:state to the app to check for when it's in a disconnecting mode. We should add additional values listening, disconnected, and starting.

Using Kraken for full-blown app example

Having trouble wrapping my head around how should I configure kraken-js app to use mongoosejs or something similar. Can I configure using config files, or do I do it the old way.
The suite is quite nice, I really like the app security module really nice work guys. Also it seems quite hard to find kraken-js related info as there is another project named kraken. Also what about IRC channel?

Allow for no view engine

I'm trying to use kraken to build an API server and as such I don't require any templating engine but I can't configure the need for one away.

I've tried:

"view engines": null

and

"view engines": {}

Both fail. I'd be willing to make a PR for this. Any thoughts on how it should be implemented?

Getting 404s for public/components assets when node env is production

I have been hacking on a project using kraken and I have run into issues with the templates/css & bower components installed in the public directory.

I can get either to work but not both..

If i configure the middleware.json as follows:

    "static": {
      "srcRoot": "path:./public",
      "rootPath": "path:./.build"
    }

All the templates and css work but i get 404s for anything in public/components as it is trying to load it from ./build/components. Is this intentional?

If i configure middleware.json as follows:

    "static": {
      "srcRoot": "path:./public",
      "rootPath": "path:./public"
    }

Then templates work but css, specifically the files compiled by less don't load as it is looking for them in public/css. All of the stuff in ./public/components does work though.

Any ideas how to get both these working at the same time?

Upgrade to use dust-js 2.2.2

Should we consider updating the generator to use dusts-linkedin 2.2.2 (2.2.3 is not yet out on npm).

I was reading through the change log and one new feature in particular seems useful: Support for dynamic partial names:

Instead of :
{> "path/to/partial"}

Use:
{> "{pathToPartial}" }

It could be tangentially useful for Poornima's task.

The only place where there might be an issue is in one of adaro's test fixtures, where we have what seems like a compiled template, that uses something that is now deprecated. (getPath, in /test/fixtures/templates/index.js).
Tests run green with the newer version.

(They also have some new, nicer debuging features)

A lot of console logs that interfering with out test

We are getting tons of these messages from Kraken to our console, interfering with our test outputs, making it hard to spot and debug test failures.

127.0.0.1 - - [Wed, 11 Dec 2013 19:11:41 GMT] "POST /test HTTP/1.1" 200 16944 "-" "CERN-LineMode/2.15 libwww/2.17b3"
127.0.0.1 - - [Wed, 11 Dec 2013 19:11:41 GMT] "POST /test HTTP/1.1" 200 14211 "-" "CERN-LineMode/2.15 libwww/2.17b3"
127.0.0.1 - - [Wed, 11 Dec 2013 19:11:41 GMT] "POST /test HTTP/1.1" 200 17362 "-" "CERN-LineMode/2.15 libwww/2.17b3"
127.0.0.1 - - [Wed, 11 Dec 2013 19:11:41 GMT] "POST /test HTTP/1.1" 200 14613 "-" "CERN-LineMode/2.15 libwww/2.17b3"

Error in production mode

My app works great in dev mode, but when i try to execute in production i have the following error:

    Tue, 17 Dec 2013 00:01:42 GMT uncaughtException Object [object Object] has no method '_get'
TypeError: Object [object Object] has no method '_get'
    at body_0 (cache.vm:1:563)
    at /var/www/pruebakraken/node_modules/adaro/lib/patch/index.js:85:33
    at /var/www/pruebakraken/node_modules/adaro/lib/reader/js.js:47:13
    at /var/www/pruebakraken/node_modules/makara/lib/cache.js:68:13
    at fs.js:266:14
    at /var/www/pruebakraken/node_modules/makara/node_modules/graceful-fs/graceful-fs.js:103:5
    at Object.oncomplete (fs.js:107:15)

any idea?

PS: Sorry for my bad english

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.