Skip to content

Instantly share code, notes, and snippets.

@cameronjacobson
Last active February 3, 2024 14:19
Show Gist options
  • Save cameronjacobson/5c19fbeb64610b39e3e6 to your computer and use it in GitHub Desktop.
Save cameronjacobson/5c19fbeb64610b39e3e6 to your computer and use it in GitHub Desktop.
Experimenting with ways to place thin "auth" layer to give web browsers direct / whitelisted access to CouchDB resources
{
"Host": "http://127.0.0.1:5984",
"Patterns":{
"GET":[
"^/_all_db",
"^/b$",
"^/c"
],
"POST":[
"^/db/"
],
"DELETE":[
"^/db/[a-f0-9]{32}[?]rev=[a-f0-9-]+?$"
]
}
}
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
)
type couchConfig struct {
Host string
Patterns map[string][]string
}
type couchMarshall struct {
config couchConfig
}
func (self *couchMarshall) loadConfig(filename string) {
data, _ := ioutil.ReadFile(filename)
err := json.Unmarshal(data, &self.config)
if err != nil {
fmt.Println("error:", err)
}
}
func (self couchMarshall) ServeHTTP(w http.ResponseWriter, req *http.Request) {
matchUrl := ""
if vals, ok := self.config.Patterns[req.Method]; ok {
for _, v := range vals {
matchUrl = req.URL.Path
if len(req.URL.RawQuery) > 0 {
matchUrl += "?" + req.URL.RawQuery
}
if matched, _ := regexp.MatchString(v, matchUrl); matched {
resp := &http.Response{}
switch req.Method {
default:
break
case "GET":
resp, _ = http.Get(self.config.Host + req.URL.Path + "?" + req.URL.RawQuery)
break
case "POST":
resp, _ = http.Post(self.config.Host+req.URL.Path+"?"+req.URL.RawQuery, "application/json", req.Body)
break
case "DELETE":
r, _ := http.NewRequest("DELETE", self.config.Host+req.URL.Path+"?"+req.URL.RawQuery, nil)
clie := &http.Client{}
resp, _ = clie.Do(r)
break
}
res, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
w.Write(res)
return
}
}
}
http.Error(w, "PROBLEM", 500)
}
func main() {
cm := couchMarshall{}
cm.loadConfig("config.json")
s := &http.Server{
Addr: ":8082",
Handler: cm,
}
log.Fatal(s.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment