Skip to content

Commit

Permalink
fix: Log username for unauthorized requests (#178)
Browse files Browse the repository at this point in the history
  • Loading branch information
csmig committed Mar 12, 2021
1 parent fc0e482 commit ac1afc9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
16 changes: 16 additions & 0 deletions api/source/utils/SmError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = class SmError extends Error {
constructor(httpStatus = 400, ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params)

// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, SmError)
}

this.name = 'SmError'
// Custom debugging information
this.httpStatus = httpStatus
}
}

33 changes: 17 additions & 16 deletions api/source/utils/auth.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const SmError = require('./SmError')
let config = require('./config');
const jwksClient = require('jwks-rsa')
const jwt = require('jsonwebtoken')
Expand All @@ -19,6 +20,13 @@ const verifyRequest = async function (req, securityDefinition, requiredScopes, c
algorithms: ['RS256']
}
let decoded = await verifyAndDecodeToken (token, getKey, options)
req.access_token = decoded
req.bearer = token
req.userObject = {
username: decoded[config.oauth.claims.username] || decoded[config.oauth.claims.servicename] || 'null',
display: decoded[config.oauth.claims.name] || 'USER',
}

let grantedScopes = decoded.scope.split(' ')
let commonScopes = _.intersectionWith(grantedScopes, requiredScopes, function(gs,rs) {
if (gs === rs) return gs
Expand All @@ -32,8 +40,7 @@ const verifyRequest = async function (req, securityDefinition, requiredScopes, c
}
})
if (commonScopes.length == 0) {
console.log("No common scopes")
writer.writeJson(req.res,{message: 'Not in scope'},403)
throw new SmError( 403, 'Not in scope' )
}
else {
// Get privileges
Expand All @@ -42,32 +49,22 @@ const verifyRequest = async function (req, securityDefinition, requiredScopes, c
privileges.canCreateCollection = roleGetter(decoded).includes('create_collection')
privileges.canAdmin = roleGetter(decoded).includes('admin')

// Build userObject
req.userObject = {
username: decoded[config.oauth.claims.username] || decoded[config.oauth.claims.servicename] || 'null',
display: decoded[config.oauth.claims.name] || 'USER',
privileges: privileges
}
req.userObject.privileges = privileges
const response = await User.getUserByUsername(req.userObject.username, ['collectionGrants', 'statistics'], false, null)
req.userObject.userId = response?.userId || null
req.userObject.collectionGrants = response?.collectionGrants || []
req.userObject.statistics = response?.statistics || {}

req.access_token = decoded
req.bearer = token

const refreshFields = {}
let now = new Date().toUTCString()
now = new Date(now).getTime()
now = now / 1000 | 0 //https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number

if (!response?.statistics?.lastAccess || now - response?.statistics?.lastAccess >= config.settings.lastAccessResolution) {
refreshFields.lastAccess = now
console.log('Will refresh lastAccess')
}
if (!response?.statistics?.lastClaims || decoded.jti !== response?.statistics?.lastClaims?.jti) {
refreshFields.lastClaims = decoded
console.log('Will refresh lastClaims')
}
if (req.userObject.username && (refreshFields.lastAccess || refreshFields.lastClaims)) {
let userId = await User.setUserData(req.userObject, refreshFields)
Expand All @@ -76,14 +73,18 @@ const verifyRequest = async function (req, securityDefinition, requiredScopes, c
}
}
if ('elevate' in req.query && (req.query.elevate === 'true' && !req.userObject.privileges.canAdmin)) {
writer.writeJson(req.res, writer.respondWithCode ( 403, {message: `User has insufficient privilege to complete this request.`} ) )
return
throw new SmError(403, 'User has insufficient privilege to complete this request.')
}
cb()
}
}
catch (err) {
writer.writeJson(req.res, { status: 403, message: err.message }, 403)
if (err.name === 'SmError') {
writer.writeJson(req.res, { status: err.httpStatus, message: err.message }, err.httpStatus)
}
else {
writer.writeJson(req.res, { status: 500, message: err.message }, 500)
}
}
}

Expand Down

0 comments on commit ac1afc9

Please sign in to comment.