This repository has been archived by the owner on Nov 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.go
211 lines (186 loc) · 5.92 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
package main
import (
"context"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/etherlabsio/healthcheck"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/xanderstrike/goplaxt/lib/config"
"github.com/xanderstrike/goplaxt/lib/store"
"github.com/xanderstrike/goplaxt/lib/trakt"
"github.com/xanderstrike/plexhooks"
)
var storage store.Store
type AuthorizePage struct {
SelfRoot string
Authorized bool
URL string
ClientID string
}
func SelfRoot(r *http.Request) string {
u, _ := url.Parse("")
u.Host = r.Host
u.Scheme = r.URL.Scheme
u.Path = ""
if u.Scheme == "" {
u.Scheme = "http"
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "https" {
u.Scheme = "https"
}
}
return u.String()
}
func authorize(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
username := strings.ToLower(args["username"][0])
log.Print(fmt.Sprintf("Handling auth request for %s", username))
code := args["code"][0]
result, _ := trakt.AuthRequest(SelfRoot(r), username, code, "", "authorization_code")
user := store.NewUser(username, result["access_token"].(string), result["refresh_token"].(string), storage)
url := fmt.Sprintf("%s/api?id=%s", SelfRoot(r), user.ID)
log.Print(fmt.Sprintf("Authorized as %s", user.ID))
tmpl := template.Must(template.ParseFiles("static/index.html"))
data := AuthorizePage{
SelfRoot: SelfRoot(r),
Authorized: true,
URL: url,
ClientID: config.TraktClientId,
}
tmpl.Execute(w, data)
}
func api(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
id := args["id"][0]
log.Print(fmt.Sprintf("Webhook call for %s", id))
user := storage.GetUser(id)
if user == nil {
log.Println("User not found.")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode("user not found")
return
}
tokenAge := time.Since(user.Updated).Hours()
if tokenAge > 1440 { // tokens expire after 3 months, so we refresh after 2
log.Println("User access token outdated, refreshing...")
result, success := trakt.AuthRequest(SelfRoot(r), user.Username, "", user.RefreshToken, "refresh_token")
if success {
user.UpdateUser(result["access_token"].(string), result["refresh_token"].(string))
log.Println("Refreshed, continuing")
} else {
log.Println("Refresh failed, skipping and deleting user")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode("fail")
storage.DeleteUser(user.ID)
return
}
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
regex := regexp.MustCompile("({.*})") // not the best way really
match := regex.FindStringSubmatch(string(body))
re, err := plexhooks.ParseWebhook([]byte(match[0]))
if err != nil {
panic(err)
}
// re := plexhooks.ParseWebhook([]byte(match[0]))
if strings.ToLower(re.Account.Title) == user.Username {
// FIXME - make everything take the pointer
trakt.Handle(re, *user)
} else {
log.Println(fmt.Sprintf("Plex username %s does not equal %s, skipping", strings.ToLower(re.Account.Title), user.Username))
}
json.NewEncoder(w).Encode("success")
}
func allowedHostsHandler(allowedHostnames string) func(http.Handler) http.Handler {
allowedHosts := strings.Split(regexp.MustCompile("https://|http://|\\s+").ReplaceAllString(strings.ToLower(allowedHostnames), ""), ",")
log.Println("Allowed Hostnames:", allowedHosts)
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.URL.EscapedPath() == "/healthcheck" {
h.ServeHTTP(w, r)
return
}
isAllowedHost := false
lcHost := strings.ToLower(r.Host)
for _, value := range allowedHosts {
if lcHost == value {
isAllowedHost = true
break
}
}
if !isAllowedHost {
w.WriteHeader(http.StatusUnauthorized)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Oh no!")
return
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func healthcheckHandler() http.Handler {
return healthcheck.Handler(
healthcheck.WithTimeout(5*time.Second),
healthcheck.WithChecker("storage", healthcheck.CheckerFunc(func(ctx context.Context) error {
return storage.Ping(ctx)
})),
)
}
func main() {
log.Print("Started!")
if os.Getenv("POSTGRESQL_URL") != "" {
storage = store.NewPostgresqlStore(store.NewPostgresqlClient(os.Getenv("POSTGRESQL_URL")))
log.Println("Using postgresql storage:", os.Getenv("POSTGRESQL_URL"))
} else if os.Getenv("REDIS_URI") != "" {
storage = store.NewRedisStore(store.NewRedisClient(os.Getenv("REDIS_URI"), os.Getenv("REDIS_PASSWORD")))
log.Println("Using redis storage:", os.Getenv("REDIS_URI"))
} else {
storage = store.NewDiskStore()
log.Println("Using disk storage:")
}
router := mux.NewRouter()
// Assumption: Behind a proper web server (nginx/traefik, etc) that removes/replaces trusted headers
router.Use(handlers.ProxyHeaders)
// which hostnames we are allowing
// REDIRECT_URI = old legacy list
// ALLOWED_HOSTNAMES = new accurate config variable
// No env = all hostnames
if os.Getenv("REDIRECT_URI") != "" {
router.Use(allowedHostsHandler(os.Getenv("REDIRECT_URI")))
} else if os.Getenv("ALLOWED_HOSTNAMES") != "" {
router.Use(allowedHostsHandler(os.Getenv("ALLOWED_HOSTNAMES")))
}
router.HandleFunc("/authorize", authorize).Methods("GET")
router.HandleFunc("/api", api).Methods("POST")
router.Handle("/healthcheck", healthcheckHandler()).Methods("GET")
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("static/index.html"))
data := AuthorizePage{
SelfRoot: SelfRoot(r),
Authorized: false,
URL: "https://plaxt.astandke.com/api?id=generate-your-own-silly",
ClientID: config.TraktClientId,
}
tmpl.Execute(w, data)
}).Methods("GET")
listen := os.Getenv("LISTEN")
if listen == "" {
listen = "0.0.0.0:8000"
}
log.Print("Started on " + listen + "!")
log.Fatal(http.ListenAndServe(listen, router))
}