gist.go (2064B)
1 package handlers 2 3 import ( 4 "bytes" 5 "dkforest/pkg/database" 6 hutils "dkforest/pkg/web/handlers/utils" 7 "github.com/alecthomas/chroma/formatters/html" 8 "github.com/alecthomas/chroma/lexers" 9 "github.com/alecthomas/chroma/styles" 10 "github.com/labstack/echo" 11 "github.com/sirupsen/logrus" 12 "net/http" 13 "strings" 14 ) 15 16 func GistHandler(c echo.Context) error { 17 authUser := c.Get("authUser").(*database.User) 18 db := c.Get("database").(*database.DkfDB) 19 gistUUID := c.Param("gistUUID") 20 gist, err := db.GetGistByUUID(gistUUID) 21 if err != nil { 22 return c.Redirect(http.StatusFound, "/") 23 } 24 var data gistData 25 data.Gist = gist 26 27 if c.Request().Method == http.MethodPost { 28 29 btnSubmit := c.Request().PostFormValue("btn_submit") 30 if btnSubmit == "logout" { 31 hutils.DeleteGistCookie(c, gist.UUID) 32 return c.Redirect(http.StatusFound, "/") 33 34 } else if btnSubmit == "delete_gist" { 35 if gist.UserID == authUser.ID { 36 if gist.Password != "" { 37 hutils.DeleteGistCookie(c, gist.UUID) 38 } 39 if err := db.DB().Delete(&gist).Error; err != nil { 40 logrus.Error(err) 41 } 42 return c.Redirect(http.StatusFound, "/") 43 } 44 return c.Redirect(http.StatusFound, "/") 45 } 46 47 password := c.Request().PostFormValue("password") 48 hashedPassword := database.GetGistPasswordHash(password) 49 if hashedPassword != gist.Password { 50 data.Error = "Invalid password" 51 return c.Render(http.StatusOK, "gist-password", data) 52 } 53 hutils.CreateGistCookie(c, gist.UUID, hashedPassword) 54 return c.Redirect(http.StatusFound, "/gists/"+gist.UUID) 55 } 56 57 if !gist.HasAccess(c) { 58 return c.Render(http.StatusOK, "gist-password", data) 59 } 60 61 if strings.HasSuffix(gist.Name, ".go") { 62 lexer := lexers.Match(gist.Name) 63 style := styles.Get("monokai") 64 formatter := html.New(html.Standalone(true), html.TabWidth(4), html.WithLineNumbers(true), html.LineNumbersInTable(true)) 65 iterator, _ := lexer.Tokenise(nil, gist.Content) 66 buf := bytes.Buffer{} 67 _ = formatter.Format(&buf, style, iterator) 68 data.Highlighted = buf.String() 69 } 70 71 return c.Render(http.StatusOK, "gist", data) 72 }