chore: use monorepo organization
This commit is contained in:
parent
deaf7d6ecc
commit
a687827f7e
1099 changed files with 8184 additions and 11535 deletions
|
|
@ -0,0 +1,175 @@
|
|||
const simpleWebauthn = require('@simplewebauthn/server')
|
||||
const base64url = require('base64url')
|
||||
const _ = require('lodash/fp')
|
||||
|
||||
const userManagement = require('../userManagement')
|
||||
const credentials = require('../../../../hardware-credentials')
|
||||
const T = require('../../../../time')
|
||||
const users = require('../../../../users')
|
||||
|
||||
const devMode = require('minimist')(process.argv.slice(2)).dev
|
||||
|
||||
const REMEMBER_ME_AGE = 90 * T.day
|
||||
|
||||
const generateAttestationOptions = (session, options) => {
|
||||
return users.getUserById(options.userId).then(user => {
|
||||
return Promise.all([credentials.getHardwareCredentialsByUserId(user.id), user])
|
||||
}).then(([userDevices, user]) => {
|
||||
const opts = simpleWebauthn.generateAttestationOptions({
|
||||
rpName: 'Lamassu',
|
||||
rpID: options.domain,
|
||||
userName: user.username,
|
||||
userID: user.id,
|
||||
timeout: 60000,
|
||||
attestationType: 'indirect',
|
||||
excludeCredentials: userDevices.map(dev => ({
|
||||
id: dev.data.credentialID,
|
||||
type: 'public-key',
|
||||
transports: ['usb', 'ble', 'nfc', 'internal']
|
||||
})),
|
||||
authenticatorSelection: {
|
||||
userVerification: 'discouraged',
|
||||
requireResidentKey: false
|
||||
}
|
||||
})
|
||||
|
||||
session.webauthn = {
|
||||
attestation: {
|
||||
challenge: opts.challenge
|
||||
}
|
||||
}
|
||||
|
||||
return opts
|
||||
})
|
||||
}
|
||||
|
||||
const generateAssertionOptions = (session, options) => {
|
||||
return userManagement.authenticateUser(options.username, options.password).then(user => {
|
||||
return credentials.getHardwareCredentialsByUserId(user.id).then(devices => {
|
||||
const opts = simpleWebauthn.generateAssertionOptions({
|
||||
timeout: 60000,
|
||||
allowCredentials: devices.map(dev => ({
|
||||
id: dev.data.credentialID,
|
||||
type: 'public-key',
|
||||
transports: ['usb', 'ble', 'nfc', 'internal']
|
||||
})),
|
||||
userVerification: 'discouraged',
|
||||
rpID: options.domain
|
||||
})
|
||||
|
||||
session.webauthn = {
|
||||
assertion: {
|
||||
challenge: opts.challenge
|
||||
}
|
||||
}
|
||||
|
||||
return opts
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const validateAttestation = (session, options) => {
|
||||
const webauthnData = session.webauthn.attestation
|
||||
const expectedChallenge = webauthnData.challenge
|
||||
|
||||
return Promise.all([
|
||||
users.getUserById(options.userId),
|
||||
simpleWebauthn.verifyAttestationResponse({
|
||||
credential: options.attestationResponse,
|
||||
expectedChallenge: `${expectedChallenge}`,
|
||||
expectedOrigin: `https://${options.domain}${devMode ? `:3001` : ``}`,
|
||||
expectedRPID: options.domain
|
||||
})
|
||||
])
|
||||
.then(([user, verification]) => {
|
||||
const { verified, attestationInfo } = verification
|
||||
|
||||
if (!(verified || attestationInfo)) {
|
||||
session.webauthn = null
|
||||
return false
|
||||
}
|
||||
|
||||
const {
|
||||
counter,
|
||||
credentialPublicKey,
|
||||
credentialID
|
||||
} = attestationInfo
|
||||
|
||||
return credentials.getHardwareCredentialsByUserId(user.id)
|
||||
.then(userDevices => {
|
||||
const existingDevice = userDevices.find(device => device.data.credentialID === credentialID)
|
||||
|
||||
if (!existingDevice) {
|
||||
const newDevice = {
|
||||
counter,
|
||||
credentialPublicKey,
|
||||
credentialID
|
||||
}
|
||||
credentials.createHardwareCredential(user.id, newDevice)
|
||||
}
|
||||
|
||||
session.webauthn = null
|
||||
return verified
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const validateAssertion = (session, options) => {
|
||||
return userManagement.authenticateUser(options.username, options.password).then(user => {
|
||||
const expectedChallenge = session.webauthn.assertion.challenge
|
||||
|
||||
return credentials.getHardwareCredentialsByUserId(user.id).then(devices => {
|
||||
const dbAuthenticator = _.find(dev => {
|
||||
return Buffer.from(dev.data.credentialID).compare(base64url.toBuffer(options.assertionResponse.rawId)) === 0
|
||||
}, devices)
|
||||
|
||||
if (!dbAuthenticator.data) {
|
||||
throw new Error(`Could not find authenticator matching ${options.assertionResponse.id}`)
|
||||
}
|
||||
|
||||
const convertedAuthenticator = _.merge(
|
||||
dbAuthenticator.data,
|
||||
{ credentialPublicKey: Buffer.from(dbAuthenticator.data.credentialPublicKey) }
|
||||
)
|
||||
|
||||
let verification
|
||||
try {
|
||||
verification = simpleWebauthn.verifyAssertionResponse({
|
||||
credential: options.assertionResponse,
|
||||
expectedChallenge: `${expectedChallenge}`,
|
||||
expectedOrigin: `https://${options.domain}${devMode ? `:3001` : ``}`,
|
||||
expectedRPID: options.domain,
|
||||
authenticator: convertedAuthenticator
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
return false
|
||||
}
|
||||
|
||||
const { verified, assertionInfo } = verification
|
||||
|
||||
if (!verified) {
|
||||
session.webauthn = null
|
||||
return false
|
||||
}
|
||||
|
||||
dbAuthenticator.data.counter = assertionInfo.newCounter
|
||||
return credentials.updateHardwareCredential(dbAuthenticator)
|
||||
.then(() => {
|
||||
const finalUser = { id: user.id, username: user.username, role: user.role }
|
||||
session.user = finalUser
|
||||
if (options.rememberMe) session.cookie.maxAge = REMEMBER_ME_AGE
|
||||
|
||||
session.webauthn = null
|
||||
return verified
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateAttestationOptions,
|
||||
generateAssertionOptions,
|
||||
validateAttestation,
|
||||
validateAssertion
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
const simpleWebauthn = require('@simplewebauthn/server')
|
||||
const base64url = require('base64url')
|
||||
const _ = require('lodash/fp')
|
||||
|
||||
const credentials = require('../../../../hardware-credentials')
|
||||
const T = require('../../../../time')
|
||||
const users = require('../../../../users')
|
||||
|
||||
const devMode = require('minimist')(process.argv.slice(2)).dev
|
||||
|
||||
const REMEMBER_ME_AGE = 90 * T.day
|
||||
|
||||
const generateAttestationOptions = (session, options) => {
|
||||
return users.getUserById(options.userId).then(user => {
|
||||
return Promise.all([credentials.getHardwareCredentialsByUserId(user.id), user])
|
||||
}).then(([userDevices, user]) => {
|
||||
const opts = simpleWebauthn.generateAttestationOptions({
|
||||
rpName: 'Lamassu',
|
||||
rpID: options.domain,
|
||||
userName: user.username,
|
||||
userID: user.id,
|
||||
timeout: 60000,
|
||||
attestationType: 'indirect',
|
||||
excludeCredentials: userDevices.map(dev => ({
|
||||
id: dev.data.credentialID,
|
||||
type: 'public-key',
|
||||
transports: ['usb', 'ble', 'nfc', 'internal']
|
||||
})),
|
||||
authenticatorSelection: {
|
||||
userVerification: 'discouraged',
|
||||
requireResidentKey: false
|
||||
}
|
||||
})
|
||||
|
||||
session.webauthn = {
|
||||
attestation: {
|
||||
challenge: opts.challenge
|
||||
}
|
||||
}
|
||||
|
||||
return opts
|
||||
})
|
||||
}
|
||||
|
||||
const generateAssertionOptions = (session, options) => {
|
||||
return users.getUserByUsername(options.username).then(user => {
|
||||
return credentials.getHardwareCredentialsByUserId(user.id).then(devices => {
|
||||
const opts = simpleWebauthn.generateAssertionOptions({
|
||||
timeout: 60000,
|
||||
allowCredentials: devices.map(dev => ({
|
||||
id: dev.data.credentialID,
|
||||
type: 'public-key',
|
||||
transports: ['usb', 'ble', 'nfc', 'internal']
|
||||
})),
|
||||
userVerification: 'discouraged',
|
||||
rpID: options.domain
|
||||
})
|
||||
|
||||
session.webauthn = {
|
||||
assertion: {
|
||||
challenge: opts.challenge
|
||||
}
|
||||
}
|
||||
|
||||
return opts
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const validateAttestation = (session, options) => {
|
||||
const webauthnData = session.webauthn.attestation
|
||||
const expectedChallenge = webauthnData.challenge
|
||||
|
||||
return Promise.all([
|
||||
users.getUserById(options.userId),
|
||||
simpleWebauthn.verifyAttestationResponse({
|
||||
credential: options.attestationResponse,
|
||||
expectedChallenge: `${expectedChallenge}`,
|
||||
expectedOrigin: `https://${options.domain}${devMode ? `:3001` : ``}`,
|
||||
expectedRPID: options.domain
|
||||
})
|
||||
])
|
||||
.then(([user, verification]) => {
|
||||
const { verified, attestationInfo } = verification
|
||||
|
||||
if (!(verified || attestationInfo)) {
|
||||
session.webauthn = null
|
||||
return false
|
||||
}
|
||||
|
||||
const {
|
||||
counter,
|
||||
credentialPublicKey,
|
||||
credentialID
|
||||
} = attestationInfo
|
||||
|
||||
return credentials.getHardwareCredentialsByUserId(user.id)
|
||||
.then(userDevices => {
|
||||
const existingDevice = userDevices.find(device => device.data.credentialID === credentialID)
|
||||
|
||||
if (!existingDevice) {
|
||||
const newDevice = {
|
||||
counter,
|
||||
credentialPublicKey,
|
||||
credentialID
|
||||
}
|
||||
credentials.createHardwareCredential(user.id, newDevice)
|
||||
}
|
||||
|
||||
session.webauthn = null
|
||||
return verified
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const validateAssertion = (session, options) => {
|
||||
return users.getUserByUsername(options.username).then(user => {
|
||||
const expectedChallenge = session.webauthn.assertion.challenge
|
||||
|
||||
return credentials.getHardwareCredentialsByUserId(user.id).then(devices => {
|
||||
const dbAuthenticator = _.find(dev => {
|
||||
return Buffer.from(dev.data.credentialID).compare(base64url.toBuffer(options.assertionResponse.rawId)) === 0
|
||||
}, devices)
|
||||
|
||||
if (!dbAuthenticator.data) {
|
||||
throw new Error(`Could not find authenticator matching ${options.assertionResponse.id}`)
|
||||
}
|
||||
|
||||
const convertedAuthenticator = _.merge(
|
||||
dbAuthenticator.data,
|
||||
{ credentialPublicKey: Buffer.from(dbAuthenticator.data.credentialPublicKey) }
|
||||
)
|
||||
|
||||
let verification
|
||||
try {
|
||||
verification = simpleWebauthn.verifyAssertionResponse({
|
||||
credential: options.assertionResponse,
|
||||
expectedChallenge: `${expectedChallenge}`,
|
||||
expectedOrigin: `https://${options.domain}${devMode ? `:3001` : ``}`,
|
||||
expectedRPID: options.domain,
|
||||
authenticator: convertedAuthenticator
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
return false
|
||||
}
|
||||
|
||||
const { verified, assertionInfo } = verification
|
||||
|
||||
if (!verified) {
|
||||
context.req.session.webauthn = null
|
||||
return false
|
||||
}
|
||||
|
||||
dbAuthenticator.data.counter = assertionInfo.newCounter
|
||||
return credentials.updateHardwareCredential(dbAuthenticator)
|
||||
.then(() => {
|
||||
const finalUser = { id: user.id, username: user.username, role: user.role }
|
||||
session.user = finalUser
|
||||
if (options.rememberMe) session.cookie.maxAge = REMEMBER_ME_AGE
|
||||
|
||||
session.webauthn = null
|
||||
return verified
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateAttestationOptions,
|
||||
generateAssertionOptions,
|
||||
validateAttestation,
|
||||
validateAssertion
|
||||
}
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
const simpleWebauthn = require('@simplewebauthn/server')
|
||||
const base64url = require('base64url')
|
||||
const _ = require('lodash/fp')
|
||||
|
||||
const credentials = require('../../../../hardware-credentials')
|
||||
const T = require('../../../../time')
|
||||
const users = require('../../../../users')
|
||||
|
||||
const devMode = require('minimist')(process.argv.slice(2)).dev
|
||||
|
||||
const REMEMBER_ME_AGE = 90 * T.day
|
||||
|
||||
const generateAttestationOptions = (session, options) => {
|
||||
return credentials.getHardwareCredentials().then(devices => {
|
||||
const opts = simpleWebauthn.generateAttestationOptions({
|
||||
rpName: 'Lamassu',
|
||||
rpID: options.domain,
|
||||
userName: `Usernameless user created at ${new Date().toISOString()}`,
|
||||
userID: options.userId,
|
||||
timeout: 60000,
|
||||
attestationType: 'direct',
|
||||
excludeCredentials: devices.map(dev => ({
|
||||
id: dev.data.credentialID,
|
||||
type: 'public-key',
|
||||
transports: ['usb', 'ble', 'nfc', 'internal']
|
||||
})),
|
||||
authenticatorSelection: {
|
||||
authenticatorAttachment: 'cross-platform',
|
||||
userVerification: 'discouraged',
|
||||
requireResidentKey: false
|
||||
}
|
||||
})
|
||||
|
||||
session.webauthn = {
|
||||
attestation: {
|
||||
challenge: opts.challenge
|
||||
}
|
||||
}
|
||||
|
||||
return opts
|
||||
})
|
||||
}
|
||||
|
||||
const generateAssertionOptions = (session, options) => {
|
||||
return credentials.getHardwareCredentials().then(devices => {
|
||||
const opts = simpleWebauthn.generateAssertionOptions({
|
||||
timeout: 60000,
|
||||
allowCredentials: devices.map(dev => ({
|
||||
id: dev.data.credentialID,
|
||||
type: 'public-key',
|
||||
transports: ['usb', 'ble', 'nfc', 'internal']
|
||||
})),
|
||||
userVerification: 'discouraged',
|
||||
rpID: options.domain
|
||||
})
|
||||
|
||||
session.webauthn = {
|
||||
assertion: {
|
||||
challenge: opts.challenge
|
||||
}
|
||||
}
|
||||
return opts
|
||||
})
|
||||
}
|
||||
|
||||
const validateAttestation = (session, options) => {
|
||||
const webauthnData = session.webauthn.attestation
|
||||
const expectedChallenge = webauthnData.challenge
|
||||
|
||||
return Promise.all([
|
||||
users.getUserById(options.userId),
|
||||
simpleWebauthn.verifyAttestationResponse({
|
||||
credential: options.attestationResponse,
|
||||
expectedChallenge: `${expectedChallenge}`,
|
||||
expectedOrigin: `https://${options.domain}${devMode ? `:3001` : ``}`,
|
||||
expectedRPID: options.domain
|
||||
})
|
||||
])
|
||||
.then(([user, verification]) => {
|
||||
const { verified, attestationInfo } = verification
|
||||
|
||||
if (!(verified || attestationInfo)) {
|
||||
session.webauthn = null
|
||||
return verified
|
||||
}
|
||||
|
||||
const {
|
||||
fmt,
|
||||
counter,
|
||||
aaguid,
|
||||
credentialPublicKey,
|
||||
credentialID,
|
||||
credentialType,
|
||||
userVerified,
|
||||
attestationObject
|
||||
} = attestationInfo
|
||||
|
||||
return credentials.getHardwareCredentialsByUserId(user.id)
|
||||
.then(userDevices => {
|
||||
const existingDevice = userDevices.find(device => device.data.credentialID === credentialID)
|
||||
|
||||
if (!existingDevice) {
|
||||
const newDevice = {
|
||||
fmt,
|
||||
counter,
|
||||
aaguid,
|
||||
credentialPublicKey,
|
||||
credentialID,
|
||||
credentialType,
|
||||
userVerified,
|
||||
attestationObject
|
||||
}
|
||||
credentials.createHardwareCredential(user.id, newDevice)
|
||||
}
|
||||
|
||||
session.webauthn = null
|
||||
return verified
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const validateAssertion = (session, options) => {
|
||||
const expectedChallenge = session.webauthn.assertion.challenge
|
||||
|
||||
return credentials.getHardwareCredentials().then(devices => {
|
||||
const dbAuthenticator = _.find(dev => {
|
||||
return Buffer.from(dev.data.credentialID).compare(base64url.toBuffer(options.assertionResponse.rawId)) === 0
|
||||
}, devices)
|
||||
|
||||
if (!dbAuthenticator.data) {
|
||||
throw new Error(`Could not find authenticator matching ${options.assertionResponse.id}`)
|
||||
}
|
||||
|
||||
const convertedAuthenticator = _.merge(
|
||||
dbAuthenticator.data,
|
||||
{ credentialPublicKey: Buffer.from(dbAuthenticator.data.credentialPublicKey) }
|
||||
)
|
||||
|
||||
let verification
|
||||
try {
|
||||
verification = simpleWebauthn.verifyAssertionResponse({
|
||||
credential: options.assertionResponse,
|
||||
expectedChallenge: `${expectedChallenge}`,
|
||||
expectedOrigin: `https://${options.domain}${devMode ? `:3001` : ``}`,
|
||||
expectedRPID: options.domain,
|
||||
authenticator: convertedAuthenticator
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
return false
|
||||
}
|
||||
|
||||
const { verified, assertionInfo } = verification
|
||||
|
||||
if (!verified) {
|
||||
session.webauthn = null
|
||||
return false
|
||||
}
|
||||
|
||||
dbAuthenticator.data.counter = assertionInfo.newCounter
|
||||
return Promise.all([
|
||||
credentials.updateHardwareCredential(dbAuthenticator),
|
||||
users.getUserById(dbAuthenticator.user_id)
|
||||
])
|
||||
.then(([_, user]) => {
|
||||
const finalUser = { id: user.id, username: user.username, role: user.role }
|
||||
session.user = finalUser
|
||||
session.cookie.maxAge = REMEMBER_ME_AGE
|
||||
|
||||
session.webauthn = null
|
||||
return verified
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateAttestationOptions,
|
||||
generateAssertionOptions,
|
||||
validateAttestation,
|
||||
validateAssertion
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
const FIDO2FA = require('./FIDO2FAStrategy')
|
||||
const FIDOPasswordless = require('./FIDOPasswordlessStrategy')
|
||||
const FIDOUsernameless = require('./FIDOUsernamelessStrategy')
|
||||
|
||||
const STRATEGIES = {
|
||||
FIDO2FA,
|
||||
FIDOPasswordless,
|
||||
FIDOUsernameless
|
||||
}
|
||||
|
||||
// FIDO2FA, FIDOPasswordless or FIDOUsernameless
|
||||
const CHOSEN_STRATEGY = 'FIDO2FA'
|
||||
|
||||
module.exports = {
|
||||
CHOSEN_STRATEGY,
|
||||
strategy: STRATEGIES[CHOSEN_STRATEGY]
|
||||
}
|
||||
271
packages/server/lib/new-admin/graphql/modules/userManagement.js
Normal file
271
packages/server/lib/new-admin/graphql/modules/userManagement.js
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
const otplib = require('otplib')
|
||||
const argon2 = require('argon2')
|
||||
const _ = require('lodash/fp')
|
||||
|
||||
const constants = require('../../../constants')
|
||||
const authTokens = require('../../../auth-tokens')
|
||||
const loginHelper = require('../../services/login')
|
||||
const T = require('../../../time')
|
||||
const users = require('../../../users')
|
||||
const sessionManager = require('../../../session-manager')
|
||||
const authErrors = require('../errors')
|
||||
const credentials = require('../../../hardware-credentials')
|
||||
|
||||
const REMEMBER_ME_AGE = 90 * T.day
|
||||
|
||||
const authenticateUser = (username, password) => {
|
||||
return users.getUserByUsername(username)
|
||||
.then(user => {
|
||||
const hashedPassword = user.password
|
||||
if (!hashedPassword || !user.enabled) throw new authErrors.InvalidCredentialsError()
|
||||
return Promise.all([argon2.verify(hashedPassword, password), hashedPassword])
|
||||
})
|
||||
.then(([isMatch, hashedPassword]) => {
|
||||
if (!isMatch) throw new authErrors.InvalidCredentialsError()
|
||||
return loginHelper.validateUser(username, hashedPassword)
|
||||
})
|
||||
.then(user => {
|
||||
if (!user) throw new authErrors.InvalidCredentialsError()
|
||||
return user
|
||||
})
|
||||
}
|
||||
|
||||
const destroySessionIfSameUser = (context, user) => {
|
||||
const sessionUser = getUserFromCookie(context)
|
||||
if (sessionUser && user.id === sessionUser.id) { context.req.session.destroy() }
|
||||
}
|
||||
|
||||
const destroySessionIfBeingUsed = (sessID, context) => {
|
||||
if (sessID === context.req.session.id) {
|
||||
context.req.session.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
const getUserFromCookie = context => {
|
||||
return context.req.session.user
|
||||
}
|
||||
|
||||
const getLamassuCookie = context => {
|
||||
return context.req.cookies && context.req.cookies.lamassu_sid
|
||||
}
|
||||
|
||||
const initializeSession = (context, user, rememberMe) => {
|
||||
const finalUser = { id: user.id, username: user.username, role: user.role }
|
||||
context.req.session.user = finalUser
|
||||
if (rememberMe) context.req.session.cookie.maxAge = REMEMBER_ME_AGE
|
||||
}
|
||||
|
||||
const executeProtectedAction = (code, id, context, action) => {
|
||||
return users.getUserById(id)
|
||||
.then(user => {
|
||||
if (user.role !== 'superuser') {
|
||||
return action()
|
||||
}
|
||||
|
||||
return confirm2FA(code, context)
|
||||
.then(() => action())
|
||||
})
|
||||
}
|
||||
|
||||
const getUserData = context => {
|
||||
const lidCookie = getLamassuCookie(context)
|
||||
if (!lidCookie) return
|
||||
|
||||
const user = getUserFromCookie(context)
|
||||
return user
|
||||
}
|
||||
|
||||
const get2FASecret = (username, password) => {
|
||||
return authenticateUser(username, password)
|
||||
.then(user => {
|
||||
const secret = otplib.authenticator.generateSecret()
|
||||
const otpauth = otplib.authenticator.keyuri(user.username, constants.AUTHENTICATOR_ISSUER_ENTITY, secret)
|
||||
return Promise.all([users.saveTemp2FASecret(user.id, secret), secret, otpauth])
|
||||
})
|
||||
.then(([_, secret, otpauth]) => {
|
||||
return { secret, otpauth }
|
||||
})
|
||||
}
|
||||
|
||||
const confirm2FA = (token, context) => {
|
||||
const requestingUser = getUserFromCookie(context)
|
||||
|
||||
if (!requestingUser) throw new authErrors.InvalidCredentialsError()
|
||||
|
||||
return users.getUserById(requestingUser.id).then(user => {
|
||||
const secret = user.twofa_code
|
||||
const isCodeValid = otplib.authenticator.verify({ token, secret })
|
||||
|
||||
if (!isCodeValid) throw new authErrors.InvalidTwoFactorError()
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
const validateRegisterLink = token => {
|
||||
if (!token) throw new authErrors.InvalidUrlError()
|
||||
return users.validateUserRegistrationToken(token)
|
||||
.then(r => {
|
||||
if (!r.success) throw new authErrors.InvalidUrlError()
|
||||
return { username: r.username, role: r.role }
|
||||
})
|
||||
}
|
||||
|
||||
const validateResetPasswordLink = token => {
|
||||
if (!token) throw new authErrors.InvalidUrlError()
|
||||
return users.validateAuthToken(token, 'reset_password')
|
||||
.then(r => {
|
||||
if (!r.success) throw new authErrors.InvalidUrlError()
|
||||
return { id: r.userID }
|
||||
})
|
||||
}
|
||||
|
||||
const validateReset2FALink = token => {
|
||||
if (!token) throw new authErrors.InvalidUrlError()
|
||||
return users.validateAuthToken(token, 'reset_twofa')
|
||||
.then(r => {
|
||||
if (!r.success) throw new authErrors.InvalidUrlError()
|
||||
return users.getUserById(r.userID)
|
||||
})
|
||||
.then(user => {
|
||||
const secret = otplib.authenticator.generateSecret()
|
||||
const otpauth = otplib.authenticator.keyuri(user.username, constants.AUTHENTICATOR_ISSUER_ENTITY, secret)
|
||||
return Promise.all([users.saveTemp2FASecret(user.id, secret), user, secret, otpauth])
|
||||
})
|
||||
.then(([_, user, secret, otpauth]) => {
|
||||
return { user_id: user.id, secret, otpauth }
|
||||
})
|
||||
}
|
||||
|
||||
const deleteSession = (sessionID, context) => {
|
||||
destroySessionIfBeingUsed(sessionID, context)
|
||||
return sessionManager.deleteSessionById(sessionID)
|
||||
}
|
||||
|
||||
const login = (username, password) => {
|
||||
return authenticateUser(username, password)
|
||||
.then(user => {
|
||||
return Promise.all([credentials.getHardwareCredentialsByUserId(user.id), user.twofa_code])
|
||||
})
|
||||
.then(([devices, twoFASecret]) => {
|
||||
if (!_.isEmpty(devices)) return 'FIDO'
|
||||
return twoFASecret ? 'INPUT2FA' : 'SETUP2FA'
|
||||
})
|
||||
}
|
||||
|
||||
const input2FA = (username, password, rememberMe, code, context) => {
|
||||
return authenticateUser(username, password)
|
||||
.then(user => {
|
||||
const secret = user.twofa_code
|
||||
const isCodeValid = otplib.authenticator.verify({ token: code, secret: secret })
|
||||
if (!isCodeValid) throw new authErrors.InvalidTwoFactorError()
|
||||
|
||||
initializeSession(context, user, rememberMe)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
const setup2FA = (username, password, rememberMe, codeConfirmation, context) => {
|
||||
return authenticateUser(username, password)
|
||||
.then(user => {
|
||||
const isCodeValid = otplib.authenticator.verify({ token: codeConfirmation, secret: user.temp_twofa_code })
|
||||
if (!isCodeValid) throw new authErrors.InvalidTwoFactorError()
|
||||
|
||||
initializeSession(context, user, rememberMe)
|
||||
return users.save2FASecret(user.id, user.temp_twofa_code)
|
||||
})
|
||||
.then(() => true)
|
||||
}
|
||||
|
||||
const changeUserRole = (code, id, newRole, context) => {
|
||||
const action = () => users.changeUserRole(id, newRole)
|
||||
return executeProtectedAction(code, id, context, action)
|
||||
}
|
||||
|
||||
const enableUser = (code, id, context) => {
|
||||
const action = () => users.enableUser(id)
|
||||
return executeProtectedAction(code, id, context, action)
|
||||
}
|
||||
|
||||
const disableUser = (code, id, context) => {
|
||||
const action = () => users.disableUser(id)
|
||||
return executeProtectedAction(code, id, context, action)
|
||||
}
|
||||
|
||||
const createResetPasswordToken = (code, userID, context) => {
|
||||
const action = () => authTokens.createAuthToken(userID, 'reset_password')
|
||||
return executeProtectedAction(code, userID, context, action)
|
||||
}
|
||||
|
||||
const createReset2FAToken = (code, userID, context) => {
|
||||
const action = () => authTokens.createAuthToken(userID, 'reset_twofa')
|
||||
return executeProtectedAction(code, userID, context, action)
|
||||
}
|
||||
|
||||
const createRegisterToken = (username, role) => {
|
||||
return users.getUserByUsername(username)
|
||||
.then(user => {
|
||||
if (user) throw new authErrors.UserAlreadyExistsError()
|
||||
|
||||
return users.createUserRegistrationToken(username, role)
|
||||
})
|
||||
}
|
||||
|
||||
const register = (token, username, password, role) => {
|
||||
return users.getUserByUsername(username)
|
||||
.then(user => {
|
||||
if (user) throw new authErrors.UserAlreadyExistsError()
|
||||
return users.register(token, username, password, role).then(() => true)
|
||||
})
|
||||
}
|
||||
|
||||
const resetPassword = (token, userID, newPassword, context) => {
|
||||
return users.getUserById(userID)
|
||||
.then(user => {
|
||||
destroySessionIfSameUser(context, user)
|
||||
return users.updatePassword(token, user.id, newPassword)
|
||||
})
|
||||
.then(() => true)
|
||||
}
|
||||
|
||||
const reset2FA = (token, userID, code, context) => {
|
||||
return users.getUserById(userID)
|
||||
.then(user => {
|
||||
const isCodeValid = otplib.authenticator.verify({ token: code, secret: user.temp_twofa_code })
|
||||
if (!isCodeValid) throw new authErrors.InvalidTwoFactorError()
|
||||
|
||||
destroySessionIfSameUser(context, user)
|
||||
return users.reset2FASecret(token, user.id, user.temp_twofa_code)
|
||||
})
|
||||
.then(() => true)
|
||||
}
|
||||
|
||||
const getToken = context => {
|
||||
if (_.isNil(context.req.cookies['lamassu_sid']) || _.isNil(context.req.session.user.id))
|
||||
throw new authErrors.AuthenticationError('Authentication failed')
|
||||
|
||||
return context.req.session.user.id
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
authenticateUser,
|
||||
getUserData,
|
||||
get2FASecret,
|
||||
confirm2FA,
|
||||
validateRegisterLink,
|
||||
validateResetPasswordLink,
|
||||
validateReset2FALink,
|
||||
deleteSession,
|
||||
login,
|
||||
input2FA,
|
||||
setup2FA,
|
||||
changeUserRole,
|
||||
enableUser,
|
||||
disableUser,
|
||||
createResetPasswordToken,
|
||||
createReset2FAToken,
|
||||
createRegisterToken,
|
||||
register,
|
||||
resetPassword,
|
||||
reset2FA,
|
||||
getToken
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue