Compare commits
16 Commits
blog-cleanup
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| eb825b3f85 | |||
| 673e9918d9 | |||
| 2a16aca6ae | |||
| 338eb84469 | |||
| 243fa03af0 | |||
| 3e1078efec | |||
| 24b99d7d1e | |||
| 11a39a53cb | |||
| cd871c7217 | |||
| fc71473177 | |||
| 1694169177 | |||
| b5d582e797 | |||
| 1229be1cee | |||
| aa180ae67e | |||
| 9a492497c8 | |||
| 198c4ff749 |
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
@@ -38,8 +37,7 @@ const (
|
||||
{{end}}
|
||||
</select>
|
||||
</p>
|
||||
<div id="editor" hx-on::after-settle="blogEditorResize()">{{.Editor}}</div>
|
||||
`
|
||||
<div id="editor" hx-on::after-settle="blogEditorResize()">{{.Editor}}</div>`
|
||||
editorForm = `
|
||||
<form id="editorForm" hx-post="/editor/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||
<input name="id" type="hidden" value="{{.Blog.ID}}"></input>
|
||||
@@ -52,8 +50,7 @@ const (
|
||||
<input id="titleInput" name="title" value="{{.Blog.Title}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||
<textarea id="blogEditor" name="blog" oninput="blogEditorResize()">{{.Blog.RawBlog}}</textarea>
|
||||
<div id="formResult">{{.Result}}</div>
|
||||
<p style="margin-right:0px;">
|
||||
<button class="formButton" type="submit">{{if eq .Blog.ID ""}}Create{{else}}Update{{end}}</button>
|
||||
<p style="margin-right:0px;display:flex;">
|
||||
<button class="formButton"
|
||||
hx-get="/editor/edit"
|
||||
hx-include="#blogSelect"
|
||||
@@ -61,6 +58,16 @@ const (
|
||||
hx-confirm="Undo all your changes??">
|
||||
Cancel
|
||||
</button>
|
||||
<span style="flex-grow:1;"></span>
|
||||
<button class="formButton"
|
||||
hx-delete="/editor/edit"
|
||||
hx-include="#blogSelect"
|
||||
hx-target="#editor"
|
||||
hx-confirm="Delete Page????">
|
||||
Delete
|
||||
</button>
|
||||
<span style="flex-grow:1;"></span>
|
||||
<button class="formButton" type="submit">{{if eq .Blog.ID ""}}Create{{else}}Update{{end}}</button>
|
||||
<p>
|
||||
</form>`
|
||||
)
|
||||
@@ -81,11 +88,12 @@ func trueLoginRequest(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
u, err := back.TryLogin(r.Context(), r.FormValue("username"), r.FormValue("password"))
|
||||
if err != nil {
|
||||
if err == backend.ErrLoginTimeout {
|
||||
sendContent(w, r, fmt.Sprint("<p>Timed out for", time.Unix(u.Timeout, 0).Sub(time.Now()), "</p>"), "", "")
|
||||
} else if err == backend.ErrLoginIncorrect {
|
||||
switch err {
|
||||
case backend.ErrLoginTimeout:
|
||||
sendContent(w, r, fmt.Sprint("<p>Timed out for", time.Until(time.Unix(u.Timeout, 0)), "</p>"), "", "")
|
||||
case backend.ErrLoginIncorrect:
|
||||
sendContent(w, r, "<p>Username or password invalid</p>", "", "")
|
||||
} else {
|
||||
default:
|
||||
log.Println("error trying to login:", err)
|
||||
sendContent(w, r, "<p>Server error</p>", "", "")
|
||||
}
|
||||
@@ -211,7 +219,7 @@ func editorPost(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if newBlog.ID == "" {
|
||||
newBlog.ID = strings.TrimSpace(strings.ToLower(strings.ReplaceAll(newBlog.ID, " ", "-")))
|
||||
newBlog.ID = newBlog.IDFromTitle()
|
||||
if blogApp.Contains(r.Context(), newBlog.ID) {
|
||||
sendContent(w, r, "<p>Title is not unique!</p>", "", "")
|
||||
return
|
||||
@@ -273,6 +281,43 @@ func editorPost(w http.ResponseWriter, r *http.Request) {
|
||||
pageTmpl.Execute(w, pageTmplStruct{Selected: newBlog.ID, Blogs: blogs, Editor: newForm.String()})
|
||||
}
|
||||
|
||||
func editorDelete(w http.ResponseWriter, r *http.Request) {
|
||||
usr := verifyEditorCookie(r)
|
||||
if usr == nil {
|
||||
editorRedirect(w, r, "/login")
|
||||
return
|
||||
}
|
||||
if usr.Perm["blog"] != "admin" {
|
||||
sendContent(w, r, "<p>You are not allowed to perform this action. Sorry, not sorry.</p>", "", "")
|
||||
return
|
||||
}
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
sendContent(w, r, "<p>Bad request</p>", "", "")
|
||||
return
|
||||
}
|
||||
id := r.FormValue("id")
|
||||
if id == "" {
|
||||
sendContent(w, r, "<p>Invalid ID</p>", "", "")
|
||||
return
|
||||
}
|
||||
err = blogApp.RemoveBlog(r.Context(), id)
|
||||
if err != nil {
|
||||
log.Println("error updating blog:", err)
|
||||
sendContent(w, r, "<p>Server error removing blog</p>", "", "")
|
||||
return
|
||||
}
|
||||
var blogs []blog.BlogListResult
|
||||
blogs, err = blogApp.AllBlogsList(r.Context())
|
||||
if err != nil {
|
||||
log.Println("error getting all blogs list:", err)
|
||||
sendContent(w, r, "<p>Updated!</p>", "", "")
|
||||
return
|
||||
}
|
||||
w.Header().Set("HX-Retarget", "#content")
|
||||
pageTmpl.Execute(w, pageTmplStruct{Selected: "", Blogs: blogs, Editor: "<p>Blog removed!</p>"})
|
||||
}
|
||||
|
||||
func verifyEditorCookie(r *http.Request) *backend.User {
|
||||
authCookie, err := r.Cookie("blogAuthToken")
|
||||
if err != nil {
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
module github.com/CalebQ42/darkstorm-server
|
||||
|
||||
go 1.23.0
|
||||
go 1.23.4
|
||||
|
||||
require (
|
||||
github.com/CalebQ42/bbConvert v1.0.2
|
||||
github.com/CalebQ42/bbConvert v1.0.7
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/lithammer/shortuuid/v3 v3.0.7
|
||||
go.mongodb.org/mongo-driver v1.15.1
|
||||
golang.org/x/crypto v0.24.0
|
||||
go.mongodb.org/mongo-driver v1.17.1
|
||||
golang.org/x/crypto v0.31.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dlclark/regexp2 v1.11.5-0.20240806004527-5bbbed8ea10b // indirect
|
||||
github.com/golang/snappy v0.0.1 // indirect
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/klauspost/compress v1.13.6 // indirect
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/montanaflynn/stats v0.7.1 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.2 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
golang.org/x/sys v0.21.0 // indirect
|
||||
golang.org/x/text v0.16.0 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,62 +1,62 @@
|
||||
github.com/CalebQ42/bbConvert v1.0.2 h1:N0+q7Kw3Ge2m117jbYp1DyrCa7zUuBOpyBfhcuphjz8=
|
||||
github.com/CalebQ42/bbConvert v1.0.2/go.mod h1:gV0gaDhzuIwWqX9O1F8qu7tFXz50DnGQOnq56qrtO3A=
|
||||
github.com/CalebQ42/bbConvert v1.0.7 h1:dJh6S7lliotdQvcXrMbtBo4p8Afwe295/XvnKP0oj7E=
|
||||
github.com/CalebQ42/bbConvert v1.0.7/go.mod h1:UBFqtgZWSm9v/2Kl4NJDmgdSzEBZDkgON3QKoVOBC6Q=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.5-0.20240806004527-5bbbed8ea10b h1:AJKOdc+1fRSJ0/75Jty1npvxUUD0y7hQDg15LMAHhyU=
|
||||
github.com/dlclark/regexp2 v1.11.5-0.20240806004527-5bbbed8ea10b/go.mod h1:YvCrhrh/qlds8EhFKPtJprdXn5fWBllSw1qo99dZyiQ=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJVuvyJQQ8=
|
||||
github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
|
||||
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
|
||||
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.mongodb.org/mongo-driver v1.15.1 h1:l+RvoUOoMXFmADTLfYDm7On9dRm7p4T80/lEQM+r7HU=
|
||||
go.mongodb.org/mongo-driver v1.15.1/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c=
|
||||
go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM=
|
||||
go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
|
||||
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
|
||||
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
|
||||
@@ -49,6 +49,7 @@ func (b *Backend) countLog(w http.ResponseWriter, r *http.Request) {
|
||||
ap := b.GetApp(hdr.Key)
|
||||
count := ap.CountTable()
|
||||
if count == nil {
|
||||
log.Println(ap.AppID(), "misconfigured: count table is nil.")
|
||||
ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server Misconfigured")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -112,6 +112,7 @@ func (b *Backend) managementDeleteCrash(w http.ResponseWriter, r *http.Request)
|
||||
func (b *Backend) actualCrashDelete(ctx context.Context, w http.ResponseWriter, ap App, crashID string) {
|
||||
crash := ap.CrashTable()
|
||||
if crash == nil {
|
||||
log.Println(ap.AppID(), "misconfigured: crash table is nil.")
|
||||
ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server Misconfigured")
|
||||
return
|
||||
}
|
||||
@@ -166,6 +167,7 @@ func (b *Backend) managementArchiveCrash(w http.ResponseWriter, r *http.Request)
|
||||
func (b *Backend) actualCrashArchive(ctx context.Context, w http.ResponseWriter, ap App, toArchive ArchivedCrash) {
|
||||
crash := ap.CrashTable()
|
||||
if crash == nil {
|
||||
log.Println(ap.AppID(), "misconfigured: crash table is nil.")
|
||||
ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server Misconfigured")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ var robotEmbed embed.FS
|
||||
// A simple backend that handles user authentication, user count, and crash reports.
|
||||
type Backend struct {
|
||||
userTable Table[User]
|
||||
keyTable Table[ApiKey]
|
||||
keyTable Table[APIKey]
|
||||
m *http.ServeMux
|
||||
apps map[string]App
|
||||
managementKeyID string
|
||||
@@ -29,7 +29,7 @@ type Backend struct {
|
||||
}
|
||||
|
||||
// Create a new Backend with the given apps. keyTable must be specified.
|
||||
func NewBackend(keyTable Table[ApiKey], apps ...App) (*Backend, error) {
|
||||
func NewBackend(keyTable Table[APIKey], apps ...App) (*Backend, error) {
|
||||
b := &Backend{
|
||||
keyTable: keyTable,
|
||||
m: &http.ServeMux{},
|
||||
@@ -75,7 +75,13 @@ func NewBackend(keyTable Table[ApiKey], apps ...App) (*Backend, error) {
|
||||
}
|
||||
|
||||
func (b *Backend) cleanupLoop() {
|
||||
b.cleanup()
|
||||
for range time.Tick(24 * time.Hour) {
|
||||
b.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Backend) cleanup() {
|
||||
old := getDate(time.Now().Add(-30 * 24 * time.Hour))
|
||||
var err error
|
||||
for _, a := range b.apps {
|
||||
@@ -90,7 +96,6 @@ func (b *Backend) cleanupLoop() {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Enable CORS for with the given cors address
|
||||
func (b *Backend) AddCorsAddress(corsAddr string) {
|
||||
@@ -138,7 +143,7 @@ func (b *Backend) HandleFunc(pattern string, h http.HandlerFunc) {
|
||||
}
|
||||
|
||||
// Try to get the App associated with the given ApiKey. Returns nil if not found.
|
||||
func (b *Backend) GetApp(a *ApiKey) App {
|
||||
func (b *Backend) GetApp(a *APIKey) App {
|
||||
return b.apps[a.AppID]
|
||||
}
|
||||
|
||||
@@ -10,11 +10,11 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrApiKeyUnauthorized = errors.New("api key present but invalid")
|
||||
ErrAPIKeyUnauthorized = errors.New("api key present but invalid")
|
||||
ErrTokenUnauthorized = errors.New("token present but invalid")
|
||||
)
|
||||
|
||||
type ApiKey struct {
|
||||
type APIKey struct {
|
||||
Perm map[string]bool `json:"perm" bson:"perm"`
|
||||
ID string `json:"id" bson:"_id" valkey:",key"`
|
||||
AppID string `json:"appID" bson:"appID"`
|
||||
@@ -22,13 +22,13 @@ type ApiKey struct {
|
||||
AllowedOrigins []string `json:"allowedOrigins" bson:"allowedOrigins"`
|
||||
}
|
||||
|
||||
func (k ApiKey) GetID() string {
|
||||
func (k APIKey) GetID() string {
|
||||
return k.ID
|
||||
}
|
||||
|
||||
type ParsedHeader struct {
|
||||
User *ReqestUser
|
||||
Key *ApiKey
|
||||
Key *APIKey
|
||||
}
|
||||
|
||||
// Parses the X-API-Key and Authorization headers. If the API Key provided but invalid (either due to expiring or isn't found), ErrApiKeyUnauthorized is returned.
|
||||
@@ -41,24 +41,24 @@ func (b *Backend) ParseHeader(r *http.Request) (*ParsedHeader, error) {
|
||||
if key != "" {
|
||||
apiKey, err := b.keyTable.Get(r.Context(), key)
|
||||
if err == ErrNotFound {
|
||||
return nil, ErrApiKeyUnauthorized
|
||||
return nil, ErrAPIKeyUnauthorized
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if apiKey.Death > 0 && time.Unix(apiKey.Death, 0).Before(time.Now()) {
|
||||
return nil, ErrApiKeyUnauthorized
|
||||
return nil, ErrAPIKeyUnauthorized
|
||||
}
|
||||
out.Key = &apiKey
|
||||
} else {
|
||||
fmt.Println("origin:", r.Header.Get("origin"))
|
||||
keys, err := b.keyTable.Find(r.Context(), map[string]any{"allowedOrigins": r.Header.Get("origin")})
|
||||
if err == ErrNotFound {
|
||||
return nil, ErrApiKeyUnauthorized
|
||||
return nil, ErrAPIKeyUnauthorized
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if keys[0].Death > 0 && time.Unix(keys[0].Death, 0).Before(time.Now()) {
|
||||
return nil, ErrApiKeyUnauthorized
|
||||
return nil, ErrAPIKeyUnauthorized
|
||||
}
|
||||
out.Key = &keys[0]
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func (b *Backend) ParseHeader(r *http.Request) (*ParsedHeader, error) {
|
||||
func (b *Backend) VerifyHeader(w http.ResponseWriter, r *http.Request, keyPerm string, allowManagementKey bool) (*ParsedHeader, error) {
|
||||
hdr, err := b.ParseHeader(r)
|
||||
if hdr == nil || hdr.Key == nil {
|
||||
if err == ErrApiKeyUnauthorized {
|
||||
if err == ErrAPIKeyUnauthorized {
|
||||
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -301,13 +301,14 @@ func (b *Backend) login(w http.ResponseWriter, r *http.Request) {
|
||||
if err == nil {
|
||||
ret.Token, err = b.GenerateJWT(u.ToReqUser())
|
||||
if err != nil {
|
||||
log.Println("error generating JWT token:", err)
|
||||
ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err == ErrLoginTimeout {
|
||||
ret.Error = "timeout"
|
||||
ret.ErrorMsg = fmt.Sprint("Timed out for", time.Unix(u.Timeout, 0).Sub(time.Now()), "seconds")
|
||||
ret.ErrorMsg = fmt.Sprint("Timed out for", time.Until(time.Unix(u.Timeout, 0)), "seconds")
|
||||
ret.Timeout = u.Timeout
|
||||
} else {
|
||||
ret.Error = "incorrect"
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
# Blog module
|
||||
|
||||
A simple blog module for darkstorm-backend.
|
||||
|
||||
## Requests
|
||||
|
||||
### Author info
|
||||
|
||||
#### Get author info
|
||||
|
||||
> GET /author/{authorID}
|
||||
|
||||
```json
|
||||
{
|
||||
id: "authorID",
|
||||
name: "author name",
|
||||
about: "about",
|
||||
picurl: "picture URL"
|
||||
}
|
||||
```
|
||||
|
||||
#### Update author info
|
||||
|
||||
> POST /author/{authorID}
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
name: "author name",
|
||||
about: "about",
|
||||
picurl: "picture url"
|
||||
}
|
||||
```
|
||||
|
||||
#### Add Author info
|
||||
|
||||
> POST /author
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
name: "author name",
|
||||
about: "about",
|
||||
picurl: "picture URL"
|
||||
}
|
||||
```
|
||||
|
||||
### Blog
|
||||
|
||||
#### Specific blog
|
||||
|
||||
> GET /blog/{blogID}
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
id: "blogID",
|
||||
staticPage: false, // static pages don't show up alongside other blog pages.
|
||||
createTime: 0, // creation time in Unix format
|
||||
updateTime: 0, // last update time in Unix format
|
||||
author: "authorID",
|
||||
favicon: "favicon url",
|
||||
title: "blog title",
|
||||
blog: "blog", // blog will have been converted to HTML
|
||||
}
|
||||
```
|
||||
|
||||
#### Create blog
|
||||
|
||||
Request:
|
||||
|
||||
> POST /blog
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
favicon: "favicon url",
|
||||
title: "blog title",
|
||||
blog: "blog", // blog will have been converted to HTML
|
||||
}
|
||||
```
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
id: "blogID"
|
||||
}
|
||||
```
|
||||
|
||||
#### Update blog
|
||||
|
||||
Request:
|
||||
|
||||
> POST /blog/{blogID}
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
favicon: "new icon",
|
||||
title: "new title",
|
||||
blog: "new blog content"
|
||||
}
|
||||
```
|
||||
|
||||
#### Latest blogs
|
||||
|
||||
> GET /blog?page=0
|
||||
|
||||
Will return up to 5 blogs. `page` query is optional (implies 0 if not set).
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
num: 1, // Number of returned results, returns up to 5 results
|
||||
blogs: [
|
||||
{
|
||||
id: "blogID",
|
||||
createTime: 0, // creation time in Unix format
|
||||
updateTime: 0, // last update time in Unix format
|
||||
author: "authorID",
|
||||
favicon: "favicon url",
|
||||
title: "blog title",
|
||||
blog: "blog", // blog will have been converted to HTML
|
||||
}
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Blog List
|
||||
|
||||
> GET /blog/list?page=0
|
||||
|
||||
Will return up to 50 IDs. `page` query is optional (implies 0 if not set).
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
num: 1, // Number of returned results, returns up to 50 results
|
||||
blogList: [
|
||||
{
|
||||
id: "blogID",
|
||||
createTime: 0, // Unix format
|
||||
},
|
||||
{
|
||||
id: "blogID",
|
||||
createTime: 0, // Unix format
|
||||
},
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Portfolio
|
||||
|
||||
#### Get Projects
|
||||
|
||||
> GET: /portfolio?lang=go
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
title: "Darkstorm Server",
|
||||
order: 0,
|
||||
repository: "https://github.com/CalebQ42/darkstorm-server",
|
||||
description: "The backend that runs runs my website and APIs",
|
||||
technologies: [ // May be empty
|
||||
"MongoDB",
|
||||
"RESTful API"
|
||||
],
|
||||
language: [
|
||||
{
|
||||
language: "go",
|
||||
dates: "September 2021"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
@@ -1,164 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
const authorInfo = `
|
||||
<table><tr>
|
||||
<td><img src="%v" alt="%v" class='author-pic'></td>
|
||||
<td><h3 class="author-title">%v</h3>%v</td>
|
||||
</tr></table>`
|
||||
|
||||
type Author struct {
|
||||
ID string `json:"id" bson:"_id"`
|
||||
Name string `json:"name" bson:"name"`
|
||||
About string `json:"about" bson:"about"`
|
||||
PicURL string `json:"picurl" bson:"picurl"`
|
||||
}
|
||||
|
||||
func (a Author) HTML() string {
|
||||
return fmt.Sprintf(authorInfo, a.PicURL, a.Name+"'s profile picture", a.Name, a.About)
|
||||
}
|
||||
|
||||
func (b *BlogApp) AboutMe(ctx context.Context) (*Author, error) {
|
||||
res := b.authCol.FindOne(ctx, bson.M{"_id": "caleb_gardner"})
|
||||
if res.Err() != nil {
|
||||
log.Println("error getting about me:", res.Err())
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
var aboutMe Author
|
||||
err := res.Decode(&aboutMe)
|
||||
if err != nil {
|
||||
log.Println("error decoding about me:", res)
|
||||
return nil, err
|
||||
}
|
||||
return &aboutMe, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||
res := b.authCol.FindOne(r.Context(), r.PathValue("authorID"))
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found")
|
||||
return
|
||||
} else if res.Err() != nil {
|
||||
log.Println("error getting author info:", res.Err())
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
var auth Author
|
||||
err := res.Decode(&auth)
|
||||
if err != nil {
|
||||
log.Println("error decoding author info:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(auth)
|
||||
}
|
||||
|
||||
func (b *BlogApp) addAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
var newAuth Author
|
||||
err = json.NewDecoder(r.Body).Decode(&newAuth)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
||||
return
|
||||
}
|
||||
for i := 1; ; i++ {
|
||||
newID := strings.ReplaceAll(newAuth.Name, " ", "-")
|
||||
if i != 1 {
|
||||
newID += strconv.Itoa(i)
|
||||
}
|
||||
collisionCheck := b.authCol.FindOne(r.Context(), bson.M{"name": newAuth.Name})
|
||||
if collisionCheck.Err() == mongo.ErrNoDocuments {
|
||||
newAuth.ID = newID
|
||||
break
|
||||
} else if collisionCheck.Err() != nil {
|
||||
log.Println("error checking for new author ID collisions:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
}
|
||||
_, err = b.authCol.InsertOne(r.Context(), newAuth)
|
||||
if err != nil {
|
||||
log.Println("error inserting new author:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
func (b *BlogApp) updateAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
var rawUpd map[string]string
|
||||
err = json.NewDecoder(r.Body).Decode(&rawUpd)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
||||
return
|
||||
}
|
||||
actlUpd := make(map[string]string)
|
||||
if rawUpd["name"] != "" {
|
||||
actlUpd["name"] = rawUpd["name"]
|
||||
}
|
||||
if rawUpd["about"] != "" {
|
||||
actlUpd["about"] = rawUpd["about"]
|
||||
}
|
||||
if rawUpd["picurl"] != "" {
|
||||
actlUpd["picurl"] = rawUpd["picurl"]
|
||||
}
|
||||
res, err := b.authCol.UpdateByID(r.Context(), r.PathValue("authorID"), actlUpd)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||
} else {
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if res.MatchedCount == 0 {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
@@ -1,387 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
const (
|
||||
blogTitle = "<h1 class='blog-title'><a hx-push-url='true' hx-get='/%v' hx-target='#content' href='/%v' style='text-decoration:none'>%v</a></h1>"
|
||||
blogAuthor = "<h4 class='blog-author'><i><b>By %v</b></i></h4>"
|
||||
blogCreate = "<h5 class='blog-time'><i>Written on: %v</i></h5>"
|
||||
blogMain = "<div class='blog'>%v</div>"
|
||||
)
|
||||
|
||||
type Blog struct {
|
||||
ID string `json:"id" bson:"_id"`
|
||||
Author string `json:"author" bson:"author"`
|
||||
Favicon string `json:"favicon" bson:"favicon"`
|
||||
Title string `json:"title" bson:"title"`
|
||||
RawBlog string `json:"blog" bson:"blog"`
|
||||
HTMLBlog string `json:"-" bson:"-"`
|
||||
StaticPage bool `json:"staticPage" bson:"staticPage"`
|
||||
Draft bool `json:"draft" bson:"draft"`
|
||||
CreateTime int64 `json:"createTime" bson:"createTime"`
|
||||
UpdateTime int64 `json:"updateTime" bson:"updateTime"`
|
||||
}
|
||||
|
||||
func (b *Blog) HTMX(blogApp *BlogApp, ctx context.Context) string {
|
||||
if b.StaticPage {
|
||||
return b.RawBlog
|
||||
}
|
||||
out := fmt.Sprintf(blogTitle, b.ID, b.ID, b.Title)
|
||||
auth, err := blogApp.GetAuthor(ctx, b)
|
||||
if err == nil {
|
||||
out += fmt.Sprintf(blogAuthor, auth.Name)
|
||||
} else {
|
||||
out += fmt.Sprintf(blogAuthor, "unknown")
|
||||
}
|
||||
cTime := time.Unix(b.CreateTime, 0).Format(time.DateOnly)
|
||||
if b.UpdateTime > b.CreateTime {
|
||||
out += fmt.Sprintf(blogCreate, cTime+"; Last updated on: "+time.Unix(b.UpdateTime, 0).Format(time.DateOnly))
|
||||
} else {
|
||||
out += fmt.Sprintf(blogCreate, cTime)
|
||||
}
|
||||
out += fmt.Sprintf(blogMain, b.HTMLBlog)
|
||||
if err == nil {
|
||||
out += "<h2 class='blog-author-info'>About the author:</h2>" + auth.HTML()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *BlogApp) ConvertBlog(blog *Blog) {
|
||||
if !blog.StaticPage {
|
||||
blog.HTMLBlog = b.conv.HTMLConvert(blog.RawBlog)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BlogApp) GetAuthor(ctx context.Context, blog *Blog) (*Author, error) {
|
||||
res := b.authCol.FindOne(ctx, bson.M{"_id": blog.Author})
|
||||
if res.Err() != nil {
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
var author Author
|
||||
err := res.Decode(&author)
|
||||
return &author, err
|
||||
}
|
||||
|
||||
func (b *BlogApp) Blog(ctx context.Context, ID string) (*Blog, error) {
|
||||
b.cacheMutex.RLock()
|
||||
blog, has := b.blogCache[ID]
|
||||
b.cacheMutex.RUnlock()
|
||||
if has {
|
||||
return &blog, nil
|
||||
}
|
||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID, "draft": false})
|
||||
if res.Err() != nil {
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
err := res.Decode(&blog)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.ConvertBlog(&blog)
|
||||
b.cacheMutex.Lock()
|
||||
b.blogCache[ID] = blog
|
||||
b.cacheMutex.Unlock()
|
||||
go b.CleanCache(ID)
|
||||
return &blog, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) AnyBlog(ctx context.Context, ID string) (*Blog, error) {
|
||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
||||
if res.Err() != nil {
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
var blog Blog
|
||||
err := res.Decode(&blog)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.ConvertBlog(&blog)
|
||||
return &blog, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) Contains(ctx context.Context, ID string) bool {
|
||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
||||
return res.Err() == nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) CleanCache(ID string) {
|
||||
time.Sleep(5 * time.Minute)
|
||||
b.cacheMutex.Lock()
|
||||
delete(b.blogCache, ID)
|
||||
b.cacheMutex.Unlock()
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqBlog(w http.ResponseWriter, r *http.Request) {
|
||||
blogID := r.PathValue("blogID")
|
||||
if blogID == "" {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Must provide a blogID")
|
||||
return
|
||||
}
|
||||
blog, err := b.Blog(r.Context(), blogID)
|
||||
if err != nil {
|
||||
if err == backend.ErrNotFound {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Not blog found with the given ID")
|
||||
return
|
||||
}
|
||||
log.Println("error getting blog:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Hx-Request") == "true" {
|
||||
w.Write([]byte(blog.HTMX(b, r.Context())))
|
||||
} else {
|
||||
json.NewEncoder(w).Encode(blog)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BlogApp) createBlog(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
var newBlog Blog
|
||||
err = json.NewDecoder(r.Body).Decode(&newBlog)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||
return
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
tim := time.Now().Unix()
|
||||
newBlog.ID = id.String()
|
||||
newBlog.CreateTime = tim
|
||||
newBlog.UpdateTime = tim
|
||||
newBlog.Author = hdr.User.Username
|
||||
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||
if err != nil {
|
||||
log.Println("error when inserting new blog:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
|
||||
}
|
||||
|
||||
func (b *BlogApp) updateBlog(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if r.PathValue("blogID") == "" {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||
return
|
||||
}
|
||||
var reqUpdRaw map[string]string
|
||||
err = json.NewDecoder(r.Body).Decode(&reqUpdRaw)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||
return
|
||||
}
|
||||
reqUpd := bson.M{}
|
||||
if fav, ok := reqUpdRaw["favicon"]; ok && fav != "" {
|
||||
reqUpd["favicon"] = fav
|
||||
}
|
||||
if titl, ok := reqUpdRaw["title"]; ok && titl != "" {
|
||||
reqUpd["title"] = titl
|
||||
}
|
||||
if blog, ok := reqUpdRaw["blog"]; ok && blog != "" {
|
||||
reqUpd["blog"] = blog
|
||||
}
|
||||
reqUpd["updateTime"] = time.Now().Unix()
|
||||
res, err := b.blogCol.UpdateByID(r.Context(), r.PathValue("blogID"), reqUpd)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||
} else {
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if res.MatchedCount == 0 {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
func (b *BlogApp) InsertBlog(ctx context.Context, blog Blog) error {
|
||||
_, err := b.blogCol.InsertOne(ctx, blog)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *BlogApp) UpdateBlog(ctx context.Context, ID string, updates bson.M) error {
|
||||
_, err := b.blogCol.UpdateByID(ctx, ID, bson.M{"$set": updates})
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *BlogApp) LatestBlogs(ctx context.Context, page int64) ([]*Blog, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
||||
SetSort(bson.M{"createTime": -1}).
|
||||
SetLimit(5).
|
||||
SetSkip(page*5))
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []*Blog
|
||||
err = res.All(ctx, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range out {
|
||||
b.ConvertBlog(out[i])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqLatestBlogs(w http.ResponseWriter, r *http.Request) {
|
||||
var page int
|
||||
var err error
|
||||
pagQuery := r.URL.Query().Get("page")
|
||||
if pagQuery != "" {
|
||||
page, err = strconv.Atoi(pagQuery)
|
||||
if err != nil {
|
||||
page = 0
|
||||
}
|
||||
}
|
||||
blogs, err := b.LatestBlogs(r.Context(), int64(page))
|
||||
if err != nil && err != backend.ErrNotFound {
|
||||
log.Println("error getting latest blogs:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
var ret struct {
|
||||
Blogs []*Blog `json:"blogs"`
|
||||
Num int `json:"num"`
|
||||
}
|
||||
ret.Num = len(blogs)
|
||||
ret.Blogs = blogs
|
||||
json.NewEncoder(w).Encode(ret)
|
||||
}
|
||||
|
||||
type BlogListResult struct {
|
||||
ID string `json:"id" bson:"_id"`
|
||||
Title string `json:"title" bson:"title"`
|
||||
CreateTime int `json:"createTime" bson:"createTime"`
|
||||
}
|
||||
|
||||
func (b BlogListResult) HTMX() string {
|
||||
return "<a class='blog-list-item' href='https://darkstorm.tech/" +
|
||||
b.ID +
|
||||
"' hx-push-url='true' hx-target='#content' hx-get='/" +
|
||||
b.ID +
|
||||
"'>" + b.Title + "</a>"
|
||||
}
|
||||
|
||||
func (b *BlogApp) BlogList(ctx context.Context, page int64) ([]BlogListResult, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
||||
SetSort(bson.M{"createTime": -1}).
|
||||
SetLimit(50).
|
||||
SetSkip(page*50))
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []BlogListResult
|
||||
err = res.All(ctx, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) AllBlogsList(ctx context.Context) ([]BlogListResult, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{}, options.Find().
|
||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
||||
SetSort(bson.M{"createTime": -1}))
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []BlogListResult
|
||||
err = res.All(ctx, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqBlogList(w http.ResponseWriter, r *http.Request) {
|
||||
var page int
|
||||
var err error
|
||||
pagQuery := r.URL.Query().Get("page")
|
||||
if pagQuery != "" {
|
||||
page, err = strconv.Atoi(pagQuery)
|
||||
if err != nil {
|
||||
page = 0
|
||||
}
|
||||
}
|
||||
blogList, err := b.BlogList(r.Context(), int64(page))
|
||||
if err != nil && err != backend.ErrNotFound {
|
||||
log.Println("error getting blog list:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
var ret struct {
|
||||
BlogList []BlogListResult `json:"blogList"`
|
||||
Num int `json:"num"`
|
||||
}
|
||||
ret.Num = len(blogList)
|
||||
ret.BlogList = blogList
|
||||
json.NewEncoder(w).Encode(ret)
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/CalebQ42/bbConvert"
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
type BlogApp struct {
|
||||
back *backend.Backend
|
||||
blogCol *mongo.Collection
|
||||
authCol *mongo.Collection
|
||||
portfolioCol *mongo.Collection
|
||||
conv bbConvert.ComboConverter
|
||||
|
||||
cacheMutex *sync.RWMutex
|
||||
blogCache map[string]Blog
|
||||
}
|
||||
|
||||
func NewBlogApp(db *mongo.Database) *BlogApp {
|
||||
out := &BlogApp{
|
||||
blogCol: db.Collection("blog"),
|
||||
authCol: db.Collection("author"),
|
||||
portfolioCol: db.Collection("portfolio"),
|
||||
conv: bbConvert.NewComboConverter(),
|
||||
cacheMutex: &sync.RWMutex{},
|
||||
blogCache: make(map[string]Blog),
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *BlogApp) AppID() string {
|
||||
return "blog"
|
||||
}
|
||||
|
||||
func (b *BlogApp) CountTable() backend.CountTable {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) CrashTable() backend.CrashTable {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) AddBackend(back *backend.Backend) {
|
||||
b.back = back
|
||||
}
|
||||
|
||||
func (b *BlogApp) Extension(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /blog", b.reqLatestBlogs)
|
||||
mux.HandleFunc("GET /blog/list", b.reqBlogList)
|
||||
mux.HandleFunc("GET /blog/{blogID}", b.reqBlog)
|
||||
mux.HandleFunc("POST /blog", b.createBlog)
|
||||
mux.HandleFunc("POST /blog/{blogID}", b.updateBlog)
|
||||
|
||||
mux.HandleFunc("GET /blog/author/{authorID}", b.reqAuthorInfo)
|
||||
mux.HandleFunc("POST /blog/author", b.addAuthorInfo)
|
||||
mux.HandleFunc("POST /blog/author/{authorID}", b.updateAuthorInfo)
|
||||
|
||||
mux.HandleFunc("GET /blog/portfolio", b.reqPortfolio)
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
const (
|
||||
portfolioTitle = "<h2 class='portfolio-title'>%v</h2>"
|
||||
portfolioLink = "<p class='portfolio-link'><a href='%v'>%v</a>"
|
||||
portfolioLanguage = "<p class='portfolio-language'><b>%v</b>: %v</p>"
|
||||
portfolioTech = "<p class='portfolio-tech'><b>Tech: </b>%v</p>"
|
||||
portfolioDesc = "<p class='portfolio-description'>%v</p>"
|
||||
)
|
||||
|
||||
type PortfolioProject struct {
|
||||
Title string `json:"_id" bson:"_id"`
|
||||
Order int `json:"order" bson:"order"`
|
||||
Repository string `json:"repository" bson:"repository"`
|
||||
Description string `json:"description" bson:"description"`
|
||||
Technologies []string `json:"technologies" bson:"technologies"`
|
||||
Languages []struct {
|
||||
Language string `json:"language" bson:"language"`
|
||||
Dates string `json:"dates" bson:"dates"`
|
||||
} `json:"language" bson:"language"`
|
||||
}
|
||||
|
||||
func (p PortfolioProject) HTMX() string {
|
||||
out := fmt.Sprintf(portfolioTitle, p.Title)
|
||||
out += fmt.Sprintf(portfolioLink, p.Repository, p.Repository)
|
||||
for _, l := range p.Languages {
|
||||
out += fmt.Sprintf(portfolioLanguage, l.Language, l.Dates)
|
||||
}
|
||||
out += fmt.Sprintf(portfolioTech, strings.Join(p.Technologies, ", "))
|
||||
out += fmt.Sprintf(portfolioDesc, p.Description)
|
||||
return out
|
||||
}
|
||||
|
||||
type Portfolio []PortfolioProject
|
||||
|
||||
const (
|
||||
portfolioSelector = `
|
||||
<p>Tech Filter:
|
||||
<select
|
||||
id='techSelect'
|
||||
name='tech'
|
||||
hx-get='https://api.darkstorm.tech/blog/portfolio'
|
||||
hx-target='#projects'>
|
||||
%v
|
||||
</select>
|
||||
</p>`
|
||||
portfolioSelectorOption = "<option value='%v'%v>%v</option>"
|
||||
)
|
||||
|
||||
func (p Portfolio) FullHTMX(ctx context.Context, blogApp *BlogApp, selectedTech string) string {
|
||||
aboutMe := "<h1 class='about-me-header'>About Me</h1>"
|
||||
if me, err := blogApp.AboutMe(ctx); err != nil {
|
||||
aboutMe += "Error getting info about me :("
|
||||
} else {
|
||||
aboutMe += me.HTML()
|
||||
}
|
||||
aboutMe += "<h1 class='my-projects-header' style='margin-bottom:15px'>My Projects</h1>"
|
||||
tech := make(map[string]struct{})
|
||||
for i := range p {
|
||||
for _, t := range p[i].Technologies {
|
||||
tech[t] = struct{}{}
|
||||
}
|
||||
}
|
||||
techKeys := make([]string, 0, len(tech))
|
||||
for k := range tech {
|
||||
techKeys = append(techKeys, k)
|
||||
}
|
||||
slices.Sort(techKeys)
|
||||
var out string
|
||||
if selectedTech == "" {
|
||||
out = fmt.Sprintf(portfolioSelectorOption, "", " selected=true", "All")
|
||||
} else {
|
||||
out = fmt.Sprintf(portfolioSelectorOption, "", "", "All")
|
||||
}
|
||||
for _, k := range techKeys {
|
||||
if selectedTech == strings.ToLower(k) {
|
||||
out += fmt.Sprintf(portfolioSelectorOption, k, " selected=true", k)
|
||||
} else {
|
||||
out += fmt.Sprintf(portfolioSelectorOption, k, "", k)
|
||||
}
|
||||
}
|
||||
return aboutMe + fmt.Sprintf(portfolioSelector, out) + "<div id='projects'>" + p.HTMX() + "</div>"
|
||||
}
|
||||
|
||||
func (p Portfolio) HTMX() string {
|
||||
out := ""
|
||||
for _, proj := range p {
|
||||
out += proj.HTMX()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *BlogApp) Projects(ctx context.Context, techFilter string) (Portfolio, error) {
|
||||
filter := bson.M{}
|
||||
if techFilter != "" {
|
||||
filter = bson.M{"technologies": techFilter}
|
||||
}
|
||||
res, err := b.portfolioCol.Find(ctx, filter, options.Find().SetSort(bson.M{"order": 1}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []PortfolioProject
|
||||
err = res.All(ctx, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqPortfolio(w http.ResponseWriter, r *http.Request) {
|
||||
folio, err := b.Projects(r.Context(), r.URL.Query().Get("tech"))
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Hx-Request") == "true" {
|
||||
if r.URL.Query().Has("tech") {
|
||||
w.Write([]byte(folio.HTMX()))
|
||||
} else {
|
||||
w.Write([]byte(folio.FullHTMX(r.Context(), b, r.URL.Query().Get("tech"))))
|
||||
}
|
||||
} else {
|
||||
json.NewEncoder(w).Encode(folio)
|
||||
}
|
||||
}
|
||||
+188
-2
@@ -1,3 +1,189 @@
|
||||
# Blogs
|
||||
# Blog module
|
||||
|
||||
An HTMX powered blog system and editor.
|
||||
A simple blog module for darkstorm-backend.
|
||||
|
||||
## Requests
|
||||
|
||||
### Author info
|
||||
|
||||
#### Get author info
|
||||
|
||||
> GET /author/{authorID}
|
||||
|
||||
```json
|
||||
{
|
||||
id: "authorID",
|
||||
name: "author name",
|
||||
about: "about",
|
||||
picurl: "picture URL"
|
||||
}
|
||||
```
|
||||
|
||||
#### Update author info
|
||||
|
||||
> POST /author/{authorID}
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
name: "author name",
|
||||
about: "about",
|
||||
picurl: "picture url"
|
||||
}
|
||||
```
|
||||
|
||||
#### Add Author info
|
||||
|
||||
> POST /author
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
name: "author name",
|
||||
about: "about",
|
||||
picurl: "picture URL"
|
||||
}
|
||||
```
|
||||
|
||||
### Blog
|
||||
|
||||
#### Specific blog
|
||||
|
||||
> GET /blog/{blogID}
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
id: "blogID",
|
||||
staticPage: false, // static pages don't show up alongside other blog pages.
|
||||
createTime: 0, // creation time in Unix format
|
||||
updateTime: 0, // last update time in Unix format
|
||||
author: "authorID",
|
||||
favicon: "favicon url",
|
||||
title: "blog title",
|
||||
blog: "blog", // blog will have been converted to HTML
|
||||
}
|
||||
```
|
||||
|
||||
#### Create blog
|
||||
|
||||
Request:
|
||||
|
||||
> POST /blog
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
favicon: "favicon url",
|
||||
title: "blog title",
|
||||
blog: "blog", // blog will have been converted to HTML
|
||||
}
|
||||
```
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
id: "blogID"
|
||||
}
|
||||
```
|
||||
|
||||
#### Update blog
|
||||
|
||||
Request:
|
||||
|
||||
> POST /blog/{blogID}
|
||||
|
||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||
|
||||
```json
|
||||
{
|
||||
favicon: "new icon",
|
||||
title: "new title",
|
||||
blog: "new blog content"
|
||||
}
|
||||
```
|
||||
|
||||
#### Latest blogs
|
||||
|
||||
> GET /blog?page=0
|
||||
|
||||
Will return up to 5 blogs. `page` query is optional (implies 0 if not set).
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
num: 1, // Number of returned results, returns up to 5 results
|
||||
blogs: [
|
||||
{
|
||||
id: "blogID",
|
||||
createTime: 0, // creation time in Unix format
|
||||
updateTime: 0, // last update time in Unix format
|
||||
author: "authorID",
|
||||
favicon: "favicon url",
|
||||
title: "blog title",
|
||||
blog: "blog", // blog will have been converted to HTML
|
||||
}
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Blog List
|
||||
|
||||
> GET /blog/list?page=0
|
||||
|
||||
Will return up to 50 IDs. `page` query is optional (implies 0 if not set).
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
{
|
||||
num: 1, // Number of returned results, returns up to 50 results
|
||||
blogList: [
|
||||
{
|
||||
id: "blogID",
|
||||
createTime: 0, // Unix format
|
||||
},
|
||||
{
|
||||
id: "blogID",
|
||||
createTime: 0, // Unix format
|
||||
},
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Portfolio
|
||||
|
||||
#### Get Projects
|
||||
|
||||
> GET: /portfolio?lang=go
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
title: "Darkstorm Server",
|
||||
order: 0,
|
||||
repository: "https://github.com/CalebQ42/darkstorm-server",
|
||||
description: "The backend that runs runs my website and APIs",
|
||||
technologies: [ // May be empty
|
||||
"MongoDB",
|
||||
"RESTful API"
|
||||
],
|
||||
language: [
|
||||
{
|
||||
language: "go",
|
||||
dates: "September 2021"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
@@ -1,8 +1,166 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
const authorInfo = `
|
||||
<div>
|
||||
<img src="%v" alt="%v" class='author-pic'>
|
||||
<h3 class="author-title">%v</h3>
|
||||
<p>%v<p>
|
||||
</div>`
|
||||
|
||||
type Author struct {
|
||||
ID string `json:"id" bson:"_id"`
|
||||
Name string `json:"name" bson:"name"`
|
||||
About string `json:"about" bson:"about"`
|
||||
PicURL string `json:"picurl" bson:"picurl"`
|
||||
}
|
||||
|
||||
func (a Author) HTML() string {
|
||||
return fmt.Sprintf(authorInfo, a.PicURL, a.Name+"'s profile picture", a.Name, a.About)
|
||||
}
|
||||
|
||||
func (b *BlogApp) AboutMe(ctx context.Context) (*Author, error) {
|
||||
res := b.authCol.FindOne(ctx, bson.M{"_id": "BelacDarkstorm"})
|
||||
if res.Err() != nil {
|
||||
log.Println("error getting about me:", res.Err())
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
var aboutMe Author
|
||||
err := res.Decode(&aboutMe)
|
||||
if err != nil {
|
||||
log.Println("error decoding about me:", res)
|
||||
return nil, err
|
||||
}
|
||||
return &aboutMe, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||
res := b.authCol.FindOne(r.Context(), r.PathValue("authorID"))
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found")
|
||||
return
|
||||
} else if res.Err() != nil {
|
||||
log.Println("error getting author info:", res.Err())
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
var auth Author
|
||||
err := res.Decode(&auth)
|
||||
if err != nil {
|
||||
log.Println("error decoding author info:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(auth)
|
||||
}
|
||||
|
||||
func (b *BlogApp) addAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
var newAuth Author
|
||||
err = json.NewDecoder(r.Body).Decode(&newAuth)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
||||
return
|
||||
}
|
||||
for i := 1; ; i++ {
|
||||
newID := strings.ReplaceAll(newAuth.Name, " ", "-")
|
||||
if i != 1 {
|
||||
newID += strconv.Itoa(i)
|
||||
}
|
||||
collisionCheck := b.authCol.FindOne(r.Context(), bson.M{"name": newAuth.Name})
|
||||
if collisionCheck.Err() == mongo.ErrNoDocuments {
|
||||
newAuth.ID = newID
|
||||
break
|
||||
} else if collisionCheck.Err() != nil {
|
||||
log.Println("error checking for new author ID collisions:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
}
|
||||
_, err = b.authCol.InsertOne(r.Context(), newAuth)
|
||||
if err != nil {
|
||||
log.Println("error inserting new author:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
func (b *BlogApp) updateAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
var rawUpd map[string]string
|
||||
err = json.NewDecoder(r.Body).Decode(&rawUpd)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
||||
return
|
||||
}
|
||||
actlUpd := make(map[string]string)
|
||||
if rawUpd["name"] != "" {
|
||||
actlUpd["name"] = rawUpd["name"]
|
||||
}
|
||||
if rawUpd["about"] != "" {
|
||||
actlUpd["about"] = rawUpd["about"]
|
||||
}
|
||||
if rawUpd["picurl"] != "" {
|
||||
actlUpd["picurl"] = rawUpd["picurl"]
|
||||
}
|
||||
res, err := b.authCol.UpdateByID(r.Context(), r.PathValue("authorID"), actlUpd)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found")
|
||||
} else {
|
||||
log.Println("error updating author", r.PathValue("authorID")+":", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if res.MatchedCount == 0 {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
type BlogList struct {
|
||||
ID string `json:"id" bson:"_id"`
|
||||
Title string `json:"title" bson:"title"`
|
||||
Draft bool `json:"draft" bson:"draft"`
|
||||
CreateTime int64 `json:"createTime" bson:"createTime"`
|
||||
}
|
||||
|
||||
func (b *Backend) FullBlogList(ctx context.Context) ([]BlogList, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{}, options.Find().
|
||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1, "draft": 1}).
|
||||
SetSort(bson.M{"createTime": -1}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var list []BlogList
|
||||
err = res.All(ctx, &list)
|
||||
return list, err
|
||||
}
|
||||
|
||||
func (b *Backend) BlogList(ctx context.Context) ([]BlogList, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{
|
||||
"draft": false,
|
||||
"staticPage": false,
|
||||
}, options.Find().
|
||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1, "draft": 1}).
|
||||
SetSort(bson.M{"createTime": -1}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var list []BlogList
|
||||
err = res.All(ctx, &list)
|
||||
return list, err
|
||||
}
|
||||
+344
-169
@@ -1,15 +1,29 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
const (
|
||||
blogTitle = "<h1 class='blog-title'><a hx-push-url='true' hx-get='/%v' hx-target='#content' href='/%v' style='text-decoration:none'>%v</a></h1>"
|
||||
blogAuthor = "<h4 class='blog-author'><i><b>By %v</b></i></h4>"
|
||||
blogCreate = "<h5 class='blog-time'><i>Written on: %v</i></h5>"
|
||||
blogUpdate = "<h5 class='blog-time'><i>Updated on: %v</i></h5>"
|
||||
blogMain = "<div class='blog'>%v</div>"
|
||||
)
|
||||
|
||||
type Blog struct {
|
||||
@@ -25,201 +39,362 @@ type Blog struct {
|
||||
UpdateTime int64 `json:"updateTime" bson:"updateTime"`
|
||||
}
|
||||
|
||||
func (b *Backend) GetBlog(ctx context.Context, ID string, allowDraft bool) (Blog, error) {
|
||||
filter := bson.M{"_id": ID}
|
||||
if !allowDraft {
|
||||
filter["draft"] = false
|
||||
func (b *Blog) HTMX(blogApp *BlogApp, ctx context.Context) string {
|
||||
if b.StaticPage {
|
||||
return b.RawBlog
|
||||
}
|
||||
res := b.blogCol.FindOne(ctx, filter)
|
||||
if res.Err() != nil {
|
||||
return Blog{}, res.Err()
|
||||
}
|
||||
var out Blog
|
||||
err := res.Decode(&out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (b *Backend) postBlogReq(w http.ResponseWriter, r *http.Request) {
|
||||
usr := b.verifyEditorCookie(r)
|
||||
if usr == nil {
|
||||
redirect(w, r, "/login")
|
||||
return
|
||||
}
|
||||
if usr.Perm["blog"] != "admin" && usr.Perm["blog"] != "writer" {
|
||||
w.Write([]byte("<p>Sorry, but you aren't authorized to do this action.</p>"))
|
||||
return
|
||||
}
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
w.Write([]byte("<p>Error decoding form</p>"))
|
||||
return
|
||||
}
|
||||
newBlog := Blog{
|
||||
ID: r.FormValue("id"),
|
||||
Title: r.FormValue("title"),
|
||||
RawBlog: r.FormValue("blog"),
|
||||
StaticPage: r.FormValue("staticPage") == "on",
|
||||
Draft: r.FormValue("draft") == "on",
|
||||
UpdateTime: time.Now().Unix(),
|
||||
}
|
||||
if newBlog.Title == "" || newBlog.RawBlog == "" {
|
||||
w.Write([]byte("<p>Title and blog contents are required</p>"))
|
||||
return
|
||||
}
|
||||
if newBlog.ID == "" {
|
||||
newBlog.ID = strings.ToLower(strings.ReplaceAll(newBlog.Title, " ", "-"))
|
||||
newBlog.CreateTime = newBlog.UpdateTime
|
||||
newBlog.Author = usr.Username
|
||||
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||
if mongo.IsDuplicateKeyError(err) {
|
||||
w.Write([]byte("<p>Title already exists</p>"))
|
||||
return
|
||||
} else if err != nil {
|
||||
log.Println("error inserting document")
|
||||
w.Write([]byte("<p>Server error inserting document</p>"))
|
||||
return
|
||||
}
|
||||
b.blogSuccessFullPageReplace(r.Context(), w, newBlog)
|
||||
return
|
||||
}
|
||||
res := b.blogCol.FindOne(r.Context(), bson.M{"_id": newBlog.ID})
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
w.Write([]byte("<p>Error finding old document</p>"))
|
||||
return
|
||||
} else if res.Err() != nil {
|
||||
log.Println("error getting old blog for update:", res.Err())
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
return
|
||||
}
|
||||
var oldBlog Blog
|
||||
err = res.Decode(&oldBlog)
|
||||
if err != nil {
|
||||
log.Println("error decoding old blog for update:", res.Err())
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
return
|
||||
}
|
||||
newBlog.CreateTime = oldBlog.CreateTime
|
||||
if oldBlog.Title != newBlog.Title {
|
||||
res = b.blogCol.FindOne(r.Context(), bson.M{"_id": strings.ToLower(strings.ReplaceAll(newBlog.Title, " ", "-"))})
|
||||
if res.Err() == nil {
|
||||
w.Write([]byte("<p>Title already exists</p>"))
|
||||
return
|
||||
} else if res.Err() != mongo.ErrNoDocuments {
|
||||
log.Println("error checking for title existance:", res.Err())
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
return
|
||||
}
|
||||
res = b.blogCol.FindOneAndDelete(r.Context(), bson.M{"_id": oldBlog.ID})
|
||||
if res.Err() != nil {
|
||||
log.Println("error deleting old blog:", res.Err())
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
return
|
||||
}
|
||||
newBlog.ID = strings.ToLower(strings.ReplaceAll(newBlog.Title, " ", "-"))
|
||||
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||
if err != nil {
|
||||
log.Println("error inserting document")
|
||||
w.Write([]byte("<p>Server error inserting document</p>"))
|
||||
return
|
||||
}
|
||||
b.blogSuccessFullPageReplace(r.Context(), w, newBlog)
|
||||
return
|
||||
}
|
||||
_, err = b.blogCol.UpdateByID(r.Context(), newBlog.ID, bson.M{
|
||||
"updateTime": newBlog.UpdateTime,
|
||||
"blog": newBlog.RawBlog,
|
||||
"staticPage": newBlog.StaticPage,
|
||||
"draft": newBlog.Draft,
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("error updating blog:", err)
|
||||
w.Write([]byte("<p>Server error inserting document</p>"))
|
||||
out := fmt.Sprintf(blogTitle, b.ID, b.ID, b.Title)
|
||||
auth, err := blogApp.GetAuthor(ctx, b)
|
||||
if err == nil {
|
||||
out += fmt.Sprintf(blogAuthor, auth.Name)
|
||||
} else {
|
||||
w.Write([]byte("<p>Successfully updated</p>"))
|
||||
out += fmt.Sprintf(blogAuthor, "unknown")
|
||||
}
|
||||
out += fmt.Sprintf(blogCreate, time.Unix(b.CreateTime, 0).Format(time.DateOnly))
|
||||
if b.UpdateTime > b.CreateTime {
|
||||
out += fmt.Sprintf(blogUpdate, time.Unix(b.UpdateTime, 0).Format(time.DateOnly))
|
||||
}
|
||||
out += fmt.Sprintf(blogMain, b.HTMLBlog)
|
||||
if err == nil {
|
||||
out += "<h2 class='blog-author-info'>About the author:</h2>" + auth.HTML()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (b Blog) IDFromTitle() string {
|
||||
id := strings.Join(regexp.MustCompile("([A-z]| |[0-9])*").FindAllString(b.Title, -1), "")
|
||||
return strings.ToLower(strings.ReplaceAll(id, " ", "-"))
|
||||
}
|
||||
|
||||
func (b *BlogApp) ConvertBlog(blog *Blog) {
|
||||
if !blog.StaticPage {
|
||||
blog.HTMLBlog = b.conv.HTMLConvert(blog.RawBlog)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Backend) blogSuccessFullPageReplace(ctx context.Context, w http.ResponseWriter, blog Blog) {
|
||||
form, err := b.BlogEditForm(blog)
|
||||
func (b *BlogApp) GetAuthor(ctx context.Context, blog *Blog) (*Author, error) {
|
||||
res := b.authCol.FindOne(ctx, bson.M{"_id": blog.Author})
|
||||
if res.Err() != nil {
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
var author Author
|
||||
err := res.Decode(&author)
|
||||
return &author, err
|
||||
}
|
||||
|
||||
func (b *BlogApp) Blog(ctx context.Context, ID string) (*Blog, error) {
|
||||
b.cacheMutex.RLock()
|
||||
blog, has := b.blogCache[ID]
|
||||
b.cacheMutex.RUnlock()
|
||||
if has {
|
||||
return &blog, nil
|
||||
}
|
||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID, "draft": false})
|
||||
if res.Err() != nil {
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, res.Err()
|
||||
}
|
||||
err := res.Decode(&blog)
|
||||
if err != nil {
|
||||
log.Println("error with blogForm template:", err)
|
||||
w.Write([]byte("<p>Success, but error reloading page</p>"))
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
out, err := b.BlogEditPage(ctx, blog.ID, form)
|
||||
if err != nil {
|
||||
log.Println("error with getting blog list:", err)
|
||||
w.Write([]byte("<p>Success, but error reloading page</p>"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Hx-Retarget", "#editPage")
|
||||
w.Write([]byte(out))
|
||||
b.ConvertBlog(&blog)
|
||||
b.cacheMutex.Lock()
|
||||
b.blogCache[ID] = blog
|
||||
b.cacheMutex.Unlock()
|
||||
go b.CleanCache(ID)
|
||||
return &blog, nil
|
||||
}
|
||||
|
||||
func (b *Backend) BlogEditForm(blog Blog) (string, error) {
|
||||
form := new(bytes.Buffer)
|
||||
err := b.tmpl.ExecuteTemplate(form, "blogForm", blogFormStruct{
|
||||
Blog: blog,
|
||||
Result: "<p>Success!!</p>",
|
||||
})
|
||||
return form.String(), err
|
||||
func (b *BlogApp) AnyBlog(ctx context.Context, ID string) (*Blog, error) {
|
||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
||||
if res.Err() != nil {
|
||||
if res.Err() == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
|
||||
func (b *Backend) blogFormReq(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Hx-Request") != "true" {
|
||||
redirect(w, r, "/editor")
|
||||
return
|
||||
return nil, res.Err()
|
||||
}
|
||||
blogID := r.URL.Query().Get("blog")
|
||||
var blog Blog
|
||||
if blogID != "" {
|
||||
var err error
|
||||
blog, err = b.GetBlog(r.Context(), blogID, true)
|
||||
err := res.Decode(&blog)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.ConvertBlog(&blog)
|
||||
return &blog, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) Contains(ctx context.Context, ID string) bool {
|
||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
||||
return res.Err() == nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) CleanCache(ID string) {
|
||||
time.Sleep(5 * time.Minute)
|
||||
b.cacheMutex.Lock()
|
||||
delete(b.blogCache, ID)
|
||||
b.cacheMutex.Unlock()
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqBlog(w http.ResponseWriter, r *http.Request) {
|
||||
blogID := r.PathValue("blogID")
|
||||
if blogID == "" {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Must provide a blogID")
|
||||
return
|
||||
}
|
||||
blog, err := b.Blog(r.Context(), blogID)
|
||||
if err != nil {
|
||||
if err == backend.ErrNotFound {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Not blog found with the given ID")
|
||||
return
|
||||
}
|
||||
log.Println("error getting blog:", err)
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Hx-Request") == "true" {
|
||||
w.Write([]byte(blog.HTMX(b, r.Context())))
|
||||
} else {
|
||||
json.NewEncoder(w).Encode(blog)
|
||||
}
|
||||
form, err := b.BlogEditForm(blog)
|
||||
if err != nil {
|
||||
log.Println("error using blogForm template:", err)
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(form))
|
||||
}
|
||||
|
||||
func (b *Backend) BlogEditPage(ctx context.Context, selectedID, editor string) (string, error) {
|
||||
blogs, err := b.FullBlogList(ctx)
|
||||
func (b *BlogApp) createBlog(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
return "", err
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
out := new(bytes.Buffer)
|
||||
err = b.tmpl.ExecuteTemplate(out, "blogPage", blogPageStruct{
|
||||
Selected: selectedID,
|
||||
Editor: editor,
|
||||
Blogs: blogs,
|
||||
})
|
||||
return out.String(), err
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
var newBlog Blog
|
||||
err = json.NewDecoder(r.Body).Decode(&newBlog)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||
return
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
log.Println("error generating UUID:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
tim := time.Now().Unix()
|
||||
newBlog.ID = id.String()
|
||||
newBlog.CreateTime = tim
|
||||
newBlog.UpdateTime = tim
|
||||
newBlog.Author = hdr.User.Username
|
||||
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||
if err != nil {
|
||||
log.Println("error when inserting new blog:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
|
||||
}
|
||||
|
||||
func (b *Backend) blogPageReq(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Hx-Request") != "true" {
|
||||
redirect(w, r, "/editor")
|
||||
return
|
||||
}
|
||||
form, err := b.BlogEditForm(Blog{})
|
||||
func (b *BlogApp) updateBlog(w http.ResponseWriter, r *http.Request) {
|
||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||
if hdr == nil {
|
||||
if err != nil {
|
||||
log.Println("error using blogForm template:", err)
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
log.Println("request key parsing error:", err)
|
||||
}
|
||||
return
|
||||
} else if hdr.Key.AppID != "blog" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
page, err := b.BlogEditPage(r.Context(), "", form)
|
||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||
return
|
||||
}
|
||||
if r.PathValue("blogID") == "" {
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||
return
|
||||
}
|
||||
var reqUpdRaw map[string]string
|
||||
err = json.NewDecoder(r.Body).Decode(&reqUpdRaw)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
log.Println("error using blogPage template:", err)
|
||||
w.Write([]byte("<p>Server error!</p>"))
|
||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||
return
|
||||
}
|
||||
w.Write([]byte(page))
|
||||
reqUpd := bson.M{}
|
||||
if fav, ok := reqUpdRaw["favicon"]; ok && fav != "" {
|
||||
reqUpd["favicon"] = fav
|
||||
}
|
||||
if titl, ok := reqUpdRaw["title"]; ok && titl != "" {
|
||||
reqUpd["title"] = titl
|
||||
}
|
||||
if blog, ok := reqUpdRaw["blog"]; ok && blog != "" {
|
||||
reqUpd["blog"] = blog
|
||||
}
|
||||
reqUpd["updateTime"] = time.Now().Unix()
|
||||
res, err := b.blogCol.UpdateByID(r.Context(), r.PathValue("blogID"), reqUpd)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||
} else {
|
||||
log.Println("error updating blog", r.PathValue("blogID")+":", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if res.MatchedCount == 0 {
|
||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
|
||||
func (b *BlogApp) InsertBlog(ctx context.Context, blog Blog) error {
|
||||
_, err := b.blogCol.InsertOne(ctx, blog)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *BlogApp) UpdateBlog(ctx context.Context, ID string, updates bson.M) error {
|
||||
_, err := b.blogCol.UpdateByID(ctx, ID, bson.M{"$set": updates})
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *BlogApp) RemoveBlog(ctx context.Context, ID string) error {
|
||||
_, err := b.blogCol.DeleteOne(ctx, bson.M{"_id": ID})
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *BlogApp) LatestBlogs(ctx context.Context, page int64) ([]*Blog, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
||||
SetSort(bson.M{"createTime": -1}).
|
||||
SetLimit(5).
|
||||
SetSkip(page*5))
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []*Blog
|
||||
err = res.All(ctx, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range out {
|
||||
b.ConvertBlog(out[i])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqLatestBlogs(w http.ResponseWriter, r *http.Request) {
|
||||
var page int
|
||||
var err error
|
||||
pagQuery := r.URL.Query().Get("page")
|
||||
if pagQuery != "" {
|
||||
page, err = strconv.Atoi(pagQuery)
|
||||
if err != nil {
|
||||
page = 0
|
||||
}
|
||||
}
|
||||
blogs, err := b.LatestBlogs(r.Context(), int64(page))
|
||||
if err != nil && err != backend.ErrNotFound {
|
||||
log.Println("error getting latest blogs:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
var ret struct {
|
||||
Blogs []*Blog `json:"blogs"`
|
||||
Num int `json:"num"`
|
||||
}
|
||||
ret.Num = len(blogs)
|
||||
ret.Blogs = blogs
|
||||
json.NewEncoder(w).Encode(ret)
|
||||
}
|
||||
|
||||
type BlogListResult struct {
|
||||
ID string `json:"id" bson:"_id"`
|
||||
Title string `json:"title" bson:"title"`
|
||||
CreateTime int `json:"createTime" bson:"createTime"`
|
||||
}
|
||||
|
||||
func (b BlogListResult) HTMX() string {
|
||||
return "<a class='blog-list-item' href='https://darkstorm.tech/" +
|
||||
b.ID +
|
||||
"' hx-push-url='true' hx-target='#content' hx-get='/" +
|
||||
b.ID +
|
||||
"'>" + b.Title + "</a>"
|
||||
}
|
||||
|
||||
func (b *BlogApp) BlogList(ctx context.Context, page int64) ([]BlogListResult, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
||||
SetSort(bson.M{"createTime": -1}).
|
||||
SetLimit(50).
|
||||
SetSkip(page*50))
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []BlogListResult
|
||||
err = res.All(ctx, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) AllBlogsList(ctx context.Context) ([]BlogListResult, error) {
|
||||
res, err := b.blogCol.Find(ctx, bson.M{}, options.Find().
|
||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
||||
SetSort(bson.M{"createTime": -1}))
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, backend.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var out []BlogListResult
|
||||
err = res.All(ctx, &out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqBlogList(w http.ResponseWriter, r *http.Request) {
|
||||
var page int
|
||||
var err error
|
||||
pagQuery := r.URL.Query().Get("page")
|
||||
if pagQuery != "" {
|
||||
page, err = strconv.Atoi(pagQuery)
|
||||
if err != nil {
|
||||
page = 0
|
||||
}
|
||||
}
|
||||
blogList, err := b.BlogList(r.Context(), int64(page))
|
||||
if err != nil && err != backend.ErrNotFound {
|
||||
log.Println("error getting blog list:", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
var ret struct {
|
||||
BlogList []BlogListResult `json:"blogList"`
|
||||
Num int `json:"num"`
|
||||
}
|
||||
ret.Num = len(blogList)
|
||||
ret.BlogList = blogList
|
||||
json.NewEncoder(w).Encode(ret)
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (b *Backend) editorReq(w http.ResponseWriter, r *http.Request) {
|
||||
blogForm := new(bytes.Buffer)
|
||||
err := b.tmpl.ExecuteTemplate(blogForm, "blogForm", blogFormStruct{
|
||||
Blog: Blog{},
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("error using blogForm:", err)
|
||||
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||
return
|
||||
}
|
||||
blogs, err := b.FullBlogList(r.Context())
|
||||
if err != nil {
|
||||
log.Println("error getting blog list:", err)
|
||||
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||
return
|
||||
}
|
||||
blogPage := new(bytes.Buffer)
|
||||
err = b.tmpl.ExecuteTemplate(blogPage, "blogPage", blogPageStruct{
|
||||
Selected: "",
|
||||
Editor: blogForm.String(),
|
||||
Blogs: blogs,
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("error using blogPage:", err)
|
||||
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||
return
|
||||
}
|
||||
out := new(bytes.Buffer)
|
||||
err = b.tmpl.ExecuteTemplate(out, "editor", editorStruct{
|
||||
SelectedPage: "",
|
||||
Page: blogPage.String(),
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("error using editor:", err)
|
||||
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||
return
|
||||
}
|
||||
b.wrapper(w, r, "Editor", out.String())
|
||||
}
|
||||
+36
-54
@@ -1,81 +1,63 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"text/template"
|
||||
|
||||
"github.com/CalebQ42/bbConvert"
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
type WrapperFunc func(w http.ResponseWriter, r *http.Request, title, content string)
|
||||
|
||||
type Backend struct {
|
||||
type BlogApp struct {
|
||||
back *backend.Backend
|
||||
blogCol *mongo.Collection
|
||||
authCol *mongo.Collection
|
||||
projCol *mongo.Collection
|
||||
portfolioCol *mongo.Collection
|
||||
conv bbConvert.ComboConverter
|
||||
|
||||
tmpl *template.Template
|
||||
wrapper WrapperFunc
|
||||
|
||||
back *backend.Backend
|
||||
|
||||
cacheMutex sync.RWMutex
|
||||
cache map[string]string
|
||||
cacheMutex *sync.RWMutex
|
||||
blogCache map[string]Blog
|
||||
}
|
||||
|
||||
func New(c *mongo.Client, back *backend.Backend, wrapper WrapperFunc) (*Backend, error) {
|
||||
var b = &Backend{
|
||||
blogCol: c.Database("blog").Collection("blog"),
|
||||
authCol: c.Database("blog").Collection("blog"),
|
||||
projCol: c.Database("blog").Collection("blog"),
|
||||
wrapper: wrapper,
|
||||
back: back,
|
||||
cache: make(map[string]string),
|
||||
func NewBlogApp(db *mongo.Database) *BlogApp {
|
||||
out := &BlogApp{
|
||||
blogCol: db.Collection("blog"),
|
||||
authCol: db.Collection("author"),
|
||||
portfolioCol: db.Collection("portfolio"),
|
||||
conv: bbConvert.NewComboConverter(),
|
||||
cacheMutex: &sync.RWMutex{},
|
||||
blogCache: make(map[string]Blog),
|
||||
}
|
||||
return b, b.parseTemplates()
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *Backend) RegisterToMux(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /editor", b.editorReq)
|
||||
|
||||
mux.HandleFunc("GET /editor/blog", b.blogPageReq)
|
||||
mux.HandleFunc("GET /editor/blog/edit", b.blogFormReq)
|
||||
mux.HandleFunc("POST /editor/blog/post", b.postBlogReq)
|
||||
|
||||
// mux.HandleFunc("GET /editor/portfolio", b.portfolioPageReq)
|
||||
// mux.HandleFunc("GET /editor/portfolio/edit", b.portfolioFormReq)
|
||||
// mux.HandleFunc("POST /editor/portfolio/post", b.postPortfolioReq)
|
||||
|
||||
// mux.HandleFunc("GET /editor/author", b.authorPageReq)
|
||||
// mux.HandleFunc("GET /editor/author/edit", b.authorFormReq)
|
||||
// mux.HandleFunc("POST /editor/author/post", b.postAuthorReq)
|
||||
func (b *BlogApp) AppID() string {
|
||||
return "blog"
|
||||
}
|
||||
|
||||
func (b *Backend) verifyEditorCookie(r *http.Request) *backend.User {
|
||||
authCookie, err := r.Cookie("blogAuthToken")
|
||||
if err != nil {
|
||||
if err != http.ErrNoCookie {
|
||||
log.Println("error getting auth cookie:", err)
|
||||
}
|
||||
func (b *BlogApp) CountTable() backend.CountTable {
|
||||
return nil
|
||||
}
|
||||
usr, err := b.back.VerifyUser(r.Context(), authCookie.Value)
|
||||
if err != nil {
|
||||
if err != backend.ErrTokenUnauthorized {
|
||||
log.Println("error authorizing JWT token:", err)
|
||||
}
|
||||
|
||||
func (b *BlogApp) CrashTable() backend.CrashTable {
|
||||
return nil
|
||||
}
|
||||
return usr
|
||||
|
||||
func (b *BlogApp) AddBackend(back *backend.Backend) {
|
||||
b.back = back
|
||||
}
|
||||
|
||||
func redirect(w http.ResponseWriter, r *http.Request, path string) {
|
||||
if r.Header.Get("HX-Request") == "true" {
|
||||
w.Header().Set("HX-Location", `{"path": "`+path+`", "target":"#content"}`)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "https://darkstorm.tech"+path, http.StatusFound)
|
||||
func (b *BlogApp) Extension(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /blog", b.reqLatestBlogs)
|
||||
mux.HandleFunc("GET /blog/list", b.reqBlogList)
|
||||
mux.HandleFunc("GET /blog/{blogID}", b.reqBlog)
|
||||
mux.HandleFunc("POST /blog", b.createBlog)
|
||||
mux.HandleFunc("POST /blog/{blogID}", b.updateBlog)
|
||||
|
||||
mux.HandleFunc("GET /blog/author/{authorID}", b.reqAuthorInfo)
|
||||
mux.HandleFunc("POST /blog/author", b.addAuthorInfo)
|
||||
mux.HandleFunc("POST /blog/author/{authorID}", b.updateAuthorInfo)
|
||||
|
||||
mux.HandleFunc("GET /blog/portfolio", b.reqPortfolio)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
const (
|
||||
portfolioTitle = "<h2 class='portfolio-title'>%v</h2>"
|
||||
portfolioLink = "<p class='portfolio-link'><a href='%v'>%v</a>"
|
||||
portfolioLanguage = "<p class='portfolio-language'><b>%v</b>: %v</p>"
|
||||
portfolioTech = "<p class='portfolio-tech'><b>Tech: </b>%v</p>"
|
||||
portfolioDesc = "<p class='portfolio-description'>%v</p>"
|
||||
)
|
||||
|
||||
type PortfolioProject struct {
|
||||
Title string `json:"_id" bson:"_id"`
|
||||
Order int `json:"order" bson:"order"`
|
||||
@@ -11,3 +33,105 @@ type PortfolioProject struct {
|
||||
Dates string `json:"dates" bson:"dates"`
|
||||
} `json:"language" bson:"language"`
|
||||
}
|
||||
|
||||
func (p PortfolioProject) HTMX() string {
|
||||
out := fmt.Sprintf(portfolioTitle, p.Title)
|
||||
out += fmt.Sprintf(portfolioLink, p.Repository, p.Repository)
|
||||
for _, l := range p.Languages {
|
||||
out += fmt.Sprintf(portfolioLanguage, l.Language, l.Dates)
|
||||
}
|
||||
out += fmt.Sprintf(portfolioTech, strings.Join(p.Technologies, ", "))
|
||||
out += fmt.Sprintf(portfolioDesc, p.Description)
|
||||
return out
|
||||
}
|
||||
|
||||
type Portfolio []PortfolioProject
|
||||
|
||||
const (
|
||||
portfolioSelector = `
|
||||
<p>Tech Filter:
|
||||
<select
|
||||
id='techSelect'
|
||||
name='tech'
|
||||
hx-get='https://api.darkstorm.tech/blog/portfolio'
|
||||
hx-target='#projects'>
|
||||
%v
|
||||
</select>
|
||||
</p>`
|
||||
portfolioSelectorOption = "<option value='%v'%v>%v</option>"
|
||||
)
|
||||
|
||||
func (p Portfolio) FullHTMX(ctx context.Context, blogApp *BlogApp, selectedTech string) string {
|
||||
aboutMe := "<h1 class='about-me-header'>About Me</h1>"
|
||||
if me, err := blogApp.AboutMe(ctx); err != nil {
|
||||
aboutMe += "Error getting info about me :("
|
||||
} else {
|
||||
aboutMe += me.HTML()
|
||||
}
|
||||
aboutMe += "<h1 class='my-projects-header' style='margin-bottom:15px'>My Projects</h1>"
|
||||
tech := make(map[string]struct{})
|
||||
for i := range p {
|
||||
for _, t := range p[i].Technologies {
|
||||
tech[t] = struct{}{}
|
||||
}
|
||||
}
|
||||
techKeys := make([]string, 0, len(tech))
|
||||
for k := range tech {
|
||||
techKeys = append(techKeys, k)
|
||||
}
|
||||
slices.Sort(techKeys)
|
||||
var out string
|
||||
if selectedTech == "" {
|
||||
out = fmt.Sprintf(portfolioSelectorOption, "", " selected=true", "All")
|
||||
} else {
|
||||
out = fmt.Sprintf(portfolioSelectorOption, "", "", "All")
|
||||
}
|
||||
for _, k := range techKeys {
|
||||
if selectedTech == strings.ToLower(k) {
|
||||
out += fmt.Sprintf(portfolioSelectorOption, k, " selected=true", k)
|
||||
} else {
|
||||
out += fmt.Sprintf(portfolioSelectorOption, k, "", k)
|
||||
}
|
||||
}
|
||||
return aboutMe + fmt.Sprintf(portfolioSelector, out) + "<div id='projects'>" + p.HTMX() + "</div>"
|
||||
}
|
||||
|
||||
func (p Portfolio) HTMX() string {
|
||||
out := ""
|
||||
for _, proj := range p {
|
||||
out += proj.HTMX()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (b *BlogApp) Projects(ctx context.Context, techFilter string) (Portfolio, error) {
|
||||
filter := bson.M{}
|
||||
if techFilter != "" {
|
||||
filter = bson.M{"technologies": techFilter}
|
||||
}
|
||||
res, err := b.portfolioCol.Find(ctx, filter, options.Find().SetSort(bson.M{"order": 1}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []PortfolioProject
|
||||
err = res.All(ctx, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (b *BlogApp) reqPortfolio(w http.ResponseWriter, r *http.Request) {
|
||||
folio, err := b.Projects(r.Context(), r.URL.Query().Get("tech"))
|
||||
if err != nil {
|
||||
log.Println("error getting projects with filter", r.URL.Query().Get("tech")+":", err)
|
||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Hx-Request") == "true" {
|
||||
if r.URL.Query().Has("tech") {
|
||||
w.Write([]byte(folio.HTMX()))
|
||||
} else {
|
||||
w.Write([]byte(folio.FullHTMX(r.Context(), b, r.URL.Query().Get("tech"))))
|
||||
}
|
||||
} else {
|
||||
json.NewEncoder(w).Encode(folio)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
package blog
|
||||
|
||||
import (
|
||||
"text/template"
|
||||
)
|
||||
|
||||
const editor = `
|
||||
<p id="editSelector" hx-target="#editPage" hx-swap="swap:0.5s settle:0.5s" hx-push-url="true">
|
||||
<a href="/editor/blog" hx-get="/editor/blog" class="editSelectorItems{{if (eq .SelectedPage "blogs") | (eq .SelectedPage "")}} editSelectorSelected{{end}}" {{if eq .SelectedPage "blogs"}}{{end}}>Blogs</a>
|
||||
<a href="/editor/portfolio" hx-get="/editor/portfolio" class="editSelectorItems{{if eq .SelectedPage "portfolio"}} editSelectorSelected{{end}}">Portfolio</a>
|
||||
<a href="/editor/author" hx-get="/editor/author" class="editSelectorItems{{if eq .SelectedPage "author"}} editSelectorSelected{{end}}">Author</a>
|
||||
</p>
|
||||
<div id="editPage">{{ .Page }}</div>`
|
||||
|
||||
type editorStruct struct {
|
||||
SelectedPage string
|
||||
Page string
|
||||
}
|
||||
|
||||
const blogPage = `<p>
|
||||
<label for="blog" style="margin-right:10px">Blog:</label>
|
||||
<select id="blogSelect"
|
||||
name='blog'
|
||||
hx-get='/editor/blog/edit'
|
||||
hx-target='#editor'>
|
||||
<option value=''{{if eq .Selected ""}} selected{{end}}>New Blog</option>
|
||||
{{ range $blog := .Blogs }}
|
||||
<option value='{{.ID}}'{{if eq $.Selected .ID}} selected{{end}}>{{.Title}}{{if .Draft}} (Draft){{end}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
</p>
|
||||
<div id="editor" hx-on::after-settle="editorResize()">{{.Editor}}</div>`
|
||||
|
||||
type blogPageStruct struct {
|
||||
Selected string
|
||||
Editor string
|
||||
Blogs []BlogList
|
||||
}
|
||||
|
||||
// TODO: Add delete
|
||||
const blogForm = `
|
||||
<form id="editorForm" hx-post="/editor/blog/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||
<input name="id" type="hidden" value="{{.Blog.ID}}"></input>
|
||||
<p>
|
||||
<label for="staticPage" style="margin-right:10px">Static Page:</label><input type="checkbox" name="staticPage"{{if .Blog.StaticPage}} checked {{end}}/>
|
||||
<span class="vertical-seperator"></span>
|
||||
<label for="draft" style="margin-right:10px">Draft:</label><input type="checkbox" name="draft"{{if or .Blog.Draft (not .Blog.ID)}} checked {{end}}/>
|
||||
</p>
|
||||
<label for="title">Title</label>
|
||||
<input id="titleInput" name="title" value="{{.Blog.Title}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||
<textarea id="textEditor" name="blog" oninput="editorResize()">{{.Blog.RawBlog}}</textarea>
|
||||
<div id="formResult">{{.Result}}</div>
|
||||
<p style="margin-right:0px;">
|
||||
<button class="formButton" type="submit">{{if eq .Blog.ID ""}}Create{{else}}Update{{end}}</button>
|
||||
<button class="formButton"
|
||||
hx-get="/editor/blog/edit"
|
||||
hx-include="#blogSelect"
|
||||
hx-target="#editor"
|
||||
hx-confirm="Undo all your changes??">
|
||||
Cancel
|
||||
</button>
|
||||
<p>
|
||||
</form>`
|
||||
|
||||
type blogFormStruct struct {
|
||||
Blog Blog
|
||||
Result string
|
||||
}
|
||||
|
||||
const portfolioPage = `<p>
|
||||
<label for="project" style="margin-right:10px">Project:</label>
|
||||
<select id="projectSelect"
|
||||
name='project'
|
||||
hx-get='/editor/portfolio/edit'
|
||||
hx-target='#editor'>
|
||||
<option value=''{{if eq .Selected ""}} selected{{end}}>New Project</option>
|
||||
{{ range $project := .Projects }}
|
||||
<option value='{{.Title}}'{{if eq $.Selected .Title}} selected{{end}}>{{.Title}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
</p>
|
||||
<div id="editor" hx-on::after-settle="editorResize()">{{.Editor}}</div>`
|
||||
|
||||
type portfolioPageStruct struct {
|
||||
Selected string
|
||||
Editor string
|
||||
Projects []PortfolioProject
|
||||
}
|
||||
|
||||
// TODO: Add Languages to editor
|
||||
const portfolioForm = `<form id="editorForm" hx-post="/editor/portfolio/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||
<input name="origTitle" type="hidden" value="{{.Project.Title}}"></input>
|
||||
<label for="title">Title</label>
|
||||
<input id="titleInput" name="title" value="{{.Project.Title}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||
<label for="technologies">Technologies</label>
|
||||
<input id="techInput" name="technologies" value="{{range $ind, $tech := .Project.Technologies}}{{if not (eq $ind 0)}}, {{end}}$tech{{end}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||
<textarea id="textEditor" name="description" oninput="editorResize()">{{.Project.Description}}</textarea>
|
||||
<div id="formResult">{{.Result}}</div>
|
||||
<p style="margin-right:0px;">
|
||||
<button class="formButton" type="submit">{{if eq .Project.Title ""}}Create{{else}}Update{{end}}</button>
|
||||
<button class="formButton"
|
||||
hx-get="/editor/portfolio/edit"
|
||||
hx-include="#projectSelect"
|
||||
hx-target="#editor"
|
||||
hx-confirm="Undo all your changes??">
|
||||
Cancel
|
||||
</button>
|
||||
<p>
|
||||
</form>`
|
||||
|
||||
type portfolioFormStruct struct {
|
||||
Project PortfolioProject
|
||||
Result string
|
||||
}
|
||||
|
||||
const authorPage = `<p>
|
||||
<label for="author" style="margin-right:10px">Author:</label>
|
||||
<select id="authorSelect"
|
||||
name='author'
|
||||
hx-get='/editor/author/edit'
|
||||
hx-target='#editor'>
|
||||
<option value=''{{if eq .Selected ""}} selected{{end}}>New Author</option>
|
||||
{{ range $author := .Authors }}
|
||||
<option value='{{.ID}}'{{if eq $.Selected .ID}} selected{{end}}>{{.Name}}</option>
|
||||
{{end}}
|
||||
</select>
|
||||
</p>
|
||||
<div id="editor" hx-on::after-settle="editorResize()">{{.Editor}}</div>`
|
||||
|
||||
type authorPageStruct struct {
|
||||
Selected string
|
||||
Editor string
|
||||
Authors []Author
|
||||
}
|
||||
|
||||
const authorForm = `<form id="editorForm" hx-post="/editor/author/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||
<input name="id" type="hidden" value="{{.Author.ID}}"></input>
|
||||
<label for="name">Name</label>
|
||||
<input id="nameInput" name="name" value="{{.Author.Name}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||
<textarea id="textEditor" name="about" oninput="editorResize()">{{.Author.About}}</textarea>
|
||||
<div id="formResult">{{.Result}}</div>
|
||||
<p style="margin-right:0px;">
|
||||
<button class="formButton" type="submit">{{if eq .Author.ID ""}}Create{{else}}Update{{end}}</button>
|
||||
<button class="formButton"
|
||||
hx-get="/editor/author/edit"
|
||||
hx-include="#projectSelect"
|
||||
hx-target="#editor"
|
||||
hx-confirm="Undo all your changes??">
|
||||
Cancel
|
||||
</button>
|
||||
<p>
|
||||
</form>`
|
||||
|
||||
type authorFormStruct struct {
|
||||
Author Author
|
||||
Result string
|
||||
}
|
||||
|
||||
func (b *Backend) parseTemplates() error {
|
||||
var err error
|
||||
b.tmpl, err = template.New("editor").Parse(editor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tmpl, err = template.New("blogPage").Parse(blogPage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tmpl, err = template.New("blogForm").Parse(blogForm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tmpl, err = template.New("portfolioPage").Parse(portfolioPage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tmpl, err = template.New("portfolioForm").Parse(portfolioForm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tmpl, err = template.New("authorPage").Parse(authorPage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tmpl, err = template.New("authorForm").Parse(authorForm)
|
||||
return err
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"flag"
|
||||
"io"
|
||||
"log"
|
||||
@@ -13,6 +12,7 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||
"github.com/CalebQ42/darkstorm-server/internal/backend/db"
|
||||
@@ -71,13 +71,8 @@ func main() {
|
||||
|
||||
func setupMongo(uri string) {
|
||||
if !*testing {
|
||||
mongoCert, err := tls.LoadX509KeyPair(filepath.Join(flag.Arg(0), "mongo.pem"), filepath.Join(flag.Arg(0), "key.pem"))
|
||||
if err != nil {
|
||||
log.Fatal("error loading mongo keys:", err)
|
||||
}
|
||||
mongoClient, err = mongo.Connect(context.Background(), options.Client().ApplyURI(uri).SetTLSConfig(&tls.Config{
|
||||
Certificates: []tls.Certificate{mongoCert},
|
||||
}))
|
||||
var err error
|
||||
mongoClient, err = mongo.Connect(context.Background(), options.Client().ApplyURI(uri).SetTimeout(5*time.Second))
|
||||
if err != nil {
|
||||
log.Fatal("error connecting to mongo:", err)
|
||||
}
|
||||
@@ -93,7 +88,7 @@ func setupMongo(uri string) {
|
||||
func setupBackend(mux *http.ServeMux) {
|
||||
blogApp = blog.NewBlogApp(mongoClient.Database("blog"))
|
||||
var err error
|
||||
back, err = backend.NewBackend(db.NewMongoTable[backend.ApiKey](
|
||||
back, err = backend.NewBackend(db.NewMongoTable[backend.APIKey](
|
||||
mongoClient.Database("darkstorm").Collection("keys")),
|
||||
blogApp,
|
||||
swassistant.NewSWBackend(mongoClient.Database("swassistant")),
|
||||
@@ -144,8 +139,11 @@ here:
|
||||
|
||||
func setupWebsite(mux *http.ServeMux) {
|
||||
if !*testing {
|
||||
url, _ := url.Parse("https://localhost:30000")
|
||||
mux.Handle("rpg.darkstorm.tech/", httputil.NewSingleHostReverseProxy(url))
|
||||
rpgUrl, _ := url.Parse("https://localhost:30000")
|
||||
mux.Handle("rpg.darkstorm.tech/", httputil.NewSingleHostReverseProxy(rpgUrl))
|
||||
|
||||
gitUrl, _ := url.Parse("https://darkstorm.tech:3000")
|
||||
mux.Handle("git.darkstorm.tech/", httputil.NewSingleHostReverseProxy(gitUrl))
|
||||
}
|
||||
mux.HandleFunc("/", mainHandle)
|
||||
mux.HandleFunc("GET /files/{w...}", filesRequest)
|
||||
@@ -160,6 +158,7 @@ func setupWebsite(mux *http.ServeMux) {
|
||||
// Editor stuff
|
||||
mux.HandleFunc("GET /login", loginPageRequest)
|
||||
mux.HandleFunc("GET /editor/", editorRequest)
|
||||
mux.HandleFunc("DELETE /editor/edit", editorDelete)
|
||||
mux.HandleFunc("GET /editor/edit", editorEdit)
|
||||
mux.HandleFunc("POST /editor/post", editorPost)
|
||||
mux.HandleFunc("POST /login", trueLoginRequest)
|
||||
|
||||
@@ -6,6 +6,12 @@ import (
|
||||
)
|
||||
|
||||
func portfolioRequest(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "https://darkstorm.tech")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.Header().Set("Access-Control-Allow-Methods", "*")
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "*, Authorization")
|
||||
}
|
||||
selectedTech := r.URL.Query().Get("tech")
|
||||
proj, err := blogApp.Projects(r.Context(), selectedTech)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user