76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func (server *Server) authenticate(w http.ResponseWriter, r *http.Request) (*Server, bool, error) {
|
|
if err := server.parseLogin(w, r); err != nil {
|
|
return nil, false, err
|
|
}
|
|
if ok, err := server.needsLogin(r); err != nil {
|
|
return nil, false, err
|
|
} else if ok {
|
|
w.Header().Set("WWW-Authenticate", "Basic")
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return nil, true, nil
|
|
}
|
|
// TODO: if bad cookie OR no cookie: https://blog.stevensanderson.com/2008/08/25/using-the-browsers-native-login-prompt/
|
|
// TODO: prompt for user-pass if nothing supplied
|
|
// TODO: login
|
|
// TODO: logged in
|
|
// TODO: get namespaces
|
|
// TODO: verify cookie namespace is OK
|
|
// TODO: ~~logout~~ // client side
|
|
return server.WithLoggedIn("", "", []string{}), false, errors.New("not impl")
|
|
}
|
|
|
|
func (server *Server) parseLogin(w http.ResponseWriter, r *http.Request) error {
|
|
username, password, ok := r.BasicAuth()
|
|
if !ok {
|
|
return nil
|
|
}
|
|
_, _ = username, password
|
|
server.setLoginCookie(w, r, "abc")
|
|
return errors.New("todo: use username+password to set cookie")
|
|
}
|
|
|
|
func (server *Server) needsLogin(r *http.Request) (bool, error) {
|
|
_, ok := server.loginCookie(r)
|
|
if !ok {
|
|
return true, nil
|
|
}
|
|
// TODO compare namespace + cookie groups
|
|
return false, errors.New("not impl")
|
|
}
|
|
|
|
func (server *Server) setLoginCookie(w http.ResponseWriter, r *http.Request, value string) {
|
|
cookie := &http.Cookie{
|
|
Name: "login",
|
|
Value: server.encodeCookie(value),
|
|
Expires: time.Now().Add(time.Hour * 24),
|
|
}
|
|
w.Header().Set("Set-Cookie", cookie.String())
|
|
r.AddCookie(cookie)
|
|
}
|
|
|
|
func (server *Server) loginCookie(r *http.Request) (string, bool) {
|
|
cookies := r.Cookies()
|
|
for i := range cookies {
|
|
if cookies[i].Name == "login" && time.Now().Before(cookies[i].Expires) {
|
|
return server.decodeCookie(cookies[i].Value)
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
func (server *Server) decodeCookie(s string) (string, bool) {
|
|
panic("not impl")
|
|
}
|
|
|
|
func (server *Server) encodeCookie(s string) string {
|
|
panic("not impl")
|
|
}
|