aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/fortee/fortee.go
blob: cfe4effe67c468e75fbf3f64eeabcc682c45cf7d (plain)
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
package fortee

import (
	"context"
	"errors"
	"net/http"
)

const (
	Endpoint = "https://fortee.jp"
)

var (
	ErrLoginFailed  = errors.New("fortee login failed")
	ErrUserNotFound = errors.New("fortee user not found")
)

func Login(ctx context.Context, username string, password string) (string, error) {
	client, err := NewClientWithResponses(Endpoint, WithRequestEditorFn(addAcceptHeader))
	if err != nil {
		return "", err
	}
	res, err := client.PostLoginWithFormdataBodyWithResponse(ctx, PostLoginFormdataRequestBody{
		Username: username,
		Password: password,
	})
	if err != nil {
		return "", err
	}
	if res.StatusCode() != http.StatusOK {
		return "", ErrLoginFailed
	}
	resOk := res.JSON200
	if !resOk.LoggedIn {
		return "", ErrLoginFailed
	}
	if resOk.User == nil {
		return "", ErrLoginFailed
	}
	return resOk.User.Username, nil
}

func GetUserAvatarURL(ctx context.Context, username string) (string, error) {
	client, err := NewClientWithResponses(Endpoint, WithRequestEditorFn(addAcceptHeader))
	if err != nil {
		return "", err
	}
	res, err := client.GetUserWithResponse(ctx, username)
	if err != nil {
		return "", err
	}
	if res.StatusCode() != http.StatusOK {
		return "", ErrUserNotFound
	}
	return res.JSON200.AvatarURL, nil
}

// fortee API denies requests without Accept header.
func addAcceptHeader(_ context.Context, req *http.Request) error {
	req.Header.Set("Accept", "application/json")
	return nil
}