forked from flexd/slackinviter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
244 lines (223 loc) · 5.85 KB
/
main.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
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"bytes"
"expvar"
"log"
"net"
"net/http"
"os"
"text/template"
"time"
"github.com/go-recaptcha/recaptcha"
"github.com/gorilla/handlers"
"github.com/kelseyhightower/envconfig"
"github.com/nlopes/slack"
"github.com/paulbellamy/ratecounter"
)
var indexTemplate = template.Must(template.New("index.tmpl").ParseFiles("templates/index.tmpl"))
var (
api *slack.Client
captcha *recaptcha.Recaptcha
counter *ratecounter.RateCounter
ourTeam = new(team)
m *expvar.Map
hitsPerMinute,
requests,
inviteErrors,
missingFirstName,
missingLastName,
missingEmail,
missingCoC,
successfulCaptcha,
failedCaptcha,
invalidCaptcha,
successfulInvites,
userCount,
activeUserCount expvar.Int
)
var c Specification
// Specification is the config struct
type Specification struct {
Port string `envconfig:"PORT" required:"true"`
CaptchaSitekey string `required:"true"`
CaptchaSecret string `required:"true"`
SlackToken string `required:"true"`
CocUrl string `required:"false" default:"http://coc.golangbridge.org/"`
EnforceHTTPS bool
Debug bool
}
func init() {
err := envconfig.Process("slackinviter", &c)
if err != nil {
log.Fatal(err.Error())
}
counter = ratecounter.NewRateCounter(1 * time.Minute)
m = expvar.NewMap("metrics")
m.Set("hits_per_minute", &hitsPerMinute)
m.Set("requests", &requests)
m.Set("invite_errors", &inviteErrors)
m.Set("missing_first_name", &missingFirstName)
m.Set("missing_last_name", &missingLastName)
m.Set("missing_email", &missingEmail)
m.Set("missing_coc", &missingCoC)
m.Set("failed_captcha", &failedCaptcha)
m.Set("invalid_captcha", &invalidCaptcha)
m.Set("successful_captcha", &successfulCaptcha)
m.Set("successful_invites", &successfulInvites)
m.Set("active_user_count", &activeUserCount)
m.Set("user_count", &userCount)
captcha = recaptcha.New(c.CaptchaSecret)
api = slack.New(c.SlackToken)
if c.Debug {
api.SetDebug(true)
}
}
func main() {
go pollSlack()
mux := http.NewServeMux()
mux.HandleFunc("/invite/", handleInvite)
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
mux.HandleFunc("/", enforceHTTPSFunc(homepage))
mux.Handle("/debug/vars", http.DefaultServeMux)
err := http.ListenAndServe(":"+c.Port, handlers.CombinedLoggingHandler(os.Stdout, mux))
if err != nil {
log.Fatal(err.Error())
}
}
func enforceHTTPSFunc(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if xfp := r.Header.Get("X-Forwarded-Proto"); c.EnforceHTTPS && xfp == "http" {
u := *r.URL
u.Scheme = "https"
if u.Host == "" {
u.Host = r.Host
}
http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
return
}
h(w, r)
}
}
// Updates the globals from the slack API
// returns the length of time to sleep before the function
// should be called again
func updateFromSlack() time.Duration {
users, err := api.GetUsers()
if err != nil {
log.Println("error polling slack for users:", err)
return time.Minute
}
var uCount, aCount int64 // users and active users
for _, u := range users {
if u.ID != "USLACKBOT" && !u.IsBot && !u.Deleted {
uCount++
if u.Presence == "active" {
aCount++
}
}
}
userCount.Set(uCount)
activeUserCount.Set(aCount)
st, err := api.GetTeamInfo()
if err != nil {
log.Println("error polling slack for team info:", err)
return time.Minute
}
ourTeam.Update(st)
return 10 * time.Minute
}
// pollSlack over and over again
func pollSlack() {
for {
time.Sleep(updateFromSlack())
}
}
// Homepage renders the homepage
func homepage(w http.ResponseWriter, r *http.Request) {
counter.Incr(1)
hitsPerMinute.Set(counter.Rate())
requests.Add(1)
var buf bytes.Buffer
err := indexTemplate.Execute(
&buf,
struct {
SiteKey,
UserCount,
ActiveCount string
Team *team
CocUrl string
}{
c.CaptchaSitekey,
userCount.String(),
activeUserCount.String(),
ourTeam,
c.CocUrl,
},
)
if err != nil {
log.Println("error rendering template:", err)
http.Error(w, "error rendering template :-(", http.StatusInternalServerError)
return
}
// Set the header and write the buffer to the http.ResponseWriter
w.Header().Set("Content-Type", "text/html; charset=utf-8")
buf.WriteTo(w)
}
// ShowPost renders a single post
func handleInvite(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
captchaResponse := r.FormValue("g-recaptcha-response")
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
failedCaptcha.Add(1)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
valid, err := captcha.Verify(captchaResponse, remoteIP)
if err != nil {
failedCaptcha.Add(1)
http.Error(w, "Error validating recaptcha.. Did you click it?", http.StatusPreconditionFailed)
return
}
if !valid {
invalidCaptcha.Add(1)
http.Error(w, "Invalid recaptcha", http.StatusInternalServerError)
return
}
successfulCaptcha.Add(1)
fname := r.FormValue("fname")
lname := r.FormValue("lname")
email := r.FormValue("email")
coc := r.FormValue("coc")
if email == "" {
missingEmail.Add(1)
http.Error(w, "Missing email", http.StatusPreconditionFailed)
return
}
if fname == "" {
missingFirstName.Add(1)
http.Error(w, "Missing first name", http.StatusPreconditionFailed)
return
}
if lname == "" {
missingLastName.Add(1)
http.Error(w, "Missing last name", http.StatusPreconditionFailed)
return
}
if coc != "1" {
missingCoC.Add(1)
http.Error(w, "You need to accept the code of conduct", http.StatusPreconditionFailed)
return
}
err = api.InviteToTeam(ourTeam.Domain(), fname, lname, email)
if err != nil {
log.Println("InviteToTeam error:", err)
inviteErrors.Add(1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
successfulInvites.Add(1)
}