Compare commits

..

6 Commits

Author SHA1 Message Date
Chris Sexton 6988064309 adoc support
* These changes are unverified and I don't know what they're really for
* Ref #7
2020-07-23 12:13:58 -04:00
cws b15a85131f Merge pull request 'authorization: only public entries without login' (#21) from 6_public_tag into master
Reviewed-on: #21
2020-03-18 18:08:21 +00:00
Chris Sexton 7f077cfe31 authorization: only public entries without login
Fixes #6
2020-03-18 14:07:34 -04:00
Chris Sexton 68b485c36f esc: fix string quotes 2020-03-17 12:57:04 -04:00
Chris Sexton d9a688dbd1 docker: change container to work with esc
* Also fix esc generate command
2020-03-17 10:36:23 -04:00
cws e504a660ae Merge pull request 'gen: switch to esc for static generation' (#18) from generate into master
Reviewed-on: #18
2020-03-17 09:57:30 +00:00
8 changed files with 166 additions and 84 deletions

View File

@ -49,7 +49,7 @@ func makeKey() (string, error) {
} }
func New(db *db.Database, name, password string) (*User, error) { func New(db *db.Database, name, password string) (*User, error) {
q := `insert into users values (null, ?, ?, ?, ?)` q := `insert or replace into users values (null, ?, ?, ?, ?)`
key, err := makeKey() key, err := makeKey()
if err != nil { if err != nil {

View File

@ -1,4 +1,4 @@
FROM alpine:edge FROM golang:alpine
RUN apk add --no-cache git RUN apk add --no-cache git
RUN apk add --no-cache musl-dev RUN apk add --no-cache musl-dev
@ -27,8 +27,7 @@ ENV TZ America/New_York
# RUN yarn global add @vue/cli # RUN yarn global add @vue/cli
RUN cd $SRC_DIR/frontend; yarn && yarn build RUN cd $SRC_DIR/frontend; yarn && yarn build
RUN go get -u github.com/gobuffalo/packr/v2/packr2 RUN go get -u github.com/mjibson/esc
RUN cd $SRC_DIR; $HOME/go/bin/packr2 RUN cd $SRC_DIR; go generate && go get ./... && go build -o /app/cabinet
RUN cd $SRC_DIR; go get ./...; go build -o /app/cabinet
ENTRYPOINT ["/app/cabinet", "-httpAddr=0.0.0.0:5673", "-db=/app/var/cabinet.db"] ENTRYPOINT ["/app/cabinet", "-httpAddr=0.0.0.0:5673", "-db=/app/var/cabinet.db"]

View File

@ -2,13 +2,16 @@ package entry
import ( import (
"fmt" "fmt"
"io"
"os/exec"
"regexp" "regexp"
"strings" "strings"
"time" "time"
"code.chrissexton.org/cws/cabinet/db"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"code.chrissexton.org/cws/cabinet/db"
) )
type Entry struct { type Entry struct {
@ -52,7 +55,7 @@ func PrepareTable(tx *sqlx.Tx) error {
return nil return nil
} }
func NewFromMd(db *db.Database, body string) *Entry { func NewFromAdoc(db *db.Database, body string) *Entry {
e := New(db) e := New(db)
e.Content = body e.Content = body
e.Title = e.GenerateTitle() e.Title = e.GenerateTitle()
@ -60,6 +63,33 @@ func NewFromMd(db *db.Database, body string) *Entry {
return e return e
} }
func pandocMdToAdoc(body string) string {
log.Debug().Str("input", body).Msgf("converting md->adoc")
cmd := exec.Command("pandoc", "-f", "commonmark", "-t", "asciidoctor")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Error().Err(err).Msgf("could not get stdin")
}
go func() {
defer stdin.Close()
io.WriteString(stdin, body)
}()
out, err := cmd.CombinedOutput()
if err != nil {
log.Error().Err(err).Msgf("could not get stdout")
}
log.Debug().Msgf("md->adoc: %s", out)
return string(out)
}
func NewFromMd(db *db.Database, body string) *Entry {
body = pandocMdToAdoc(body)
return NewFromAdoc(db, body)
}
func New(db *db.Database) *Entry { func New(db *db.Database) *Entry {
e := Entry{ e := Entry{
db: db, db: db,
@ -94,27 +124,49 @@ func GetByID(db *db.Database, id int64) (Entry, error) {
return e, e.populateTags() return e, e.populateTags()
} }
func Search(db *db.Database, query string) ([]*Entry, error) { func SearchByTag(db *db.Database, query string, tags []string) ([]*Entry, error) {
entries := []*Entry{} entries := []*Entry{}
log.Debug().Str("query", query).Msg("searching") query = fmt.Sprintf("%%%s%%", query)
if query != "" { log.Debug().Str("tag query", query).Int("len(tags)", len(tags)).Msg("searching")
q := `select * from entries where content like ? order by updated desc`
err := db.Select(&entries, q, "%"+query+"%") if len(tags) > 0 {
q := `select e.*
from entries e
inner join tags t
on e.id=t.entry_id
where
t.name in (?)
AND content like ?
order by updated desc`
q, args, err := sqlx.In(q, tags, query)
if err != nil {
return nil, err
}
err = db.Select(&entries, q, args...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} else { } else {
q := `select * from entries order by updated desc` q := `select e.*
err := db.Select(&entries, q) from entries e
where
content like ?
order by updated desc`
err := db.Select(&entries, q, query)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} }
for _, e := range entries { for _, e := range entries {
e.db = db e.db = db
e.Title = e.GenerateTitle() e.Title = e.GenerateTitle()
e.populateTags() e.populateTags()
} }
return entries, nil return entries, nil
} }
@ -277,3 +329,12 @@ func (e *Entry) Create() error {
tx.Commit() tx.Commit()
return nil return nil
} }
func (e *Entry) HasTag(tag string) bool {
for _, t := range e.Tags {
if strings.ToLower(tag) == strings.ToLower(t) {
return true
}
}
return false
}

View File

@ -1,2 +1,2 @@
//go:generate esc -o esc.go -prefix="frontend/dist" frontend/dist //go:generate esc -prefix frontend/dist -o esc.go frontend/dist
package main package main

View File

@ -33,6 +33,15 @@
components: { components: {
Error Error
}, },
created() {
if (!this.$store.state.key) {
let key = this.$cookies.get('key')
if (key) {
this.$store.commit('setKey', key)
return
}
}
},
methods: { methods: {
newFile: function() { newFile: function() {
this.$store.dispatch('newFile') this.$store.dispatch('newFile')

View File

@ -80,11 +80,6 @@ export default {
// because it has not been created yet when this guard is called! // because it has not been created yet when this guard is called!
next(vm => { next(vm => {
if (!vm.$store.state.key) { if (!vm.$store.state.key) {
let key = vm.$cookies.get('key')
if (key) {
vm.$store.commit('setKey', key)
return
}
vm.$router.push({name: "login", params: {returnTo: vm.$route.path}}) vm.$router.push({name: "login", params: {returnTo: vm.$route.path}})
} }
}) })

View File

@ -13,6 +13,18 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
func (web *Web) writeJSON(w http.ResponseWriter, code int, data interface{}) error {
w.Header().Set("content-type", "application/json")
resp, err := json.Marshal(data)
if err != nil {
w.WriteHeader(500)
return err
}
w.WriteHeader(code)
w.Write(resp)
return nil
}
func (web *Web) editEntry(w http.ResponseWriter, r *http.Request) { func (web *Web) editEntry(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
slug := vars["slug"] slug := vars["slug"]
@ -43,93 +55,87 @@ func (web *Web) editEntry(w http.ResponseWriter, r *http.Request) {
err = oldEntry.Update() err = oldEntry.Update()
if err != nil { if err != nil {
w.WriteHeader(500) web.writeJSON(w, 500, err)
fmt.Fprint(w, err)
return return
} }
resp, err := json.Marshal(oldEntry) web.writeJSON(w, 200, oldEntry)
}
func (web *Web) newAdocEntry(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
w.WriteHeader(500) web.writeJSON(w, 500, err)
fmt.Fprint(w, err) return
}
newEntry := entry.NewFromAdoc(web.db, string(body))
err = newEntry.Create()
if err != nil {
web.writeJSON(w, 500, err)
return return
} }
w.Header().Set("content-type", "application/json") web.writeJSON(w, 200, newEntry)
fmt.Fprint(w, string(resp))
} }
func (web *Web) newMarkdownEntry(w http.ResponseWriter, r *http.Request) { func (web *Web) newMarkdownEntry(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
w.WriteHeader(500) log.Error().Err(err).Msgf("could not read message body")
fmt.Fprint(w, err) web.writeJSON(w, 500, err)
return return
} }
newEntry := entry.NewFromMd(web.db, string(body)) newEntry := entry.NewFromMd(web.db, string(body))
err = newEntry.Create() err = newEntry.Create()
if err != nil { if err != nil {
w.WriteHeader(500) log.Error().Err(err).Msgf("could not create entry")
fmt.Fprint(w, err) web.writeJSON(w, 500, err)
return return
} }
resp, err := json.Marshal(newEntry) web.writeJSON(w, 200, newEntry)
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
w.Header().Set("content-type", "application/json")
fmt.Fprint(w, string(resp))
} }
func (web *Web) newEntry(w http.ResponseWriter, r *http.Request) { func (web *Web) newEntry(w http.ResponseWriter, r *http.Request) {
log.Debug().
Str("content-type", r.Header.Get("Content-Type")).
Msgf("newEntry")
dec := json.NewDecoder(r.Body) dec := json.NewDecoder(r.Body)
newEntry := entry.New(web.db) newEntry := entry.New(web.db)
err := dec.Decode(&newEntry) err := dec.Decode(&newEntry)
if err != nil { if err != nil {
w.WriteHeader(500) log.Error().Err(err).Msgf("could not decode entry")
fmt.Fprint(w, err) web.writeJSON(w, 500, err)
return return
} }
err = newEntry.Create() err = newEntry.Create()
if err != nil { if err != nil {
w.WriteHeader(500) log.Error().Err(err).Msgf("could not create raw entry")
fmt.Fprint(w, err) web.writeJSON(w, 500, err)
return return
} }
resp, err := json.Marshal(newEntry)
if err != nil { web.writeJSON(w, 200, newEntry)
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
w.Header().Set("content-type", "application/json")
fmt.Fprint(w, string(resp))
} }
func (web *Web) allEntries(w http.ResponseWriter, r *http.Request) { func (web *Web) allEntries(w http.ResponseWriter, r *http.Request) {
query := "" query := ""
tags := []string{}
if !web.AuthCheck(r) {
tags = append(tags, "public")
}
items, ok := r.URL.Query()["query"] items, ok := r.URL.Query()["query"]
if ok { if ok {
query = items[0] query = items[0]
} }
entries, err := entry.Search(web.db, query) entries, err := entry.SearchByTag(web.db, query, tags)
if err != nil { if err != nil {
w.WriteHeader(500) log.Error().Msgf("Error querying: %w", err)
fmt.Fprint(w, err) web.writeJSON(w, 500, err)
return return
} }
resp, err := json.Marshal(entries) web.writeJSON(w, 200, entries)
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
w.Header().Set("content-type", "application/json")
fmt.Fprint(w, string(resp))
} }
func (web *Web) getEntry(w http.ResponseWriter, r *http.Request) { func (web *Web) getEntry(w http.ResponseWriter, r *http.Request) {
@ -138,19 +144,16 @@ func (web *Web) getEntry(w http.ResponseWriter, r *http.Request) {
entry, err := entry.GetBySlug(web.db, slug) entry, err := entry.GetBySlug(web.db, slug)
if err != nil { if err != nil {
w.WriteHeader(500) web.writeJSON(w, 500, err)
fmt.Fprint(w, err)
return return
} }
resp, err := json.Marshal(entry) if !web.AuthCheck(r) && !entry.HasTag("public") {
if err != nil { web.writeJSON(w, 401, "not authorized")
w.WriteHeader(500)
fmt.Fprint(w, err)
return return
} }
w.Header().Set("content-type", "application/json")
fmt.Fprint(w, string(resp)) web.writeJSON(w, 200, entry)
} }
func (web *Web) removeEntry(w http.ResponseWriter, r *http.Request) { func (web *Web) removeEntry(w http.ResponseWriter, r *http.Request) {
@ -160,9 +163,8 @@ func (web *Web) removeEntry(w http.ResponseWriter, r *http.Request) {
err := entry.RemoveBySlug(web.db, slug) err := entry.RemoveBySlug(web.db, slug)
if err != nil { if err != nil {
log.Error().Msgf("Error deleting: %s", err) log.Error().Msgf("Error deleting: %s", err)
w.WriteHeader(500) web.writeJSON(w, 500, err)
fmt.Fprint(w, err)
return return
} }
w.WriteHeader(200) web.writeJSON(w, 200, "success")
} }

View File

@ -38,27 +38,42 @@ func New(addr string, db *db.Database, static http.FileSystem) *Web {
} }
type AuthMiddleware struct { type AuthMiddleware struct {
db *db.Database web *Web
db *db.Database
}
func NewAuthMiddleware(web *Web) AuthMiddleware {
return AuthMiddleware{
web: web,
db: web.db,
}
} }
func (aw *AuthMiddleware) Middleware(next http.Handler) http.Handler { func (aw *AuthMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("X-Auth-Key") if aw.web.AuthCheck(r) {
u, err := auth.GetByKey(aw.db, key) next.ServeHTTP(w, r)
if key == "" || err != nil {
w.WriteHeader(401)
fmt.Fprint(w, "invalid login")
return return
} }
log.Debug().Msgf("This shit is authed to user %s!", u.Name) w.WriteHeader(401)
next.ServeHTTP(w, r) fmt.Fprint(w, "invalid login")
}) })
} }
func (web *Web) AuthCheck(r *http.Request) bool {
key := r.Header.Get("X-Auth-Key")
u, err := auth.GetByKey(web.db, key)
if key == "" || err != nil {
return false
}
log.Debug().Msgf("This shit is authed to user %s!", u.Name)
return true
}
func (web *Web) routeSetup() http.Handler { func (web *Web) routeSetup() http.Handler {
r := mux.NewRouter() r := mux.NewRouter()
api := r.PathPrefix("/v1/").Subrouter() api := r.PathPrefix("/v1/").Subrouter()
auth := AuthMiddleware{web.db} auth := NewAuthMiddleware(web)
authedApi := r.PathPrefix("/v1/").Subrouter() authedApi := r.PathPrefix("/v1/").Subrouter()
authedApi.Use(auth.Middleware) authedApi.Use(auth.Middleware)
@ -73,11 +88,12 @@ func (web *Web) routeSetup() http.Handler {
// curl 'http://127.0.0.1:8080/v1/test' -X POST -H 'Accept: application/json, text/plain, */*' --compressed -H 'Content-Type: application/json;charset=utf-8' --data '{ "test": 1 }' // curl 'http://127.0.0.1:8080/v1/test' -X POST -H 'Accept: application/json, text/plain, */*' --compressed -H 'Content-Type: application/json;charset=utf-8' --data '{ "test": 1 }'
authedApi.HandleFunc("/entries", web.newEntry).Methods(http.MethodPost)
authedApi.HandleFunc("/entries", web.newEntry).Methods(http.MethodPost). authedApi.HandleFunc("/entries", web.newEntry).Methods(http.MethodPost).
HeadersRegexp("Content-Type", "application/(text|json).*") HeadersRegexp("Content-Type", "application/(text|json).*")
authedApi.HandleFunc("/entries", web.newMarkdownEntry).Methods(http.MethodPost). authedApi.HandleFunc("/entries", web.newMarkdownEntry).Methods(http.MethodPost).
HeadersRegexp("Content-Type", "application/markdown.*") HeadersRegexp("Content-Type", "application/markdown")
authedApi.HandleFunc("/entries", web.newAdocEntry).Methods(http.MethodPost).
HeadersRegexp("Content-Type", "application/asciidoc")
authedApi.HandleFunc("/entries/{slug}", web.removeEntry).Methods(http.MethodDelete) authedApi.HandleFunc("/entries/{slug}", web.removeEntry).Methods(http.MethodDelete)
authedApi.HandleFunc("/entries/{slug}", web.editEntry).Methods(http.MethodPut) authedApi.HandleFunc("/entries/{slug}", web.editEntry).Methods(http.MethodPut)