-
Notifications
You must be signed in to change notification settings - Fork 0
/
logout.go
80 lines (65 loc) · 1.7 KB
/
logout.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
package action
import (
"context"
"fmt"
"io"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
"github.com/wolftotem4/go-dope-ben-don/internal/client"
"github.com/wolftotem4/go-dope-ben-don/internal/parser"
)
type LogoutAction struct {
Client client.Client
}
func (action *LogoutAction) PerformLogout(ctx context.Context, interfaceValue int) error {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
logoutUrl := fmt.Sprintf("/do/?wicket:interface=:%d:logout::ILinkListener", interfaceValue)
res, err := action.Client.Call(ctx, logoutUrl, client.Webpage)
if err != nil {
return errors.WithStack(err)
}
if !strings.HasPrefix(res.Request.URL.EscapedPath(), "/do/login") {
body, err := io.ReadAll(res.Body)
if err != nil {
return errors.WithStack(err)
}
defer res.Body.Close()
matched, err := regexp.Match(`(?i)Page Expired|網頁已過期`, body)
if err != nil {
return errors.WithStack(err)
}
if matched {
return ErrPageExpired
} else {
return errors.New("failed to logout")
}
}
return nil
}
func (action *LogoutAction) ForceLogout(ctx context.Context, interfaceValue int) error {
for retry := 1; retry >= 0; retry-- {
err := action.PerformLogout(ctx, interfaceValue)
if err == nil {
break
} else if retry == 0 || err != ErrPageExpired {
return err
}
// refresh homepage in order to renew expired Logout page
res, err := action.Client.Call(ctx, "/do/", client.Webpage)
if err != nil {
return errors.WithStack(err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return errors.WithStack(err)
}
interfaceValue, err = parser.ExtractInterface(body)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}