Skip to content

Instantly share code, notes, and snippets.

@robert-kratz
Last active December 6, 2021 11:57
Show Gist options
  • Save robert-kratz/0b9cd0de71050643ddc696b861e55e0b to your computer and use it in GitHub Desktop.
Save robert-kratz/0b9cd0de71050643ddc696b861e55e0b to your computer and use it in GitHub Desktop.
NodeJS Google Authenticator Module using Axios
const axios = require('axios').default;
const secret = 'SECRET';
const appname = 'Your-App';
/**
* Google Authenticator API: https://authenticatorapi.com/
*
* App Store: https://apps.apple.com/de/app/google-authenticator/id388497605
* Play Store: https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=de&gl=US
*/
/**
* Register the current user with google authenticator
* @description Returns you, if resolved a url with the pairing qr-code
* @param {String} username
* @returns Promise<String>
*/
const register = (username) => {
return new Promise((resolve, rejects) => {
axios.get(registerURL(username)).then(response => {
if(response.status == 200) {
try {
var url = response.data.split('><')[1].split("'")[1];
return resolve(url);
} catch (error) {
return rejects(error);
}
}
return rejects();
});
});
}
/**
* Validates the useres authenticator app with the user account
* @param {String} code
* @returns Promise<>
*/
const validate = (code) => {
return new Promise((resolve, rejects) => {
axios.get(validateURL(code)).then(response => {
if(response.status == 200) {
if(response.data == 'True') return resolve()
}
return rejects();
});
})
}
const registerURL = (username) => {
return `https://www.authenticatorApi.com/pair.aspx?AppName=${appname}&AppInfo=${username}&SecretCode=${secret}`;
}
const validateURL = (code) => {
return `https://www.authenticatorApi.com/Validate.aspx?Pin=${code}&SecretCode=${secret}`;
}
module.exports = {
register: register,
validate: validate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment