/
utils.go
232 lines (190 loc) · 5.87 KB
/
utils.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package slack
import (
"encoding/json"
"errors"
"fmt"
"html"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/slack-go/slack"
)
func (s *Slack) getSlackToken() (string, error) {
type findTeamResponseFull struct {
SSO bool `json:"sso"`
TeamID string `json:"team_id"`
slack.SlackResponse
}
type loginResponseFull struct {
Token string `json:"token"`
slack.SlackResponse
}
resp, err := http.PostForm("https://slack.com/api/auth.findTeam", url.Values{"domain": {s.credentials.Team}})
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var findTeamResponse findTeamResponseFull
err = json.Unmarshal(body, &findTeamResponse)
if err != nil {
return "", err
}
if findTeamResponse.SSO {
return "", errors.New("SSO teams not yet supported")
}
resp, err = http.PostForm("https://slack.com/api/auth.signin",
url.Values{"team": {findTeamResponse.TeamID}, "email": {s.credentials.Login}, "password": {s.credentials.Pass}})
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var loginResponse loginResponseFull
err = json.Unmarshal(body, &loginResponse)
if err != nil {
return "", err
}
if !loginResponse.Ok {
return "", errors.New(loginResponse.Error)
}
return loginResponse.Token, nil
}
func isValidNick(s string) bool {
/* IRC RFC ([0] - see below) mentions a limit of 9 chars for
* IRC nicks, but modern clients allow more than that. Let's
* use a "sane" big value, the triple of the spec.
*/
if len(s) < 1 || len(s) > 27 {
return false
}
/* According to IRC RFC [0], the allowed chars to have as nick
* are: ( letter / special-'-' ).*( letter / digit / special ),
* where:
* letter = [a-z / A-Z]; digit = [0-9];
* special = [';', '[', '\', ']', '^', '_', '`', '{', '|', '}', '-']
*
* ASCII codes (decimal) for the allowed chars:
* letter = [65-90,97-122]; digit = [48-57]
* special = [59, 91-96, 123-125, 45]
* [0] RFC 2812 (tools.ietf.org/html/rfc2812)
*/
if s[0] != 59 && (s[0] < 65 || s[0] > 125) {
return false
}
for i := 1; i < len(s); i++ {
if s[i] != 45 && s[i] != 59 && (s[i] < 65 || s[i] > 125) {
if s[i] < 48 || s[i] > 57 {
return false
}
}
}
return true
}
func formatTS(unixts string) string {
var targetts, targetus int64
fmt.Sscanf(unixts, "%d.%d", &targetts, &targetus)
ts := time.Unix(targetts, targetus*1000)
if ts.YearDay() != time.Now().YearDay() {
return ts.Format("2.1. 15:04:05")
}
return ts.Format("15:04:05")
}
// @see https://api.slack.com/docs/message-formatting#linking_to_channels_and_users
func (s *Slack) replaceMention(text string) string {
results := regexp.MustCompile(`<@([a-zA-z0-9]+)>`).FindAllStringSubmatch(text, -1)
for _, r := range results {
text = strings.ReplaceAll(text, "<@"+r[1]+">", "@"+s.userName(r[1]))
}
return text
}
// @see https://api.slack.com/docs/message-formatting#linking_to_channels_and_users
func replaceChannel(text string) string {
results := regexp.MustCompile(`<#[a-zA-Z0-9]+\|(.+?)>`).FindAllStringSubmatch(text, -1)
for _, r := range results {
text = strings.ReplaceAll(text, r[0], "#"+r[1])
}
return text
}
// @see https://api.slack.com/docs/message-formatting#variables
func replaceVariable(text string) string {
results := regexp.MustCompile(`<!((?:subteam\^)?[a-zA-Z0-9]+)(?:\|@?(.+?))?>`).FindAllStringSubmatch(text, -1)
for _, r := range results {
if r[2] != "" {
text = strings.ReplaceAll(text, r[0], "@"+r[2])
} else {
text = strings.ReplaceAll(text, r[0], "@"+r[1])
}
}
return text
}
// @see https://api.slack.com/docs/message-formatting#linking_to_urls
func replaceURL(text string) string {
results := regexp.MustCompile(`<(.*?)(\|.*?)?>`).FindAllStringSubmatch(text, -1)
for _, r := range results {
text = strings.ReplaceAll(text, r[0], r[1])
}
return text
}
func (s *Slack) cleanupMessage(msg string) string {
msg = s.replaceMention(msg)
msg = replaceVariable(msg)
msg = replaceChannel(msg)
msg = replaceURL(msg)
msg = html.UnescapeString(msg)
return msg
}
// passwordToTokenAndCookie parses the password specified by the user into a
// Slack token and optionally a cookie Auth cookies can be specified by
// appending a "|" symbol and the base64-encoded auth cookie to the Slack token.
// taken from https://github.com/insomniacslk/irc-slack/blob/master/pkg/ircslack/irc_server.go
func passwordToTokenAndCookie(p string) (string, string, error) {
parts := strings.Split(p, "|")
switch len(parts) {
case 1:
// XXX should check that the token starts with xoxp- ?
return parts[0], "", nil
case 2:
if !strings.HasPrefix(parts[0], "xoxc-") {
return "", "", errors.New("auth cookie is set, but token does not start with xoxc-")
}
if parts[1] == "" {
return "", "", errors.New("auth cookie is empty")
}
if !strings.HasPrefix(parts[1], "d=") || !strings.HasSuffix(parts[1], ";") {
return "", "", errors.New("auth cookie must have the format 'd=XXX;'")
}
return parts[0], parts[1], nil
default:
return "", "", fmt.Errorf("failed to parse password into token and cookie, got %d components, want 1 or 2", len(parts))
}
}
// custom HTTP client used to set the auth cookie if requested, and only over
// TLS.
// taken from https://github.com/insomniacslk/irc-slack/blob/master/pkg/ircslack/irc_server.go
type httpClient struct {
c http.Client
cookie string
}
// taken from https://github.com/insomniacslk/irc-slack/blob/master/pkg/ircslack/irc_server.go
func (hc httpClient) Do(req *http.Request) (*http.Response, error) {
if hc.cookie != "" {
logrus.Debug("Setting auth cookie")
if strings.ToLower(req.URL.Scheme) == "https" {
req.Header.Add("Cookie", hc.cookie)
} else {
logrus.Warning("Cookie is set but connection is not HTTPS, skipping")
}
}
return hc.c.Do(req)
}