2024-09-11 09:54:55 +02:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
2024-09-13 09:12:16 +02:00
|
|
|
"errors"
|
2024-09-11 09:54:55 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/altcha-org/altcha-lib-go"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
hmacKey string
|
|
|
|
maxNumber int64
|
|
|
|
algorithm altcha.Algorithm
|
|
|
|
salt string
|
2024-09-13 09:12:16 +02:00
|
|
|
expire time.Duration
|
2024-09-11 09:54:55 +02:00
|
|
|
checkExpire bool
|
|
|
|
}
|
|
|
|
|
2024-09-13 09:12:16 +02:00
|
|
|
func New(hmacKey string, maxNumber int64, algorithm string, salt string, expire time.Duration, checkExpire bool) (*Client, error) {
|
2024-09-11 10:18:18 +02:00
|
|
|
if len(hmacKey) == 0 {
|
2024-09-13 09:12:16 +02:00
|
|
|
return &Client{}, errors.New("HMAC key not found")
|
2024-09-11 10:18:18 +02:00
|
|
|
}
|
2024-09-11 09:54:55 +02:00
|
|
|
return &Client {
|
|
|
|
hmacKey: hmacKey,
|
|
|
|
maxNumber: maxNumber,
|
|
|
|
algorithm: altcha.Algorithm(algorithm),
|
|
|
|
salt: salt,
|
|
|
|
expire: expire,
|
|
|
|
checkExpire: checkExpire,
|
2024-09-13 09:12:16 +02:00
|
|
|
}, nil
|
2024-09-11 09:54:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Generate() (altcha.Challenge, error) {
|
2024-09-13 09:12:16 +02:00
|
|
|
expiration := time.Now().Add(c.expire)
|
2024-09-11 09:54:55 +02:00
|
|
|
|
|
|
|
options := altcha.ChallengeOptions{
|
|
|
|
HMACKey: c.hmacKey,
|
|
|
|
MaxNumber: c.maxNumber,
|
|
|
|
Algorithm: c.algorithm,
|
|
|
|
Expires: &expiration,
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(c.salt) > 0 {
|
|
|
|
options.Salt = c.salt
|
|
|
|
}
|
|
|
|
|
|
|
|
return altcha.CreateChallenge(options)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Solve(challenge string) (*altcha.Solution, error) {
|
|
|
|
return altcha.SolveChallenge(challenge, c.salt, c.algorithm, int(c.maxNumber), 0, make(<-chan struct{}))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) VerifySolution(payload interface{}) (bool, error) {
|
|
|
|
return altcha.VerifySolution(payload, c.hmacKey, c.checkExpire)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) VerifyServerSignature(payload interface{}) (bool, altcha.ServerSignatureVerificationData, error) {
|
|
|
|
return altcha.VerifyServerSignature(payload, c.hmacKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) VerifyFieldsHash(formData map[string][]string, fields []string, fieldsHash string) (bool, error) {
|
|
|
|
return altcha.VerifyFieldsHash(formData, fields, fieldsHash, c.algorithm)
|
|
|
|
}
|