package totpmdl import ( "bytes" "image/png" "time" "corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl" "github.com/pquerna/otp" "github.com/pquerna/otp/totp" ) type TOTPGenerate struct { // Name of the issuing Organization/Company/application. Issuer string // Name of the User's Account (eg, email address) AccountName string // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds. Period uint // Size in size of the generated Secret. Defaults to 20 bytes. SecretSize uint // Secret to store. Defaults to a randomly generated secret of SecretSize. You should generally leave this empty. // Secret []byte // Digits to request. Defaults to 6. Digits otp.Digits // Algorithm to use for HMAC. Defaults to SHA1. Algorithm otp.Algorithm // Reader to use for generating TOTP Key. // Rand io.Reader } type TOTPValidate struct { //OTP Generated by authenticator application Token string //secret key Secret string // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds. Period uint // Periods before or after the current time to allow. Value of 1 allows up to Period // of either side of the specified time. Defaults to 0 allowed skews. Values greater // than 1 are likely sketchy. Skew uint // Digits to request. Defaults to 6. Digits otp.Digits // Algorithm to use for HMAC. Defaults to SHA1. Algorithm otp.Algorithm } //generate QR func (t *TOTPGenerate) NewQR(key *otp.Key) ([]byte, error) { var buf bytes.Buffer img, errImage := key.Image(500, 500) //set dimenions of qr image if errImage != nil { return nil, errImage } imageCreateErr := png.Encode(&buf, img) //encode the Image.Image to buffer if imageCreateErr != nil { return nil, imageCreateErr } return buf.Bytes(), nil //return image in bytes() format } //create totp secret key func (t *TOTPGenerate) CreateSecretKey() (*otp.Key, error) { key, keyGenErr := totp.Generate(totp.GenerateOpts{ Issuer: t.Issuer, AccountName: t.AccountName, SecretSize: t.SecretSize, Period: t.Period, Digits: t.Digits, Algorithm: t.Algorithm, }) if keyGenErr != nil { return nil, keyGenErr } return key, nil } //validate totp code func (v *TOTPValidate) ValidateTOTP() (bool, error) { isValid, errValidation := totp.ValidateCustom( // you can also use the validate method but it will not allow you customizations v.Token, v.Secret, time.Now().UTC(), totp.ValidateOpts{ Period: v.Period, Skew: v.Skew, Digits: v.Digits, Algorithm: v.Algorithm, }, ) if errValidation != nil { loggermdl.LogError("Error in totp validation:", errValidation.Error()) return isValid, errValidation } return isValid, nil }