// Generated by CoffeeScript 1.10.0
(function() {
  var _, url;

  url = require('url');

  _ = require('lodash');

  module.exports = function() {
    var provider;
    provider = function(req, res, next) {
      if (req.session) {
        if (req.session.isNew || !(req.session.csrfToken != null)) {
          req.session.csrfToken = Math.random().toString(16).substring(2);
        }
        req.csrfToken = req.session.csrfToken;
      }
      return next();
    };
    provider.protect = function(opts) {
      opts = _.defaults(opts || {}, {
        queryKey: '_s'
      });
      return function(req, res, next) {
        var csrfToken, urlInfo;
        if (req.method === 'POST') {
          return next();
        }
        csrfToken = null;
        urlInfo = url.parse(req.originalUrl, true);
        if (opts.queryKey && urlInfo.query[opts.queryKey]) {
          csrfToken = urlInfo.query[opts.queryKey];
        }
        console.log(csrfToken + ' ' + req.session.csrfToken);
        if (req.session && req.session.csrfToken && req.session.csrfToken === csrfToken) {
          return next();
        } else {
          return res.status(403).end('CSRF protection prevented access, please make sure that your browser has cookies enabled');
        }
      };
    };
    return provider;
  };

}).call(this);
