stupid basic auth

master
Bel LaPointe 2020-05-12 06:31:16 -06:00
parent 433e47e3f5
commit e1ee647767
5 changed files with 55 additions and 7 deletions

23
cookie.go Normal file
View File

@ -0,0 +1,23 @@
package main
import (
"net/http"
"time"
)
func getCookie(r *http.Request, k string) string {
c, err := r.Cookie(k)
if err != nil {
return ""
}
return c.Value
}
func setCookie(w *http.ResponseWriter, k, v string) {
http.SetCookie(*w, &http.Cookie{
Name: k,
Value: v,
MaxAge: int(time.Now().Unix() + int64(60*60*24)),
Secure: true,
})
}

View File

@ -19,6 +19,7 @@ func NewPool() *Pool {
}
func (p *Pool) Broadcast(mt int, r io.Reader) error {
// io.MultiWriter exists but I like this
b, err := ioutil.ReadAll(r)
if err != nil {
return err

View File

@ -18,7 +18,7 @@
border: 1px solid black;
display: inline-block;
}
#preview { display: none; }
#preview { display: block; max-width: 150px; position: absolute; top: 0; right: 0; z-index: 1; }
</style>
</head>

View File

@ -1,15 +1,22 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"path"
"time"
"github.com/google/uuid"
"golang.org/x/time/rate"
)
type Server struct {
fs http.Handler
ws *WS
limiter *rate.Limiter
uuid string
}
func New() *Server {
@ -17,10 +24,16 @@ func New() *Server {
return &Server{
fs: fs,
ws: NewWS(),
limiter: rate.NewLimiter(rate.Every(time.Second), 2),
uuid: uuid.New().String(),
}
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !s.Authorize(w, r) {
return
}
log.Println("ext", path.Ext(r.URL.Path))
if path.Ext(r.URL.Path) != "" {
s.fs.ServeHTTP(w, r)
@ -30,3 +43,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.fs.ServeHTTP(w, r)
}
}
func (s *Server) Authorize(w http.ResponseWriter, r *http.Request) bool {
if u, p, ok := r.BasicAuth(); !ok || u != "Q" || p != "Q" {
s.limiter.Wait(r.Context())
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", r.Host))
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
return false
}
return true
}

3
ws.go
View File

@ -3,7 +3,6 @@ package main
import (
"log"
"net/http"
"strings"
"sync"
"github.com/google/uuid"
@ -34,7 +33,7 @@ func (ws *WS) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
func (ws *WS) serveHTTP(w http.ResponseWriter, r *http.Request) error {
id := strings.Split(r.Header.Get("Cookie"), "=")[1]
id := getCookie(r, "id")
if len(id) == 0 {
id = uuid.New().String()
}