2021-01-05 09:33:45 +01:00
|
|
|
package domain
|
|
|
|
|
|
|
|
import (
|
2021-01-15 09:32:59 +01:00
|
|
|
"github.com/pquerna/otp"
|
|
|
|
"github.com/pquerna/otp/totp"
|
2023-08-02 18:57:53 +02:00
|
|
|
|
2022-04-27 01:01:45 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/crypto"
|
2023-12-08 16:30:55 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/zerrors"
|
2021-01-05 09:33:45 +01:00
|
|
|
)
|
|
|
|
|
2023-06-22 12:06:32 +02:00
|
|
|
type TOTP struct {
|
2023-06-20 12:36:21 +02:00
|
|
|
*ObjectDetails
|
|
|
|
|
|
|
|
Secret string
|
|
|
|
URI string
|
|
|
|
}
|
|
|
|
|
2024-05-14 09:20:31 +02:00
|
|
|
func NewTOTPKey(issuer, accountName string) (*otp.Key, error) {
|
2021-01-15 09:32:59 +01:00
|
|
|
key, err := totp.Generate(totp.GenerateOpts{Issuer: issuer, AccountName: accountName})
|
|
|
|
if err != nil {
|
2024-05-14 09:20:31 +02:00
|
|
|
return nil, zerrors.ThrowInternal(err, "TOTP-ieY3o", "Errors.Internal")
|
2021-01-15 09:32:59 +01:00
|
|
|
}
|
2024-05-14 09:20:31 +02:00
|
|
|
return key, nil
|
2021-01-15 09:32:59 +01:00
|
|
|
}
|
2021-01-07 16:06:45 +01:00
|
|
|
|
2023-08-02 18:57:53 +02:00
|
|
|
func VerifyTOTP(code string, secret *crypto.CryptoValue, cryptoAlg crypto.EncryptionAlgorithm) error {
|
2021-01-15 09:32:59 +01:00
|
|
|
decrypt, err := crypto.DecryptString(secret, cryptoAlg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-07 16:06:45 +01:00
|
|
|
|
2021-01-15 09:32:59 +01:00
|
|
|
valid := totp.Validate(code, decrypt)
|
|
|
|
if !valid {
|
2023-12-08 16:30:55 +02:00
|
|
|
return zerrors.ThrowInvalidArgument(nil, "EVENT-8isk2", "Errors.User.MFA.OTP.InvalidCode")
|
2021-01-15 09:32:59 +01:00
|
|
|
}
|
|
|
|
return nil
|
2021-01-07 16:06:45 +01:00
|
|
|
}
|