Created
August 23, 2022 02:32
-
-
Save omar2205/d467b3379fcda938b642e7d71b64a167 to your computer and use it in GitHub Desktop.
Deno creating an TOTP token (two factor authentication)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { generateOTPToken, generateSecret, generateQRCode } from './utils.ts' | |
// registering a new user | |
if (username) { | |
const u: User = { | |
username, | |
} | |
const user = await createUser(u) // create your user and create an auth secret | |
const authToken = generateOTPToken(generateSecret(user.secret), u.email) | |
const qr = await generateQRCode(authToken.toString()) | |
// qr is the image to scan in auth apps | |
// In deno fresh use this: | |
// <img src={props.data.qr} alt="auth qr code" /> | |
return await ctx.render({ | |
qr | |
}) | |
} | |
// validating users | |
const authToken = generateOTPToken(generateSecret(user.secret), u.email) | |
const token = authToken.generate() | |
let delta = totp.validate({ | |
token, | |
window: 1 | |
}) | |
// delta: null if invalid, 0 if correct, and -amount if token has changed (a minute passed) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as OTPAuth from 'https://deno.land/x/[email protected]/dist/otpauth.esm.js' | |
import { qrcode } from 'https://deno.land/x/[email protected]/mod.ts' | |
const opts = { | |
issuer: 'MyWebsite', | |
algorithm: 'SHA1', | |
digits: 6, | |
period: 30, | |
} | |
export function generateOTPToken (secret: string|OTPAuth.Secret, label: string) { | |
return new OTPAuth.TOTP({ | |
...opts, | |
label, | |
secret | |
}) | |
} | |
export function generateSecret (secret: string) { | |
return OTPAuth.Secret.fromUTF8(secret) | |
} | |
export default function generateQRCode(str: string) { | |
return qrcode(str) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment