43 lines
955 B
Go
43 lines
955 B
Go
|
package router
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
|
||
|
"go.jolheiser.com/cabinet/internal/workspace"
|
||
|
)
|
||
|
|
||
|
func tokenMiddleware(c Cabinet, perm workspace.TokenPermission) func(handler http.Handler) http.Handler {
|
||
|
return func(next http.Handler) http.Handler {
|
||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
prot, err := c.IsProtected()
|
||
|
if err != nil {
|
||
|
http.Error(w, "could not check token protection", http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
if !prot {
|
||
|
next.ServeHTTP(w, r)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
t := r.FormValue("token")
|
||
|
if t == "" {
|
||
|
http.Error(w, "this host is token protected", http.StatusUnauthorized)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
token, err := c.Token(t)
|
||
|
if err != nil {
|
||
|
http.Error(w, "could not get token", http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if !token.Has(perm) {
|
||
|
http.Error(w, "this token cannot access this resource", http.StatusForbidden)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
next.ServeHTTP(w, r)
|
||
|
})
|
||
|
}
|
||
|
}
|