forked from mickael-kerjean/filestash
/
index.go
157 lines (148 loc) 路 4.29 KB
/
index.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
/*
* This plugin expose syncthing to the admin user
*/
package plg_handler_syncthing
import (
"encoding/base64"
"fmt"
. "github.com/bingoohuang/filestash/server/common"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
)
const SyncthingUri = "/admin/syncthing"
func init() {
pluginEnable := Config.Get("features.syncthing.enable").Schema(func(f *FormElement) *FormElement {
if f == nil {
f = &FormElement{}
}
f.Name = "enable"
f.Type = "enable"
f.Target = []string{"syncthing_server_url"}
f.Description = "Enable/Disable integration with the syncthing server. This will make your syncthing server available at `/admin/syncthing`"
f.Default = false
if u := os.Getenv("SYNCTHING_URL"); u != "" {
f.Default = true
}
return f
}).Bool()
Config.Get("features.syncthing.server_url").Schema(func(f *FormElement) *FormElement {
if f == nil {
f = &FormElement{}
}
f.Id = "syncthing_server_url"
f.Name = "server_url"
f.Type = "text"
f.Description = "Location of your Syncthing server"
f.Default = ""
f.Placeholder = "Eg: http://127.0.0.1:8080"
if u := os.Getenv("SYNCTHING_URL"); u != "" {
f.Default = u
f.Placeholder = fmt.Sprintf("Default: '%s'", u)
}
return f
})
Hooks.Register.HttpEndpoint(func(r *mux.Router, _ *App) error {
if !pluginEnable {
return nil
}
r.HandleFunc(SyncthingUri, func(res http.ResponseWriter, req *http.Request) {
http.Redirect(res, req, SyncthingUri+"/", http.StatusTemporaryRedirect)
})
r.Handle(SyncthingUri+"/", AuthBasic(
func() (string, string) { return "admin", ConfigAuthAdmin() },
http.HandlerFunc(SyncthingProxyHandler),
))
r.PathPrefix(SyncthingUri + "/").HandlerFunc(SyncthingProxyHandler)
return nil
})
}
func AuthBasic(credentials func() (string, string), fn http.Handler) http.HandlerFunc {
var notAuthorised = func(res http.ResponseWriter, req *http.Request) {
time.Sleep(1 * time.Second)
res.Header().Set("WWW-Authenticate", `Basic realm="User protect", charset="UTF-8"`)
res.WriteHeader(http.StatusUnauthorized)
res.Write([]byte("Not Authorised"))
return
}
return func(res http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Basic ") {
notAuthorised(res, req)
return
}
auth = strings.TrimPrefix(auth, "Basic ")
decoded, err := base64.StdEncoding.DecodeString(auth)
if err != nil {
notAuthorised(res, req)
return
}
auth = string(decoded)
stuffs := strings.Split(auth, ":")
if len(stuffs) < 2 {
notAuthorised(res, req)
return
}
username := stuffs[0]
password := strings.Join(stuffs[1:], ":")
refUsername, refPassword := credentials()
if refUsername != username {
notAuthorised(res, req)
return
} else if err = bcrypt.CompareHashAndPassword([]byte(refPassword), []byte(password)); err != nil {
notAuthorised(res, req)
return
}
fn.ServeHTTP(res, req)
return
}
}
func SyncthingProxyHandler(res http.ResponseWriter, req *http.Request) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, SyncthingUri)
req.Header.Set("X-Forwarded-Host", req.Host+SyncthingUri)
req.Header.Set("X-Forwarded-Proto", func() string {
if scheme := req.Header.Get("X-Forwarded-Proto"); scheme != "" {
return scheme
} else if req.TLS != nil {
return "https"
}
return "http"
}())
u, err := url.Parse(Config.Get("features.syncthing.server_url").String())
if err != nil {
SendErrorResult(res, err)
return
}
reverseProxy := &httputil.ReverseProxy{
Director: func(rq *http.Request) {
rq.URL.Scheme = "http"
rq.URL.Host = u.Host
rq.URL.Path = func(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}(u.Path, rq.URL.Path)
if u.RawQuery == "" || rq.URL.RawQuery == "" {
rq.URL.RawQuery = u.RawQuery + rq.URL.RawQuery
} else {
rq.URL.RawQuery = u.RawQuery + "&" + rq.URL.RawQuery
}
},
}
reverseProxy.ErrorHandler = func(rw http.ResponseWriter, rq *http.Request, err error) {
Log.Warning("[syncthing] %s", err.Error())
SendErrorResult(rw, NewError(err.Error(), http.StatusBadGateway))
}
reverseProxy.ServeHTTP(res, req)
}