-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqrcode.go
70 lines (54 loc) · 2.01 KB
/
qrcode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package isugata
import (
"fmt"
"image/png"
"net/http"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
)
// CorrectionLevel is the correction level of QR code
type correctionLevel string
const (
// CorrectionLevelL is correction level L (approx 7%)
CorrectionLevelL correctionLevel = "L"
// CorrectionLevelM is correction level M (approx 15%)
CorrectionLevelM correctionLevel = "M"
// CorrectionLevelQ is correction level Q (approx 25%)
CorrectionLevelQ correctionLevel = "Q"
// CorrectionLevelH is correction level H (approx 30%)
CorrectionLevelH correctionLevel = "H"
)
// WithQRCodeEqual validates if the QR code equals to the expected
func WithQRCodeEqual(size int, corrLevel correctionLevel, content string, decryptFunc func(string) (string, error)) ValidateOpt {
return func(res *http.Response) error {
img, err := png.Decode(res.Body)
if err != nil {
return fmt.Errorf("%w: %w", ErrUndecodableBody, err)
}
rect := img.Bounds()
if rect.Dx() != size || rect.Dy() != size {
return fmt.Errorf("%w: invalid QR code size: expected: %d, actual: %d", ErrInvalidBody, size, rect.Dx())
}
bmp, err := gozxing.NewBinaryBitmapFromImage(img)
if err != nil {
return fmt.Errorf("%w: %w", ErrUndecodableBody, err)
}
qrReader := qrcode.NewQRCodeReader()
result, err := qrReader.Decode(bmp, nil)
if err != nil {
return fmt.Errorf("%w: %w", ErrUndecodableBody, err)
}
actualCorrectionLevel, _ := (result.GetResultMetadata()[gozxing.ResultMetadataType_ERROR_CORRECTION_LEVEL]).(string)
if actualCorrectionLevel != string(corrLevel) {
return fmt.Errorf("%w: invalid QR code correction level: expected: %s, actual: %s", ErrInvalidBody, corrLevel, actualCorrectionLevel)
}
decryptedContent, err := decryptFunc(result.String())
if err != nil {
return fmt.Errorf("%w: %w", ErrInvalidBody, err)
}
if decryptedContent != content {
return fmt.Errorf("%w: invalid QR code content: expected: %s, actual: %s", ErrInvalidBody, content, decryptedContent)
}
return nil
}
}