2021-09-22 13:36:45 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2021-11-25 22:48:16 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2021-09-22 13:36:45 +00:00
|
|
|
"github.com/Luzifer/go_helpers/v2/str"
|
2022-10-23 13:06:45 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v2/pkg/twitch"
|
2021-09-22 13:36:45 +00:00
|
|
|
)
|
|
|
|
|
2021-10-22 15:09:39 +00:00
|
|
|
func getAuthorizationFromRequest(r *http.Request) (string, *twitch.Client, error) {
|
|
|
|
token := r.Header.Get("Authorization")
|
|
|
|
if token == "" {
|
|
|
|
return "", nil, errors.New("no authorization provided")
|
|
|
|
}
|
2021-09-22 13:36:45 +00:00
|
|
|
|
2021-12-31 12:42:37 +00:00
|
|
|
tc := twitch.New(cfg.TwitchClient, cfg.TwitchClientSecret, token, "")
|
2021-09-22 13:36:45 +00:00
|
|
|
|
2022-10-25 16:47:30 +00:00
|
|
|
_, user, err := tc.GetAuthorizedUser()
|
2021-10-22 15:09:39 +00:00
|
|
|
return user, tc, errors.Wrap(err, "getting authorized user")
|
|
|
|
}
|
|
|
|
|
|
|
|
func botEditorAuthMiddleware(h http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user, tc, err := getAuthorizationFromRequest(r)
|
2021-09-22 13:36:45 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(w, errors.Wrap(err, "getting authorized user").Error(), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
id, err := tc.GetIDForUsername(user)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, errors.Wrap(err, "getting ID for authorized user").Error(), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !str.StringInSlice(user, config.BotEditors) && !str.StringInSlice(id, config.BotEditors) {
|
|
|
|
http.Error(w, "user is not authorized", http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|