-
Notifications
You must be signed in to change notification settings - Fork 927
/
verification_web.go
350 lines (281 loc) · 10.2 KB
/
verification_web.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package verification
import (
"database/sql"
_ "embed"
"encoding/json"
"fmt"
"html"
"html/template"
"net/http"
"net/url"
"strconv"
"time"
"github.com/botlabs-gg/yagpdb/v2/analytics"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/common/cplogs"
"github.com/botlabs-gg/yagpdb/v2/common/scheduledevents2"
"github.com/botlabs-gg/yagpdb/v2/verification/models"
"github.com/botlabs-gg/yagpdb/v2/web"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday"
"github.com/sirupsen/logrus"
"github.com/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
"goji.io/pat"
)
//go:embed assets/verification_control_panel.html
var PageHTMLControlPanel string
//go:embed assets/verification_verify_page.html
var PageHTMLVerifyPage string
type FormData struct {
Enabled bool
VerifiedRole int64 `valid:"role,true"`
PageContent string `valid:",10000"`
KickUnverifiedAfter int `valid:"0,"`
WarnUnverifiedAfter int `valid:"0,"`
WarnMessage string `valid:"template,10000"`
DMMessage string `valid:"template,10000"`
LogChannel int64 `valid:"channel,true"`
}
var panelLogKey = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "verification_updated_settings", FormatString: "Updated verification settings"})
func (p *Plugin) InitWeb() {
web.AddHTMLTemplate("verification/assets/verification_control_panel.html", PageHTMLControlPanel)
web.AddHTMLTemplate("verification/assets/verification_verify_page.html", PageHTMLVerifyPage)
web.AddSidebarItem(web.SidebarCategoryTools, &web.SidebarItem{
Name: "Verification",
URL: "verification",
Icon: "fas fa-address-card",
})
getHandler := web.ControllerHandler(p.handleGetSettings, "cp_verification_settings")
postHandler := web.ControllerPostHandler(p.handlePostSettings, getHandler, FormData{})
web.CPMux.Handle(pat.Get("/verification"), web.RequireBotMemberMW(getHandler))
web.CPMux.Handle(pat.Get("/verification/"), web.RequireBotMemberMW(getHandler))
web.CPMux.Handle(pat.Post("/verification"), postHandler)
getVerifyPageHandler := web.ControllerHandler(p.handleGetVerifyPage, "verification_verify_page")
postVerifyPageHandler := web.ControllerPostHandler(p.handlePostVerifyPage, getVerifyPageHandler, nil)
web.ServerPublicMux.Handle(pat.Get("/verify/:user_id/:token"), getVerifyPageHandler)
web.ServerPublicMux.Handle(pat.Post("/verify/:user_id/:token"), postVerifyPageHandler)
}
func (p *Plugin) handleGetSettings(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, templateData := web.GetBaseCPContextData(ctx)
settings, err := models.FindVerificationConfigG(ctx, g.ID)
if err == sql.ErrNoRows {
settings = &models.VerificationConfig{
GuildID: g.ID,
}
err = nil
}
roleInvalid := true
for _, role := range g.Roles {
if role.ID == settings.VerifiedRole {
roleInvalid = false
break
}
}
if settings != nil && settings.DMMessage == "" {
settings.DMMessage = DefaultDMMessage
}
templateData["DefaultPageContent"] = DefaultPageContent
templateData["PluginSettings"] = settings
templateData["RoleInvalid"] = roleInvalid
return templateData, err
}
func (p *Plugin) handlePostSettings(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, templateData := web.GetBaseCPContextData(ctx)
formConfig := ctx.Value(common.ContextKeyParsedForm).(*FormData)
model := &models.VerificationConfig{
GuildID: g.ID,
Enabled: formConfig.Enabled,
VerifiedRole: formConfig.VerifiedRole,
PageContent: formConfig.PageContent,
KickUnverifiedAfter: formConfig.KickUnverifiedAfter,
WarnUnverifiedAfter: formConfig.WarnUnverifiedAfter,
WarnMessage: formConfig.WarnMessage,
LogChannel: formConfig.LogChannel,
DMMessage: formConfig.DMMessage,
}
columns := boil.Whitelist("enabled", "verified_role", "page_content", "kick_unverified_after", "warn_unverified_after", "warn_message", "log_channel", "dm_message")
columnsCreate := boil.Whitelist("guild_id", "enabled", "verified_role", "page_content", "kick_unverified_after", "warn_unverified_after", "warn_message", "log_channel", "dm_message")
err := model.UpsertG(ctx, true, []string{"guild_id"}, columns, columnsCreate)
if err == nil {
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKey))
}
return templateData, err
}
func (p *Plugin) handleGetVerifyPage(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, templateData := web.GetBaseCPContextData(ctx)
// render main page content
settings, err := models.FindVerificationConfigG(ctx, g.ID)
if err == sql.ErrNoRows {
settings = &models.VerificationConfig{
GuildID: g.ID,
}
err = nil
}
if err != nil {
return templateData, err
}
if !settings.Enabled {
templateData.AddAlerts(web.ErrorAlert("Verification system disabled on this server"))
return templateData, nil
}
if _, ok := templateData["REValid"]; !ok {
// check if there's a valid session if we didn't just finish verifying
userID, _ := strconv.ParseInt(pat.Param(r, "user_id"), 10, 64)
token := pat.Param(r, "token")
_, err = models.VerificationSessions(
models.VerificationSessionWhere.UserID.EQ(userID),
models.VerificationSessionWhere.Token.EQ(token),
models.VerificationSessionWhere.ExpiredAt.IsNull(),
models.VerificationSessionWhere.SolvedAt.IsNull()).OneG(ctx)
if err != nil {
if err == sql.ErrNoRows {
templateData.AddAlerts(web.ErrorAlert("No verification session, try rejoining the server or contact an admin if the problem persist"))
return templateData, nil
}
return templateData, err
}
}
templateData["ExtraHead"] = template.HTML(`<script src="https://www.google.com/recaptcha/api.js" async defer></script>`)
templateData["GoogleReCaptchaSiteKey"] = confGoogleReCAPTCHASiteKey.GetString()
msg := settings.PageContent
if msg == "" {
msg = DefaultPageContent
}
unsafe := blackfriday.MarkdownCommon([]byte(msg))
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
templateData["RenderedPageContent"] = template.HTML(html)
return templateData, nil
}
func (p *Plugin) handlePostVerifyPage(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, templateData := web.GetBaseCPContextData(ctx)
settings, err := models.FindVerificationConfigG(ctx, g.ID)
if err == sql.ErrNoRows {
settings = &models.VerificationConfig{
GuildID: g.ID,
}
err = nil
}
if err != nil {
return templateData, err
}
if !settings.Enabled {
templateData.AddAlerts(web.ErrorAlert("Verification system disabled on this server"))
return templateData, nil
}
valid, err := p.checkCAPTCHAResponse(r.FormValue("g-recaptcha-response"))
if err != nil {
logrus.WithError(err).Error("Failed recaptcha response")
}
token := pat.Param(r, "token")
userID, _ := strconv.ParseInt(pat.Param(r, "user_id"), 10, 64)
verSession, err := models.VerificationSessions(
models.VerificationSessionWhere.UserID.EQ(userID),
models.VerificationSessionWhere.Token.EQ(token),
models.VerificationSessionWhere.ExpiredAt.IsNull(),
models.VerificationSessionWhere.SolvedAt.IsNull()).OneG(ctx)
if err != nil {
if err == sql.ErrNoRows {
templateData.AddAlerts(web.ErrorAlert("No verification session, try rejoining the server or contact an admin if the problem persist"))
return templateData, nil
}
return templateData, err
}
if valid {
ip := ""
if confVerificationTrackIPs.GetBool() {
ip = web.GetRequestIP(r)
}
model := &models.VerifiedUser{
UserID: userID,
GuildID: g.ID,
VerifiedAt: time.Now(),
IP: ip,
}
err := model.UpsertG(ctx, true, []string{"guild_id", "user_id"}, boil.Infer(), boil.Infer())
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("failed verifying user")
return templateData, err
}
scheduledevents2.ScheduleEvent("verification_user_verified", g.ID, time.Now(), userID)
verSession.SolvedAt = null.TimeFrom(time.Now())
verSession.UpdateG(ctx, boil.Infer())
go analytics.RecordActiveUnit(g.ID, p, "completed")
} else {
templateData.AddAlerts(web.ErrorAlert("Invalid reCAPTCHA submission."))
}
templateData["REValid"] = valid
return templateData, err
}
type CheckCAPTCHAResponse struct {
Success bool `json:"success"`
ChallengeTS string `json:"challenge_ts"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
type CheckCAPTCHARequest struct {
Secret string `json:"secret"`
Response string `json:"response"`
}
func (p *Plugin) checkCAPTCHAResponse(response string) (valid bool, err error) {
v := url.Values{
"response": {response},
"secret": {confGoogleReCAPTCHASecret.GetString()},
}
resp, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", v)
if err != nil {
return false, err
}
defer resp.Body.Close()
var dst CheckCAPTCHAResponse
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&dst)
if err != nil {
return false, err
}
if !dst.Success {
logger.Warnf("reCAPTCHA failed: %#v", dst)
}
return dst.Success, nil
}
var _ web.PluginWithServerHomeWidget = (*Plugin)(nil)
func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ag, templateData := web.GetBaseCPContextData(r.Context())
ctx := r.Context()
templateData["WidgetTitle"] = "Google reCAPTCHA Verification"
templateData["SettingsPath"] = "/verification"
settings, err := models.FindVerificationConfigG(ctx, ag.ID)
if err != nil {
if err == sql.ErrNoRows {
settings = &models.VerificationConfig{
GuildID: ag.ID,
}
} else {
return templateData, err
}
}
format := `<ul>
<li>Status: %s</li>
<li>Role: <code>%s</code> %s</li>
</ul>`
status := web.EnabledDisabledSpanStatus(settings.Enabled)
if settings.Enabled {
templateData["WidgetEnabled"] = true
} else {
templateData["WidgetDisabled"] = true
}
roleStr := "none / unknown"
indicatorRole := ""
if role := ag.GetRole(settings.VerifiedRole); role != nil {
roleStr = html.EscapeString(role.Name)
indicatorRole = web.Indicator(true)
} else {
indicatorRole = web.Indicator(false)
}
templateData["WidgetBody"] = template.HTML(fmt.Sprintf(format, status, roleStr, indicatorRole))
return templateData, nil
}