CoreID/app/models/auth/MFAToken.model.js

53 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-04-22 21:56:39 +00:00
const { Model } = require('flitter-orm')
const speakeasy = require('speakeasy')
2020-05-30 22:21:47 +00:00
const MFARecoveryCode = require('./MFARecoveryCode.model')
2020-08-13 06:56:33 +00:00
const uuid = require('uuid').v4
2020-04-22 21:56:39 +00:00
class MFATokenModel extends Model {
static get services() {
return [...super.services, 'MFA']
}
static get schema() {
return {
secret: String,
otpauth_url: String,
2020-05-30 22:21:47 +00:00
recovery_codes: [MFARecoveryCode],
2020-04-22 21:56:39 +00:00
}
}
2020-05-30 22:21:47 +00:00
async attempt_recovery(code) {
for ( const token of this.recovery_codes ) {
if ( await token.verify(code) && !token.used ) {
token.used = true
return true
}
}
return false
}
async generate_recovery() {
this.recovery_codes = []
const values = []
for ( let i = 0; i < 4; i++ ) {
const value = uuid()
values.push(value)
this.recovery_codes.push(await MFARecoveryCode.create(value))
}
return values
}
2020-04-22 21:56:39 +00:00
verify(value) {
return speakeasy.totp.verify({
secret: this.secret,
encoding: 'base32',
token: value,
})
}
}
module.exports = exports = MFATokenModel