Created
February 5, 2024 21:34
-
-
Save rseyf/f3687a50fad7f2515e1e2fa995be34d6 to your computer and use it in GitHub Desktop.
Golang TOTP 2FA authentication
This file contains 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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"time" | |
"github.com/mdp/qrterminal" | |
"github.com/skip2/go-qrcode" | |
"github.com/xlzd/gotp" | |
) | |
func main() { | |
randomSecret := gotp.RandomSecret(16) | |
fmt.Println("Random secret:", randomSecret) | |
generateTOTPWithSecret(randomSecret) | |
verifyOTP(randomSecret) | |
} | |
func generateTOTPWithSecret(randomSecret string) { | |
uri := gotp.NewDefaultTOTP(randomSecret).ProvisioningUri("user@email.com", "myApp") | |
fmt.Println("Secret Key URI:", uri) | |
qrcode.WriteFile(uri, qrcode.Medium, 256, "qr.png") | |
// Generate and display QR code in the terminal | |
qrterminal.GenerateWithConfig(uri, qrterminal.Config{ | |
Level: qrterminal.L, | |
Writer: os.Stdout, | |
BlackChar: qrterminal.BLACK, | |
WhiteChar: qrterminal.WHITE, | |
}) | |
fmt.Println("\nScan the QR code with your authenticator app") | |
} | |
func verifyOTP(randomSecret string) { | |
totp := gotp.NewDefaultTOTP(randomSecret) | |
// Wait for user input of the OTP | |
fmt.Print("Enter the OTP from your authenticator app: ") | |
scanner := bufio.NewScanner(os.Stdin) | |
scanner.Scan() | |
userInput := scanner.Text() | |
// Validate the provided OTP | |
if totp.Verify(userInput, time.Now().Unix()) { | |
fmt.Println("Authentication successful! Access granted.") | |
} else { | |
fmt.Println("Authentication failed! Invalid OTP.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment