-
Notifications
You must be signed in to change notification settings - Fork 214
/
middleware.go
62 lines (54 loc) · 1.38 KB
/
middleware.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
package auth
import (
"net/http"
"strings"
"github.com/nkanaev/yarr/src/assets"
"github.com/nkanaev/yarr/src/server/router"
"github.com/nkanaev/yarr/src/storage"
)
type Middleware struct {
Username string
Password string
BasePath string
Public []string
DB *storage.Storage
}
func unsafeMethod(method string) bool {
return method == "POST" || method == "PUT" || method == "DELETE"
}
func (m *Middleware) Handler(c *router.Context) {
for _, path := range m.Public {
if strings.HasPrefix(c.Req.URL.Path, m.BasePath+path) {
c.Next()
return
}
}
if IsAuthenticated(c.Req, m.Username, m.Password) {
c.Next()
return
}
rootUrl := m.BasePath + "/"
if c.Req.URL.Path != rootUrl {
c.Out.WriteHeader(http.StatusUnauthorized)
return
}
if c.Req.Method == "POST" {
username := c.Req.FormValue("username")
password := c.Req.FormValue("password")
if StringsEqual(username, m.Username) && StringsEqual(password, m.Password) {
Authenticate(c.Out, m.Username, m.Password, m.BasePath)
c.Redirect(rootUrl)
return
} else {
c.HTML(http.StatusOK, assets.Template("login.html"), map[string]interface{}{
"username": username,
"error": "Invalid username/password",
"settings": m.DB.GetSettings(),
})
return
}
}
c.HTML(http.StatusOK, assets.Template("login.html"), map[string]interface{}{
"settings": m.DB.GetSettings(),
})
}