// Setup
const util = require('util')
const Event = require('events').EventEmitter
const jwtoken = require('jsonwebtoken')
var app, config

// Exports
module.exports = Auth

function Auth (thisApp, token) {
  var self = this
  app = thisApp
  config = app.config
  self.emit('ready')
  function noCredErr () {
    return self.emit('error', 'No valid token received')
  }
  if (!token) {
    setTimeout(noCredErr, 50)
    return self
  }
  self.validateToken(token)
  return self
}

util.inherits(Auth, Event)

Auth.prototype.validateToken = function (token) {
  var self = this
  jwtoken.verify(
    token,
    config.pubKey,
    {
      algorithm: 'RS256',
      issuer: config.jwt.issuer || config.app.ns,
      audience: 'client'
    },
    function (err, data) {
      if (err) return self.emit('error', err)
      return self.setAuthObject(data)
    }
  )
}

Auth.prototype.setAuthObject = function (authObj) {
  var self = this
  var user = {
    userid: authObj.userid,
    officeid: authObj.officeid,
    all_locations: authObj.all_locations,
    managed_offices: authObj.managed_offices,
    is: {},
    can: {}
  }
  if (authObj.roles) {
    authObj.roles.forEach(function (r) {
      user.is[r.toLowerCase()] = true
    })
  }
  if (authObj.permit) {
    authObj.permit.forEach(function (p) {
      user.can[p.toLowerCase()] = true
    })
  }
  return self.emit('data', user)
}

@@ -945,184 +945,84 @@
  = %7B
-%0A    userid: authObj.userid,%0A    officeid: authObj.officeid,%0A    all_locations: authObj.all_locations,%0A    managed_offices: authObj.managed_offices,%0A    is: %7B%7D,%0A    can: %7B%7D%0A  %7D
+is: %7B%7D, can: %7B%7D%7D%0A  Object.keys(authObj).forEach((k) =%3E user%5Bk%5D = authObj%5Bk%5D)
 %0A  i
@@ -1071,28 +1071,14 @@
 ach(
-function (r) %7B%0A     
+(r) =%3E
  use
@@ -1101,31 +1101,47 @@
 se()%5D = true
+)
 %0A    
-%7D)
+delete user.roles
 %0A  %7D%0A  if (a
@@ -1188,28 +1188,14 @@
 ach(
-function (p) %7B%0A     
+(p) =%3E
  use
@@ -1227,19 +1227,72 @@
 true
+)
 %0A    
-%7D)%0A  %7D
+delete user.permit%0A  %7D%0A  delete user.aud%0A  delete user.iss
 %0A  r

Extend full auth object