aboutsummaryrefslogtreecommitdiff
path: root/backend/internal/ibd/check_ibd_username.go
blob: b0261510728a731c279ed9bfa7ae02e718897e03 (plain) (blame)
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
package ibd

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

const (
	checkUsernameUrl = "https://sso.accounts.dowjones.com/getuser"
)

func (c *Client) CheckIBDUsername(ctx context.Context, username string) (bool, error) {
	cfg, err := c.getLoginPage(ctx)
	if err != nil {
		return false, err
	}

	return c.checkIBDUsername(ctx, cfg, username)
}

func (c *Client) checkIBDUsername(ctx context.Context, cfg *authConfig, username string) (bool, error) {
	body := map[string]string{
		"username": username,
		"csrf":     cfg.ExtraParams.Csrf,
	}
	bodyJson, err := json.Marshal(body)
	if err != nil {
		return false, err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, checkUsernameUrl, bytes.NewReader(bodyJson))
	if err != nil {
		return false, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-REMOTE-USER", username)
	req.Header.Set("X-REQUEST-EDITIONID", "IBD-EN_US")
	req.Header.Set("X-REQUEST-SCHEME", "https")

	resp, err := c.Do(req, withExpectedStatuses(http.StatusOK, http.StatusUnauthorized))
	if err != nil {
		return false, err
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	if resp.StatusCode == http.StatusUnauthorized {
		return false, nil
	} else if resp.StatusCode != http.StatusOK {
		contentBytes, err := io.ReadAll(resp.Body)
		if err != nil {
			return false, fmt.Errorf("failed to read response body: %w", err)
		}
		content := string(contentBytes)
		return false, fmt.Errorf(
			"unexpected status code %d: %s",
			resp.StatusCode,
			content,
		)
	}
	return true, nil
}