id check implemented

This commit is contained in:
Christian Müller
2017-09-24 11:13:38 +02:00
parent 01d4f8b8f8
commit ea687d2faa
3 changed files with 23 additions and 4 deletions
+7 -1
View File
@@ -31,6 +31,12 @@ var (
errorBadRequest = errors.New("password is empty")
)
func statusNote(code int) *Note {
n := &Note{Text: "# " + statuses[code]}
n.prepare()
return n
}
func (n *Note) prepare() {
fstLine := rexpNewLine.Split(n.Text, -1)[0]
maxLength := 25
@@ -54,7 +60,7 @@ func md2html(c echo.Context, name string) (*Note, int) {
if err != nil {
c.Logger().Errorf("couldn't open markdown page %s: %v", path, err)
code := http.StatusServiceUnavailable
return &Note{Title: statuses[code], Text: "# " + statuses[code]}, code
return statusNote(code), code
}
c.Logger().Debugf("rendering markdown page %s", name)
return &Note{Title: name, Content: mdTmplHTML(mdContent)}, http.StatusOK
+4 -2
View File
@@ -70,7 +70,6 @@ func main() {
e.GET("/:id", func(c echo.Context) error {
n, code := load(c, db)
defer incViews(n)
n.prepare()
if fraudelent(n) {
n.Ads = mdTmplHTML(ads)
}
@@ -81,7 +80,10 @@ func main() {
e.GET("/:id/export", func(c echo.Context) error {
n, code := load(c, db)
c.Logger().Debugf("/%s/export requested; response code: %d", n.ID, code)
return c.String(code, n.Text)
if code == http.StatusOK {
return c.String(code, n.Text)
}
return c.Render(code, "Note", n)
})
e.GET("/:id/stats", func(c echo.Context) error {
+12 -1
View File
@@ -9,6 +9,7 @@ import (
"html/template"
"math/rand"
"net/http"
"regexp"
"strings"
"time"
@@ -21,6 +22,8 @@ func init() {
const idLength = 5
var rexpNoteID = regexp.MustCompile("[a-z0-9]+")
type Note struct {
ID, Title, Text, Password, DeprecatedPassword string
Published, Edited time.Time
@@ -39,6 +42,9 @@ func save(c echo.Context, db *sql.DB, n *Note) (*Note, error) {
if n.ID == "" {
return insert(c, db, n)
}
if !rexpNoteID.Match([]byte(n.ID)) {
return nil, errorBadRequest
}
return update(c, db, n)
}
@@ -115,6 +121,10 @@ func randId() string {
func load(c echo.Context, db *sql.DB) (*Note, int) {
q := c.Param("id")
if !rexpNoteID.Match([]byte(q)) {
code := http.StatusNotFound
return statusNote(code), code
}
c.Logger().Debugf("loading note %s", q)
stmt, _ := db.Prepare("select * from notes where id = ?")
defer stmt.Close()
@@ -125,7 +135,7 @@ func load(c echo.Context, db *sql.DB) (*Note, int) {
var views int
if err := row.Scan(&id, &text, &published, &editedVal, &password, &views); err != nil {
code := http.StatusNotFound
return &Note{Title: statuses[code], Text: "# " + statuses[code]}, code
return statusNote(code), code
}
n := &Note{
ID: id,
@@ -136,5 +146,6 @@ func load(c echo.Context, db *sql.DB) (*Note, int) {
if editedVal != nil {
n.Edited = editedVal.(time.Time)
}
n.prepare()
return n, http.StatusOK
}