-
Notifications
You must be signed in to change notification settings - Fork 207
/
countrychecker.go
100 lines (73 loc) · 2.15 KB
/
countrychecker.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package utils
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
// CheckCountry allows to check which country the app is running from
func CheckCountry(countriesToAvoid []string, strictCountryCheck bool) bool {
type IPInfo struct {
Country string `json:"country"`
IP string `json:"ip"`
}
ipInfo := IPInfo{}
const ipCheckerURI = "https://api.myip.com/"
const requestTimeout = 3 * time.Second
retries := 0
for ipInfo.IP == "" && retries <= 3 {
log.Printf("Checking IP address, attempt #%d", retries)
time.Sleep(1 * time.Second)
retries++
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ipCheckerURI, nil)
if err != nil {
continue
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Println("Can't check users country. Please manually check that VPN is enabled or that you have non Ukrainian IP address.")
continue
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("Can't close connection to: %s", ipCheckerURI)
return
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Can't check users country. Please manually check that VPN is enabled or that you have non Ukrainian IP address.")
continue
}
err = json.Unmarshal(body, &ipInfo)
if err != nil {
log.Println("Can't check users country. Please manually check that VPN is enabled or that you have non Ukrainian IP address.")
continue
}
}
if ipInfo.Country == "" {
if strictCountryCheck {
log.Println("Strict country check mode is enabled, exiting")
return false
}
return true
}
for _, country := range countriesToAvoid {
if ipInfo.Country == strings.TrimSpace(country) {
log.Printf("Current country: %s. You might need to enable VPN.", ipInfo.Country)
OpenBrowser("https://arriven.github.io/db1000n/vpn/")
if strictCountryCheck {
log.Println("Strict country check mode is enabled, exiting")
return false
}
return true
}
}
log.Printf("Current country: %s (%s)", ipInfo.Country, ipInfo.IP)
return true
}