49 lines
		
	
	
		
			848 B
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			49 lines
		
	
	
		
			848 B
		
	
	
	
		
			Go
		
	
	
	
	
	
package otp_test
 | 
						|
 | 
						|
import (
 | 
						|
	"fmt"
 | 
						|
 | 
						|
	"dev.justinjudd.org/justin/otp"
 | 
						|
)
 | 
						|
 | 
						|
type MapKey struct {
 | 
						|
	Issuer, Label string
 | 
						|
}
 | 
						|
 | 
						|
var keysMap map[MapKey]string
 | 
						|
 | 
						|
func CreateKey(issuer, username string) error {
 | 
						|
	mapKey := MapKey{issuer, username}
 | 
						|
	_, ok := keysMap[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)
 | 
						|
 | 
						|
	keysMap[mapKey] = k.URL()
 | 
						|
 | 
						|
	return nil
 | 
						|
}
 | 
						|
 | 
						|
func CheckCode(issuer, username, code string) bool {
 | 
						|
	mapKey := MapKey{issuer, username}
 | 
						|
	keyURL, ok := keysMap[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")
 | 
						|
 | 
						|
}
 |