49 lines
824 B
Go
49 lines
824 B
Go
|
package otp_test
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
|
||
|
"dev.justinjudd.org/justin/otp"
|
||
|
)
|
||
|
|
||
|
type Key struct {
|
||
|
Issuer, Label string
|
||
|
}
|
||
|
|
||
|
var keys map[Key]string
|
||
|
|
||
|
func CreateKey(issuer, username string) error {
|
||
|
mapKey := Key{issuer, username}
|
||
|
_, ok := keys[mapKey]
|
||
|
if ok {
|
||
|
return fmt.Errorf("Key already exists for Issuer:%s, Label:%s", issuer, username)
|
||
|
}
|
||
|
opts := otp.NewHOTPKeyOptions()
|
||
|
opts.Issuer = issuer
|
||
|
opts.Label = username
|
||
|
k := otp.NewHOTPKey(opts)
|
||
|
|
||
|
keys[mapKey] = k.URL()
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func CheckCode(issuer, username, code string) bool {
|
||
|
mapKey := Key{issuer, username}
|
||
|
keyURL, ok := keys[mapKey]
|
||
|
if !ok {
|
||
|
return false
|
||
|
}
|
||
|
k, err := otp.FromURL(keyURL)
|
||
|
if err != nil {
|
||
|
return false
|
||
|
}
|
||
|
return k.Verify(code)
|
||
|
}
|
||
|
|
||
|
func Example_hOTP() {
|
||
|
CreateKey("example.com", "user1")
|
||
|
CheckCode("example.com", "user1", "451556")
|
||
|
|
||
|
}
|