Debian Codegraph @

internal/login/login.go

raw symbols SCIP
1 package login
2
3 import (
4 "crypto/tls"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/sirupsen/logrus"
14 )
15
16 const (
17 statusPath = "/status.php"
18 minimumMajorVersion = 16
19
20 loginPath = "/index.php/login/v2"
21
22 pollInterval = time.Second
23 contentType = "application/x-www-form-urlencoded"
24 )
25
26 type loginInfo struct {
27 LoginURL string `json:"login"`
28 PollInfo pollInfo `json:"poll"`
29 }
30
31 type pollInfo struct {
32 Token string `json:"token"`
33 Endpoint string `json:"endpoint"`
34 }
35
36 type passwordInfo struct {
37 Server string `json:"server"`
38 LoginName string `json:"loginName"`
39 AppPassword string `json:"appPassword"`
40 }
41
42 // Login contains the login information gathered during the login session.
43 type Login struct {
44 Username string
45 Password string
46 }
47
48 // Client can be used to start an interactive login session with a Nextcloud server.
49 type Client struct {
50 log logrus.FieldLogger
51 userAgent string
52 serverURL string
53
54 client *http.Client
55 sleepFunc func()
56 }
57
58 // Init creates a new LoginClient. The session can then be started using StartInteractive.
59 func Init(log logrus.FieldLogger, userAgent, serverURL string, tlsSkipVerify bool) *Client {
60 return &Client{
61 log: log,
62 userAgent: userAgent,
63 serverURL: serverURL,
64
65 client: &http.Client{
66 Timeout: 30 * time.Second,
67 Transport: &http.Transport{
68 TLSClientConfig: &tls.Config{
69 InsecureSkipVerify: tlsSkipVerify,
70 },
71 },
72 },
73 sleepFunc: func() { time.Sleep(pollInterval) },
74 }
75 }
76
77 // StartInteractive starts an interactive login session for the Nextcloud server and user.
78 // The end-result of this is an app-password for the exporter which should be used instead of a user password.
79 func (c *Client) StartInteractive() error {
80 version, err := c.getMajorVersion()
81 if err != nil {
82 return fmt.Errorf("error getting version: %w", err)
83 }
84
85 if version < minimumMajorVersion {
86 return fmt.Errorf("Nextcloud version too old for login: %d Minimum: %d", version, minimumMajorVersion)
87 }
88
89 info, err := c.getLoginInfo()
90 if err != nil {
91 return fmt.Errorf("error getting login info: %w", err)
92 }
93 c.log.Infof("Please open this URL in a browser: %s", info.LoginURL)
94 c.log.Infoln("Waiting for login ... (Ctrl-C to abort)")
95
96 login, err := c.pollLogin(info.PollInfo)
97 if err != nil {
98 return fmt.Errorf("error during poll: %w", err)
99 }
100
101 c.log.Infof("Username: %s", login.Username)
102 c.log.Infof("Password: %s", login.Password)
103 return nil
104 }
105
106 func (c *Client) doRequest(method, url string, body io.Reader) (*http.Response, error) {
107 req, err := http.NewRequest(method, url, body)
108 if err != nil {
109 return nil, fmt.Errorf("can not create request: %w", err)
110 }
111 req.Header.Set("User-Agent", c.userAgent)
112
113 if body != nil {
114 req.Header.Set("Content-Type", contentType)
115 }
116
117 res, err := c.client.Do(req)
118 if err != nil {
119 return nil, fmt.Errorf("error connecting: %w", err)
120 }
121
122 return res, nil
123 }
124
125 func (c *Client) getMajorVersion() (int, error) {
126 statusURL := c.serverURL + statusPath
127 res, err := c.doRequest(http.MethodGet, statusURL, nil)
128 if err != nil {
129 return 0, fmt.Errorf("error connecting: %w", err)
130 }
131 defer res.Body.Close()
132
133 if res.StatusCode != http.StatusOK {
134 return 0, fmt.Errorf("non-ok status: %d", res.StatusCode)
135 }
136
137 var status struct {
138 Version string `json:"version"`
139 }
140 if err := json.NewDecoder(res.Body).Decode(&status); err != nil {
141 return 0, fmt.Errorf("error decoding status: %w", err)
142 }
143
144 tokens := strings.SplitN(status.Version, ".", 2)
145 version, err := strconv.Atoi(tokens[0])
146 if err != nil {
147 return 0, fmt.Errorf("can not parse %q as version: %w", status.Version, err)
148 }
149
150 return version, nil
151 }
152
153 func (c *Client) getLoginInfo() (loginInfo, error) {
154 loginURL := c.serverURL + loginPath
155 res, err := c.doRequest(http.MethodPost, loginURL, nil)
156 if err != nil {
157 return loginInfo{}, fmt.Errorf("error connecting: %w", err)
158 }
159 defer res.Body.Close()
160
161 if res.StatusCode != http.StatusOK {
162 return loginInfo{}, fmt.Errorf("non-ok status: %d", res.StatusCode)
163 }
164
165 var result loginInfo
166 if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
167 return loginInfo{}, fmt.Errorf("error decoding login info: %w", err)
168 }
169
170 return result, nil
171 }
172
173 func (c *Client) pollLogin(info pollInfo) (Login, error) {
174 body := fmt.Sprintf("token=%s", info.Token)
175 c.log.Debugf("poll endpoint: %s", info.Endpoint)
176
177 for {
178 c.sleepFunc()
179 reader := strings.NewReader(body)
180 res, err := c.doRequest(http.MethodPost, info.Endpoint, reader)
181 if err != nil {
182 continue
183 }
184 defer res.Body.Close()
185
186 if res.StatusCode != http.StatusOK {
187 c.log.Debugf("poll status: %d", res.StatusCode)
188 continue
189 }
190
191 var password passwordInfo
192 if err := json.NewDecoder(res.Body).Decode(&password); err != nil {
193 return Login{}, fmt.Errorf("error decoding password info: %w", err)
194 }
195
196 return Login{
197 Username: password.LoginName,
198 Password: password.AppPassword,
199 }, nil
200 }
201 }