further improvement of isAuthorized

This commit is contained in:
Moriz Wahl 2022-03-14 16:22:57 +01:00
parent afdaf038cc
commit fe38cec4ac

View File

@ -18,33 +18,27 @@ const isAuthorized: AuthChecker<any> = async ({ context }, rights) => {
return true return true
// Do we have a token? // Do we have a token?
if (context.token) { if (!context.token) {
// Decode the token throw new Error('401 Unauthorized')
const decoded = decode(context.token) }
if (!decoded) {
throw new Error('403.13 - Client certificate revoked')
}
// Set context pubKey
context.pubKey = Buffer.from(decoded.pubKey).toString('hex')
// Problem found by unit testing: // Decode the token
// I have a valid token in the context, but the database is cleaned, const decoded = decode(context.token)
// so the user object cannot be found here if (!decoded) {
// this should be working for inalienable rights throw new Error('403.13 - Client certificate revoked')
}
// Set context pubKey
context.pubKey = Buffer.from(decoded.pubKey).toString('hex')
// set new header token // TODO - load from database dynamically & admin - maybe encode this in the token to prevent many database requests
// TODO - load from database dynamically & admin - maybe encode this in the token to prevent many database requests // TODO this implementation is bullshit - two database queries cause our user identifiers are not aligned and vary between email, id and pubKey
// TODO this implementation is bullshit - two database queries cause our user identifiers are not aligned and vary between email, id and pubKey const userRepository = await getCustomRepository(UserRepository)
const userRepository = await getCustomRepository(UserRepository) try {
try { const user = await userRepository.findByPubkeyHex(context.pubKey)
const user = await userRepository.findByPubkeyHex(context.pubKey) const countServerUsers = await ServerUser.count({ email: user.email })
const countServerUsers = await ServerUser.count({ email: user.email }) context.role = countServerUsers > 0 ? ROLE_ADMIN : ROLE_USER
context.role = countServerUsers > 0 ? ROLE_ADMIN : ROLE_USER } catch {
throw new Error('401 Unauthorized')
context.setHeaders.push({ key: 'token', value: encode(decoded.pubKey) })
} catch {
throw new Error('401 Unauthorized')
}
} }
// check for correct rights // check for correct rights
@ -53,6 +47,8 @@ const isAuthorized: AuthChecker<any> = async ({ context }, rights) => {
throw new Error('401 Unauthorized') throw new Error('401 Unauthorized')
} }
// set new header token
context.setHeaders.push({ key: 'token', value: encode(decoded.pubKey) })
return true return true
} }