Junior — Middle
How to implement a two-step user verification for increased system security?
sobes.tech AI
Answer from AI
Two-factor authentication (2FA) enhances security by requiring two different methods of verifying the user's identity.
A typical implementation of 2FA includes:
- Password verification (something the user knows).
- Verification of the second factor — for example, a one-time code from SMS, an authenticator app (Google Authenticator), or a hardware token.
In Go, 2FA can be implemented as follows:
- After successful password verification, generate and send a one-time code to the user.
- Temporarily store the code (e.g., in a database or cache) with a time limit.
- Ask the user to enter the code and verify it.
Example of generating a TOTP code using the github.com/pquerna/otp library:
import (
"github.com/pquerna/otp/totp"
"time"
)
// Verify TOTP code
func verifyCode(secret, code string) bool {
return totp.Validate(code, secret)
}
// Generate a secret key for the user
func generateSecret() (string, error) {
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "MyApp",
AccountName: "user@example.com",
})
if err != nil {
return "", err
}
return key.Secret(), nil
}
Thus, after password verification, the user enters the code from the app, which is verified by the server.