File: mcaptcha.go

package info (click to toggle)
golang-codeberg-gusted-mcaptcha 0.0~git20220723.4f3072e-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 96 kB
  • sloc: makefile: 2
file content (81 lines) | stat: -rw-r--r-- 2,070 bytes parent folder | download
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
71
72
73
74
75
76
77
78
79
80
81
package mcaptcha

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// VerifyOpts holds all the information that is need to make a verification request.
type VerifyOpts struct {
	Secret      string `json:"secret"`
	Sitekey     string `json:"key"` //nolint:tagliatelle // `Sitekey` is the correct naming, but API expects `key`.
	Token       string `json:"token"`
	InstanceURL string `json:"-"`
}

// GetOpts returns a io.Reader that contains a JSON representation
// of the options.
func (opts *VerifyOpts) GetOpts() (io.Reader, error) {
	if opts.Secret == "" {
		return nil, ErrMissingSecret
	}
	if opts.Sitekey == "" {
		return nil, ErrMissingSitekey
	}
	if opts.Token == "" {
		return nil, ErrMissingToken
	}

	body, err := json.Marshal(opts)
	if err != nil {
		return nil, fmt.Errorf("couldn't marshal options: %w", err)
	}

	return bytes.NewReader(body), nil
}

type verifyResponse struct {
	Valid bool `json:"valid"`
}

// Verify takes in a context and options to make a verification request.
// It will verify if the given token is validated on the given mCaptcha instance.
func Verify(ctx context.Context, opts *VerifyOpts) (bool, error) {
	body, err := opts.GetOpts()
	if err != nil {
		return false, err
	}

	url := strings.TrimSuffix(opts.InstanceURL, "/")

	req, err := http.NewRequestWithContext(ctx, "POST", url+"/api/v1/pow/siteverify", body)
	if err != nil {
		return false, fmt.Errorf("couldn't create a new request: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return false, fmt.Errorf("couldn't execute request: %w", err)
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		content, _ := io.ReadAll(res.Body)
		return false, fmt.Errorf("mCaptcha didn't return 200 OK [content=%q]", string(content))
	}

	var responseStruct verifyResponse
	err = json.NewDecoder(res.Body).Decode(&responseStruct)
	if err != nil {
		return false, fmt.Errorf("couldn't decode response from mCaptcha: %w", err)
	}

	return responseStruct.Valid, nil
}