-
Notifications
You must be signed in to change notification settings - Fork 927
/
util.go
355 lines (281 loc) · 7.69 KB
/
util.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
351
352
353
354
355
package web
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/common"
"github.com/sirupsen/logrus"
"goji.io/pattern"
)
var ErrTokenExpired = errors.New("OAUTH2 Token expired")
func SetContextTemplateData(ctx context.Context, data map[string]interface{}) context.Context {
// Check for existing data
if val := ctx.Value(common.ContextKeyTemplateData); val != nil {
cast := val.(TemplateData)
for k, v := range data {
cast[k] = v
}
return ctx
}
// Fallback
return context.WithValue(ctx, common.ContextKeyTemplateData, TemplateData(data))
}
func DiscordSessionFromContext(ctx context.Context) *discordgo.Session {
if val := ctx.Value(common.ContextKeyDiscordSession); val != nil {
if cast, ok := val.(*discordgo.Session); ok {
return cast
}
}
return nil
}
func RandBase64(size int) string {
b := make([]byte, size)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
return base64.URLEncoding.EncodeToString(b)
}
func GenSessionCookie() *http.Cookie {
data := RandBase64(32)
cookie := &http.Cookie{
Name: "yagpdb-session",
Value: data,
MaxAge: 86400,
Path: "/",
}
return cookie
}
func LogIgnoreErr(err error) {
if err != nil {
logger.Error("Error:", err)
}
}
type TemplateData map[string]interface{}
func (t TemplateData) AddAlerts(alerts ...*Alert) TemplateData {
if t["Alerts"] == nil {
t["Alerts"] = make([]*Alert, 0)
}
t["Alerts"] = append(t["Alerts"].([]*Alert), alerts...)
return t
}
func (t TemplateData) Alerts() []*Alert {
if v, ok := t["Alerts"]; ok {
return v.([]*Alert)
}
return nil
}
func GetCreateTemplateData(ctx context.Context) (context.Context, TemplateData) {
if v := ctx.Value(common.ContextKeyTemplateData); v != nil {
return ctx, v.(TemplateData)
}
tmplData := TemplateData(make(map[string]interface{}))
ctx = context.WithValue(ctx, common.ContextKeyTemplateData, tmplData)
return ctx, tmplData
}
type Alert struct {
Style string
Message string
}
const (
AlertDanger = "danger"
AlertSuccess = "success"
AlertInfo = "info"
AlertWarning = "warning"
)
func ErrorAlert(args ...interface{}) *Alert {
return &Alert{
Style: AlertDanger,
Message: fmt.Sprint(args...),
}
}
func WarningAlert(args ...interface{}) *Alert {
return &Alert{
Style: AlertWarning,
Message: fmt.Sprint(args...),
}
}
func SucessAlert(args ...interface{}) *Alert {
return &Alert{
Style: AlertSuccess,
Message: fmt.Sprint(args...),
}
}
func ContextGuild(ctx context.Context) *discordgo.Guild {
return ctx.Value(common.ContextKeyCurrentGuild).(*discordgo.Guild)
}
func ContextIsAdmin(ctx context.Context) bool {
i := ctx.Value(common.ContextKeyIsAdmin)
if i == nil {
return false
}
return i.(bool)
}
// Returns base context data for control panel plugins
func GetBaseCPContextData(ctx context.Context) (*discordgo.Guild, TemplateData) {
var guild *discordgo.Guild
if v := ctx.Value(common.ContextKeyCurrentGuild); v != nil {
guild = v.(*discordgo.Guild)
}
templateData := ctx.Value(common.ContextKeyTemplateData).(TemplateData)
return guild, templateData
}
// Checks and error and logs it aswell as adding it to the alerts
// returns true if an error occured
func CheckErr(t TemplateData, err error, errMsg string, logger func(...interface{})) bool {
if err == nil {
return false
}
if errMsg == "" {
errMsg = err.Error()
}
t.AddAlerts(ErrorAlert("An Error occured: ", errMsg))
if logger != nil {
logger("An error occured:", err)
}
return true
}
// Checks the context if there is a logged in user and if so if he's and admin or not
func IsAdminRequest(ctx context.Context, r *http.Request) (read bool, write bool) {
isReadOnlyReq := strings.EqualFold(r.Method, "GET") || strings.EqualFold(r.Method, "OPTIONS")
if v := ctx.Value(common.ContextKeyCurrentGuild); v != nil {
// accessing a server page
g := v.(*discordgo.Guild)
gWithConnected := &common.GuildWithConnected{
UserGuild: &discordgo.UserGuild{
ID: g.ID,
},
Connected: true,
}
coreConf := common.ContextCoreConf(ctx)
member := ContextMember(ctx)
userID := int64(0)
var roles []int64
if member != nil {
userID = member.User.ID
roles = member.Roles
gWithConnected.Permissions = ContextMemberPerms(ctx)
gWithConnected.Owner = userID == g.OwnerID
}
hasRead, hasWrite := GetUserAccessLevel(userID, gWithConnected, coreConf, StaticRoleProvider(roles))
if hasWrite {
return true, true
}
if hasRead && isReadOnlyReq {
return true, false
}
}
if user := ctx.Value(common.ContextKeyUser); user != nil {
// there is a active session, but they're not on the related guild (if any)
cast := user.(*discordgo.User)
if common.IsOwner(cast.ID) {
return true, true
}
if isReadOnlyReq {
// allow special read only acces for GET and OPTIONS requests, simple and works well
if hasAcces, err := bot.HasReadOnlyAccess(cast.ID); hasAcces && err == nil {
return true, false
}
}
}
return false, false
}
func StaticRoleProvider(roles []int64) func(guildID, userID int64) []int64 {
return func(guildID, userID int64) []int64 {
return roles
}
}
func HasPermissionCTX(ctx context.Context, aperms int) bool {
perms := ContextMemberPerms(ctx)
// Require manageserver, ownership of guild or ownership of bot
if perms&discordgo.PermissionAdministrator == discordgo.PermissionAdministrator ||
perms&discordgo.PermissionManageServer == discordgo.PermissionManageServer || perms&aperms == aperms {
return true
}
return false
}
type APIError struct {
Message string
}
// CtxLogger Returns an always non nil entry either from the context or standard logger
func CtxLogger(ctx context.Context) *logrus.Entry {
if inter := ctx.Value(common.ContextKeyLogger); inter != nil {
return inter.(*logrus.Entry)
}
return logger
}
func WriteErrorResponse(w http.ResponseWriter, r *http.Request, err string, statusCode int) {
if r.FormValue("partial") != "" {
w.WriteHeader(statusCode)
w.Write([]byte(`{"error": "` + err + `"}`))
return
}
http.Redirect(w, r, "/?error="+url.QueryEscape(err), http.StatusTemporaryRedirect)
return
}
func IsRequestPartial(ctx context.Context) bool {
if v := ctx.Value(common.ContextKeyIsPartial); v != nil {
return v.(bool)
}
return false
}
func ContextUser(ctx context.Context) *discordgo.User {
return ctx.Value(common.ContextKeyUser).(*discordgo.User)
}
func ContextMember(ctx context.Context) *discordgo.Member {
i := ctx.Value(common.ContextKeyUserMember)
if i == nil {
return nil
}
return i.(*discordgo.Member)
}
func ContextMemberPerms(ctx context.Context) int {
i := ctx.Value(common.ContextKeyMemberPermissions)
if i == nil {
return 0
}
return i.(int)
}
func ParamOrEmpty(r *http.Request, key string) string {
s := r.Context().Value(pattern.Variable(key))
if s != nil {
return s.(string)
}
return ""
}
func Indicator(enabled bool) string {
const IndEnabled = `<span class="indicator indicator-success"></span>`
const IndDisabled = `<span class="indicator indicator-danger"></span>`
if enabled {
return IndEnabled
}
return IndDisabled
}
func EnabledDisabledSpanStatus(enabled bool) (str string) {
indicator := Indicator(enabled)
enabledStr := "disabled"
enabledClass := "danger"
if enabled {
enabledStr = "enabled"
enabledClass = "success"
}
return fmt.Sprintf("<span class=\"text-%s\">%s</span>%s", enabledClass, enabledStr, indicator)
}
func GetRequestIP(r *http.Request) string {
headerField := confReverseProxyClientIPHeader.GetString()
if headerField == "" {
li := strings.LastIndex(r.RemoteAddr, ":")
if li < 0 {
return r.RemoteAddr
}
return r.RemoteAddr[:li]
}
return r.Header.Get(headerField)
}