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