auth middleware
This commit is contained in:
parent
dfb32d4ebe
commit
e9f6a0a1d2
3 changed files with 73 additions and 15 deletions
57
src/server/middleware.go
Normal file
57
src/server/middleware.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/nkanaev/yarr/src/assets"
|
||||
"github.com/nkanaev/yarr/src/auth"
|
||||
"github.com/nkanaev/yarr/src/router"
|
||||
)
|
||||
|
||||
type authMiddleware struct {
|
||||
username string
|
||||
password string
|
||||
basepath string
|
||||
public string
|
||||
}
|
||||
|
||||
func (m *authMiddleware) handler(c *router.Context) {
|
||||
basepath := m.basepath
|
||||
if basepath == "" {
|
||||
basepath = "/"
|
||||
}
|
||||
|
||||
if strings.HasPrefix(c.Req.URL.Path, m.public) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if auth.IsAuthenticated(c.Req, m.username, m.password) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
if c.Req.URL.Path != basepath {
|
||||
// TODO: check ajax
|
||||
c.Out.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
if c.Req.Method == "POST" {
|
||||
username := c.Req.FormValue("username")
|
||||
password := c.Req.FormValue("password")
|
||||
if auth.StringsEqual(username, m.username) && auth.StringsEqual(password, m.password) {
|
||||
auth.Authenticate(c.Out, m.username, m.password, m.basepath)
|
||||
c.Redirect(m.basepath)
|
||||
return
|
||||
} else {
|
||||
// TODO: show error
|
||||
c.Out.Header().Set("Content-Type", "text/html")
|
||||
assets.Render("login.html", c.Out, nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Out.Header().Set("Content-Type", "text/html")
|
||||
assets.Render("login.html", c.Out, nil)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue