2016-01-10 23:03:04 +00:00
|
|
|
package otp_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"dev.justinjudd.org/justin/otp"
|
|
|
|
)
|
|
|
|
|
2016-01-11 00:56:15 +00:00
|
|
|
type MapKey struct {
|
2016-01-10 23:03:04 +00:00
|
|
|
Issuer, Label string
|
|
|
|
}
|
|
|
|
|
2016-01-11 00:56:15 +00:00
|
|
|
var keysMap map[MapKey]string
|
2016-01-10 23:03:04 +00:00
|
|
|
|
|
|
|
func CreateKey(issuer, username string) error {
|
2016-01-11 00:56:15 +00:00
|
|
|
mapKey := MapKey{issuer, username}
|
|
|
|
_, ok := keysMap[mapKey]
|
2016-01-10 23:03:04 +00:00
|
|
|
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)
|
|
|
|
|
2016-01-11 00:56:15 +00:00
|
|
|
keysMap[mapKey] = k.URL()
|
2016-01-10 23:03:04 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func CheckCode(issuer, username, code string) bool {
|
2016-01-11 00:56:15 +00:00
|
|
|
mapKey := MapKey{issuer, username}
|
|
|
|
keyURL, ok := keysMap[mapKey]
|
2016-01-10 23:03:04 +00:00
|
|
|
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")
|
|
|
|
|
|
|
|
}
|