Tizen 2.0 Release
[platform/framework/web/web-ui-fw.git] / libs / js / jquery-mobile-1.2.0 / node_modules / grunt / node_modules / connect / lib / middleware / csrf.js
1 /*!
2  * Connect - csrf
3  * Copyright(c) 2011 Sencha Inc.
4  * MIT Licensed
5  */
6
7 /**
8  * Module dependencies.
9  */
10
11 var utils = require('../utils');
12
13 /**
14  * Anti CSRF:
15  *
16  * CRSF protection middleware.
17  *
18  * By default this middleware generates a token named "_csrf"
19  * which should be added to requests which mutate
20  * state, within a hidden form field, query-string etc. This
21  * token is validated against the visitor's `req.session._csrf`
22  * property.
23  *
24  * The default `value` function checks `req.body` generated
25  * by the `bodyParser()` middleware, `req.query` generated
26  * by `query()`, and the "X-CSRF-Token" header field.
27  *
28  * This middleware requires session support, thus should be added
29  * somewhere _below_ `session()` and `cookieParser()`.
30  *
31  * Options:
32  *
33  *    - `value` a function accepting the request, returning the token 
34  *
35  * @param {Object} options
36  * @api public
37  */
38
39 module.exports = function csrf(options) {
40   var options = options || {}
41     , value = options.value || defaultValue;
42
43   return function(req, res, next){
44     // generate CSRF token
45     var token = req.session._csrf || (req.session._csrf = utils.uid(24));
46
47     // ignore these methods
48     if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();
49
50     // determine value
51     var val = value(req);
52
53     // check
54     if (val != token) return next(utils.error(403));
55     
56     next();
57   }
58 };
59
60 /**
61  * Default value function, checking the `req.body`
62  * and `req.query` for the CSRF token.
63  *
64  * @param {IncomingMessage} req
65  * @return {String}
66  * @api private
67  */
68
69 function defaultValue(req) {
70   return (req.body && req.body._csrf)
71     || (req.query && req.query._csrf)
72     || (req.headers['x-csrf-token']);
73 }