{"size": 1221, "ext": "js", "max_stars_repo_path": "deepstream/auth.webtask.js", "max_stars_repo_name": "RiverCut/multinc-role", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deepstream/auth.webtask.js", "max_issues_repo_name": "RiverCut/multinc-role", "max_issues_repo_issues_event_min_datetime": "2017-11-27T20:20:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-28T02:52:15.000Z", "max_forks_repo_path": "deepstream/auth.webtask.js", "max_forks_repo_name": "RiverCut/multinc-role", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 4, "max_forks_count": null, "avg_line_length": 22.2, "max_line_length": 81, "alphanum_fraction": 0.5986895987}

/**
 *  This is hosted by webtask.io to allow authentication via deepstream.
 */
var jwt = require('jsonwebtoken');
var uuid = require('uuid').v4;

module.exports = function(context, cb) {
  if(!context.data) return;

  function verifyToken(token) {
    try {
      jwt.verify(token, context.secrets.AUTH0_SECRET, { algorithms: ['HS256'] });
      return true;
    } catch(e) {
      return false;
    }
  }

  var serverToken = context.secrets.SERVER_TOKEN;
  var authData = context.body.authData;
  var generatedId = uuid();

  if(authData && authData.token) {

    // check if the token is a server token
    if(authData.token === serverToken) {
      cb(null, {
        username: 'server-' + generatedId,
        clientData: { id: 'server-' + generatedId },
        serverData: { hasAuthority: true }
      });

      return;
    }

    // check if the token is an auth token
    if(verifyToken(authData.token)) {

      var decodedToken = jwt.decode(authData.token);
      var username = decodedToken['http://multinc/username'];

      cb(null, {
        username: username,
        clientData: { id: username },
        serverData: { }
      });
      return;
    }
  }

  cb(403, { error: 'Invalid Token' });

};
