Created
July 14, 2024 18:27
-
-
Save wuriyanto48/548b8e7e997ee3b5e25457cb7045294c to your computer and use it in GitHub Desktop.
Golang Authenticator Time Based (you can use it with Authenticator App. Eg: Google Authenticator)
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 ( | |
"encoding/base64" | |
"fmt" | |
"time" | |
"github.com/skip2/go-qrcode" | |
"github.com/xlzd/gotp" | |
) | |
const STATIC_SECRET = "X3BZLQW56LDBDZTW" | |
func main() { | |
data, secret, err := GenerateTOTPWithSecret("GolangCool", "[email protected]") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(secret) | |
fmt.Println(data) | |
//VerifyOTP(secret) | |
} | |
func ToDataURI(base64EncodedQr string) string { | |
return fmt.Sprintf("data:image/png;base64,%s", base64EncodedQr) | |
} | |
func GenerateTOTPWithSecret(applicationName, userID string) (string, string, error) { | |
secret := gotp.RandomSecret(10) | |
uri := gotp.NewDefaultTOTP(secret).ProvisioningUri(userID, applicationName) | |
fmt.Println("Secret Key URI:", uri) | |
png, err := qrcode.Encode(uri, qrcode.Medium, 256) | |
if err != nil { | |
return "", "", err | |
} | |
encoded := base64.StdEncoding.EncodeToString(png) | |
return ToDataURI(encoded), secret, nil | |
} | |
func VerifyOTP(secret string, otp string) { | |
totp := gotp.NewDefaultTOTP(secret) | |
if totp.Verify(otp, 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