forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.go
93 lines (80 loc) 路 1.96 KB
/
authenticate.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
package maintenance
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/url"
"github.com/kataras/iris/core/maintenance/client"
"github.com/kataras/iris/core/maintenance/encoding"
"github.com/kataras/survey"
)
// question describes the question which will be used
// for the survey in order to authenticate the local iris.
type question struct {
Message string `json:"message"`
}
func hasInternetConnection() (bool, bool) {
r, err := client.PostForm("", nil)
if err != nil {
// no internet connection
return false, false
}
defer r.Body.Close()
return true, r.StatusCode == 204
}
func ask() bool {
qs := fetchQuestions()
var lastResponseUnsed string
for _, q := range qs {
survey.AskOne(&survey.Input{Message: q.Message}, &lastResponseUnsed, validate(q))
}
return lastResponseUnsed != ""
}
// fetchQuestions returns a list of questions
// fetched by the authority server.
func fetchQuestions() (qs []question) {
r, err := client.PostForm("/survey/ask", nil)
if err != nil {
return
}
defer r.Body.Close()
if err := encoding.UnmarshalBody(r.Body, &qs, json.Unmarshal); err != nil {
return
}
return
}
func validate(q question) survey.Validator {
return func(answer interface{}) error {
if err := survey.Required(answer); err != nil {
return err
}
ans, ok := answer.(string)
if !ok {
return fmt.Errorf("bug: expected string but got %v", answer)
}
data := url.Values{
"q": []string{q.Message},
"ans": []string{ans},
"current_version": []string{Version},
}
r, err := client.PostForm("/survey/submit", data)
if err != nil {
// error from server-side, allow.
return nil
}
defer r.Body.Close()
if r.StatusCode == 200 {
// read the whole thing, it has nothing.
io.Copy(ioutil.Discard, r.Body)
return nil // pass, no any errors.
}
// now, if invalid;
got, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil
}
errMsg := string(got)
return fmt.Errorf(errMsg)
}
}