
const keystone = require('keystone');
const jwt = require('jsonwebtoken');

/*
  JWT middleware
*/

exports.requireJwtAuth = function(req, res, next) {
  const errorMessage = {
    badHeader: 'Bad request - missing JWT header',
    unauthorized: 'Unauthorized - JWT',
  };

  if (!req.headers || !req.headers.authorization || !req.headers.authorization.startsWith("JWT ")) {
    return res.status(400).json({ error: errorMessage.badHeader })
  }
  
  const token = req.headers.authorization.substr(4);
  const secret = keystone._options.rest.jwtSecret;
  
  try {
    var decoded = jwt.verify(token, secret);
    keystone.list('User').model.findOne({ _id: decoded.user }).exec(function(err, user) {
      req.user = user;
      next();
    });
    return;
  } catch(err) {
    // err
  }
  
  // if (req.headers.authorization === ) return next();
  return res.status(403).json({ error: errorMessage.unauthorized });
}

@@ -268,16 +268,145 @@
 ,%0A  %7D;%0A%0A
+  // Enable auth with current Keystone's browser session%0A  if (req.user) %7B%0A    next();%0A    return;%0A  %7D%0A%0A  // Validate JWT header%0A
   if (!r
@@ -494,24 +494,24 @@
 (%22JWT %22)) %7B%0A
-
     return r
@@ -679,16 +679,50 @@
 ret;%0A  %0A
+  // Decode and verify JWT header%0A
   try %7B%0A
@@ -957,58 +957,27 @@
  // 
-if (req.headers.authorization === ) return next();
+Defaults to failure
 %0A  r

Enable Keystone's session auth for Rest API