2017-10-14 20:23:00 +07:00
|
|
|
import Speakeasy = require("speakeasy");
|
2017-05-21 00:16:57 +07:00
|
|
|
import BluebirdPromise = require("bluebird");
|
|
|
|
|
|
|
|
const TOTP_ENCODING = "base32";
|
2017-10-14 20:23:00 +07:00
|
|
|
const WINDOW: number = 1;
|
2017-05-21 00:16:57 +07:00
|
|
|
|
2017-05-25 20:09:29 +07:00
|
|
|
export class TOTPValidator {
|
2017-10-14 20:23:00 +07:00
|
|
|
private speakeasy: typeof Speakeasy;
|
2017-05-21 00:16:57 +07:00
|
|
|
|
2017-10-14 20:23:00 +07:00
|
|
|
constructor(speakeasy: typeof Speakeasy) {
|
2017-05-21 00:16:57 +07:00
|
|
|
this.speakeasy = speakeasy;
|
|
|
|
}
|
|
|
|
|
|
|
|
validate(token: string, secret: string): BluebirdPromise<void> {
|
2017-10-14 20:23:00 +07:00
|
|
|
const isValid = this.speakeasy.totp.verify({
|
2017-05-21 00:16:57 +07:00
|
|
|
secret: secret,
|
2017-10-14 20:23:00 +07:00
|
|
|
encoding: TOTP_ENCODING,
|
|
|
|
token: token,
|
|
|
|
window: WINDOW
|
|
|
|
} as any);
|
2017-05-21 00:16:57 +07:00
|
|
|
|
2017-10-14 20:23:00 +07:00
|
|
|
if (isValid)
|
|
|
|
return BluebirdPromise.resolve();
|
|
|
|
else
|
|
|
|
return BluebirdPromise.reject(new Error("Wrong TOTP token."));
|
2017-05-21 00:16:57 +07:00
|
|
|
}
|
|
|
|
}
|