Compare commits

...

27 Commits

Author SHA1 Message Date
45036fe286 Initial sessions implementation 2024-03-03 09:16:49 +01:00
8f7ac979a3 Just a bit of cleaning up 2024-03-02 09:09:55 +01:00
2da17014e4 Created func for minimum spec for rss and article structs, thereby crushing an annoying bug that was caused by not initializing channels but waiting for messages to go through them 2024-03-02 00:28:42 +01:00
4e2cae74bb Changed articles and rss to channels 2024-03-01 21:01:38 +01:00
4b5929911e Implemented proper User struct 2024-03-01 12:25:53 +01:00
f59321b9c6 Added ability to publish articles 2024-03-01 11:30:31 +01:00
cba3c663c9 Added article list for written but non-published articles 2024-02-27 14:10:27 +01:00
59029c86a9 Convert title and description to plain text 2024-02-27 09:03:21 +01:00
8f5739fb68 Implemented hub 2024-02-24 15:31:33 +01:00
49988edd82 Add ability to display feed 2024-02-24 14:49:29 +01:00
36f7a92a06 Added messages and field memory for adding user 2024-02-24 13:25:32 +01:00
f716e9f0b5 Require all fields to be filled out when creating a new user 2024-02-24 12:10:34 +01:00
f3c8cd6fa5 Implemented logging to file 2024-02-24 11:41:01 +01:00
280e88a526 Check if user already exists and bug fix 2024-02-24 10:56:12 +01:00
8ef6b6472d Added ability to add user 2024-02-24 10:28:12 +01:00
2e08600814 Added ability to login 2024-02-24 09:54:25 +01:00
068bf045a7 Check user credentials before adding user 2024-02-22 20:12:09 +01:00
96fe38726c Added ability to update Passwords 2024-02-22 19:27:41 +01:00
75a21eeb9f Added ability to add user 2024-02-22 18:49:51 +01:00
6020b24e44 Changed error messages 2024-02-22 15:23:29 +01:00
ebfe01069c Added HTML sanitizer 2024-02-22 15:22:45 +01:00
5d41543543 Added initial support for MySQL databases 2024-02-18 16:37:13 +01:00
2ccc9c7397 Handle misssed errors for encoding and decoding feeds 2024-02-18 14:31:28 +01:00
c5623fe4fd Added description and a way to save and restore the RSS feed. 2024-02-18 14:01:06 +01:00
ee04a2a351 Create RSS from HTML 2024-02-18 12:41:49 +01:00
aa034701df Show HTML on website 2024-02-18 10:48:37 +01:00
ad9bfb2439 First implementation of web based editor to HTML pipeline 2024-02-18 10:07:49 +01:00
25 changed files with 1095 additions and 2 deletions

2
.gitignore vendored
View File

@ -21,3 +21,5 @@
# Go workspace file
go.work
# Custom stuff
tmp/

89
cmd/data/articles.go Normal file
View File

@ -0,0 +1,89 @@
package data
import (
"sync"
"time"
"github.com/google/uuid"
)
type Article struct {
Title string
Author string
Created time.Time
Desc string
Content string
Tags []string
UUID uuid.UUID
AuthorID int64
}
type ArticleList struct {
addCh chan *Article
delCh chan uuid.UUID
retCh chan *Article
getCh chan []Article
list []*Article
wg sync.WaitGroup
}
func minArticleList() *ArticleList {
return &ArticleList{
addCh: make(chan *Article),
delCh: make(chan uuid.UUID),
retCh: make(chan *Article),
getCh: make(chan []Article),
}
}
func (l *ArticleList) start() {
l.wg.Done()
for {
select {
case article := <-l.addCh:
l.list = append(l.list, article)
case uuid := <-l.delCh:
for i, article := range l.list {
if article.UUID == uuid {
l.list = append(l.list[:i], l.list[i+1:]...)
l.retCh <- article
}
}
case l.getCh <- func() []Article {
var list []Article
for _, article := range l.list {
list = append(list, *article)
}
return list
}():
}
}
}
func NewArticleList() *ArticleList {
list := minArticleList()
list.list = []*Article{}
list.wg.Add(1)
go list.start()
list.wg.Wait()
return list
}
func (l *ArticleList) Add(a *Article) {
l.addCh <- a
}
func (l *ArticleList) Release(uuid uuid.UUID) (*Article, bool) {
l.delCh <- uuid
article := <-l.retCh
if article == nil {
return nil, false
}
return article, true
}
func (l *ArticleList) Get() []Article {
return <-l.getCh
}

143
cmd/data/db.go Normal file
View File

@ -0,0 +1,143 @@
package data
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
type DB struct {
*sql.DB
}
func OpenDB(dbName string) (*DB, error) {
var err error
db := DB{DB: &sql.DB{}}
cfg := mysql.NewConfig()
cfg.DBName = dbName
cfg.User, cfg.Passwd, err = getCredentials()
if err != nil {
return nil, fmt.Errorf("error reading user credentials for DB: %v", err)
}
db.DB, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, fmt.Errorf("error opening DB: %v", err)
}
if err = db.Ping(); err != nil {
return nil, fmt.Errorf("error pinging DB: %v", err)
}
return &db, nil
}
func (db *DB) AddUser(user User, pass string) error {
hashedPass, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("error creating password hash: %v", err)
}
query := `
INSERT INTO users
(username, password, first_name, last_name, role)
VALUES (?, ?, ?, ?, ?)
`
_, err = db.Exec(query, user.UserName, string(hashedPass), user.FirstName, user.LastName, user.Role)
if err != nil {
return fmt.Errorf("error inserting user into DB: %v", err)
}
return nil
}
func (db *DB) GetID(userName string) (int64, error) {
var id int64
query := `
SELECT id
FROM users
WHERE username = ?
`
row := db.QueryRow(query, userName)
if err := row.Scan(&id); err != nil {
return 0, fmt.Errorf("user not in DB: %v", err)
}
return id, nil
}
func (db *DB) CheckPassword(id int64, pass string) error {
var queriedPass string
query := `
SELECT password
FROM users
WHERE id = ?
`
row := db.QueryRow(query, id)
if err := row.Scan(&queriedPass); err != nil {
return fmt.Errorf("error reading password from DB: %v", err)
}
if err := bcrypt.CompareHashAndPassword([]byte(queriedPass), []byte(pass)); err != nil {
return fmt.Errorf("incorrect password: %v", err)
}
return nil
}
func (db *DB) ChangePassword(id int64, oldPass, newPass string) error {
if err := db.CheckPassword(id, oldPass); err != nil {
return fmt.Errorf("error checking password: %v", err)
}
newHashedPass, err := bcrypt.GenerateFromPassword([]byte(newPass), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("error creating password hash: %v", err)
}
query := `
UPDATE users
SET password = ?
WHERE id = ?
`
_, err = db.Exec(query, string(newHashedPass), id)
if err != nil {
return fmt.Errorf("error updating password in DB: %v", err)
}
return nil
}
func (db *DB) CountEntries() (int64, error) {
var count int64
query := `SELECT COUNT(*) FROM users`
row := db.QueryRow(query)
if err := row.Scan(&count); err != nil {
return 0, fmt.Errorf("error counting rows in user DB: %v", err)
}
return count, nil
}
// TODO: No need for ID field in general
func (db *DB) GetUser(id int64) (*User, error) {
user := new(User)
query := `
SELECT id, username, first_name, last_name, role
FROM users
WHERE id = ?
`
row := db.QueryRow(query, id)
if err := row.Scan(&user.ID, &user.UserName, &user.FirstName,
&user.LastName, &user.Role); err != nil {
return nil, fmt.Errorf("error reading user information: %v", err)
}
return user, nil
}

52
cmd/data/helpers.go Normal file
View File

@ -0,0 +1,52 @@
package data
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"golang.org/x/term"
)
func getUsername() (string, error) {
user := os.Getenv("DB_USER")
if user == "" {
var err error
fmt.Printf("DB Benutzer: ")
user, err = bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", fmt.Errorf("error reading username: %v", err)
}
}
return strings.TrimSpace(user), nil
}
func getPassword() (string, error) {
pass := os.Getenv("DB_PASS")
if pass == "" {
fmt.Printf("DB Passwort: ")
bytePass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", fmt.Errorf("error reading password: %v", err)
}
fmt.Println()
pass = strings.TrimSpace(string(bytePass))
}
return pass, nil
}
func getCredentials() (string, string, error) {
user, err := getUsername()
if err != nil {
return "", "", fmt.Errorf("error getting username: %v", err)
}
pass, err := getPassword()
if err != nil {
return "", "", fmt.Errorf("error getting password: %v", err)
}
return user, pass, nil
}

35
cmd/data/markdown.go Normal file
View File

@ -0,0 +1,35 @@
package data
import (
"bytes"
"fmt"
"github.com/microcosm-cc/bluemonday"
"github.com/yuin/goldmark"
)
func ConvertToHTML(md string) (string, error) {
var buf bytes.Buffer
if err := goldmark.Convert([]byte(md), &buf); err != nil {
return "", fmt.Errorf("error converting markdown to html: %v", err)
}
p := bluemonday.UGCPolicy()
html := p.Sanitize(buf.String())
return html, nil
}
func ConvertToPlain(md string) (string, error) {
var buf bytes.Buffer
if err := goldmark.Convert([]byte(md), &buf); err != nil {
return "", fmt.Errorf("error converting markdown to html: %v", err)
}
p := bluemonday.StrictPolicy()
plain := p.Sanitize(buf.String())
return plain, nil
}

106
cmd/data/rss.go Normal file
View File

@ -0,0 +1,106 @@
package data
import (
"encoding/gob"
"fmt"
"os"
"sync"
"github.com/gorilla/feeds"
)
type Feed struct {
addCh chan *feeds.Item
setCh chan feeds.Feed
getCh chan feeds.Feed
feed feeds.Feed
wg sync.WaitGroup
}
func minFeed() *Feed {
return &Feed{
addCh: make(chan *feeds.Item),
setCh: make(chan feeds.Feed),
getCh: make(chan feeds.Feed),
}
}
func (f *Feed) start() {
f.wg.Done()
for {
select {
case item := <-f.addCh:
f.feed.Items = append(f.feed.Items, item)
case f.getCh <- f.feed:
case f.feed = <-f.setCh:
}
}
}
func NewFeed(title, link, desc string) *Feed {
feed := minFeed()
feed.feed = feeds.Feed{
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
}
feed.wg.Add(1)
go feed.start()
feed.wg.Wait()
return feed
}
func (f *Feed) Get() feeds.Feed {
return <-f.getCh
}
func (f *Feed) Set(feed feeds.Feed) {
f.setCh <- feed
}
func OpenFeed(filename string) (*Feed, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("error opening file %v: %v", filename, err)
}
defer file.Close()
feed := minFeed()
feed.wg.Add(1)
go feed.start()
feed.wg.Wait()
decoder := gob.NewDecoder(file)
tmpFeed := new(feeds.Feed)
err = decoder.Decode(tmpFeed)
if err != nil {
return nil, fmt.Errorf("error decoding file %v: %v", filename, err)
}
feed.Set(*tmpFeed)
return feed, nil
}
func (f *Feed) Save(filename string) error {
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating file %v: %v", filename, err)
}
defer file.Close()
encoder := gob.NewEncoder(file)
feed := f.Get()
err = encoder.Encode(feed)
if err != nil {
return fmt.Errorf("error encoding file %v: %v", filename, err)
}
return nil
}
func (f *Feed) Add(i *feeds.Item) {
f.addCh <- i
}

66
cmd/data/sessions.go Normal file
View File

@ -0,0 +1,66 @@
package data
import (
"crypto/rand"
"encoding/gob"
"fmt"
"io"
"os"
"github.com/gorilla/sessions"
)
type CookieStore struct {
sessions.CookieStore
}
func NewKey() ([]byte, error) {
key := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, key)
if err != nil {
return nil, fmt.Errorf("error generating key: %v", err)
}
return key, nil
}
func SaveKey(key []byte, filename string) error {
file, err := os.Create(filename)
if err != nil {
return fmt.Errorf("error creating key file: %v", err)
}
defer file.Close()
file.Chmod(0600)
encoder := gob.NewEncoder(file)
err = encoder.Encode(key)
if err != nil {
return fmt.Errorf("error ecoding key: %v", err)
}
return nil
}
func LoadKey(filename string) ([]byte, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("error opening key file: %v", err)
}
key := make([]byte, 32)
decoder := gob.NewDecoder(file)
err = decoder.Decode(&key)
if err != nil {
return nil, fmt.Errorf("error decoding key: %v", err)
}
return key, nil
}
func NewCookieStore(key []byte) *CookieStore {
store := sessions.NewCookieStore(key)
store.Options.Secure = true
store.Options.HttpOnly = true
return &CookieStore{*store}
}

16
cmd/data/user.go Normal file
View File

@ -0,0 +1,16 @@
package data
const (
Admin = iota
Editor
Writer
)
type User struct {
UserName string
FirstName string
LastName string
RejectedArticles []*Article
ID int64
Role int
}

105
cmd/ui/admin.go Normal file
View File

@ -0,0 +1,105 @@
package ui
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"streifling.com/jason/cpolis/cmd/data"
)
type AddUserData struct {
Msg string
data.User
}
func inputsEmpty(user data.User, pass, pass2 string) bool {
return len(user.UserName) == 0 ||
len(user.FirstName) == 0 ||
len(user.LastName) == 0 ||
len(pass) == 0 ||
len(pass2) == 0
}
func checkUserStrings(user data.User) (string, int, bool) {
userLen := 15
nameLen := 50
if len(user.UserName) > userLen {
return "Benutzername", userLen, false
} else if len(user.FirstName) > nameLen {
return "Vorname", nameLen, false
} else if len(user.LastName) > nameLen {
return "Nachname", nameLen, false
} else {
return "", 0, true
}
}
func CreateUser() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("web/templates/add-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil)
}
}
func AddUser(db *data.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
role, err := strconv.Atoi(r.PostFormValue("role"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
htmlData := AddUserData{
User: data.User{
UserName: r.PostFormValue("username"),
FirstName: r.PostFormValue("first-name"),
LastName: r.PostFormValue("last-name"),
Role: role,
},
}
pass := r.PostFormValue("password")
pass2 := r.PostFormValue("password2")
if inputsEmpty(htmlData.User, pass, pass2) {
htmlData.Msg = "Alle Felder müssen ausgefüllt werden."
tmpl, err := template.ParseFiles("web/templates/add-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", htmlData)
return
}
userString, stringLen, ok := checkUserStrings(htmlData.User)
if !ok {
htmlData.Msg = fmt.Sprint(userString, " ist zu lang. Maximal ",
stringLen, " Zeichen erlaubt.")
tmpl, err := template.ParseFiles("web/templates/add-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", htmlData)
return
}
id, _ := db.GetID(htmlData.UserName)
if id != 0 {
htmlData.Msg = fmt.Sprint(htmlData.UserName,
" ist bereits vergeben. Bitte anderen Benutzernamen wählen.")
tmpl, err := template.ParseFiles("web/templates/add-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", htmlData)
return
}
if pass != pass2 {
htmlData.Msg = "Die Passwörter stimmen nicht überein."
tmpl, err := template.ParseFiles("web/templates/add-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", htmlData)
return
}
if err := db.AddUser(htmlData.User, pass); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl, err := template.ParseFiles("web/templates/hub.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil)
}
}

153
cmd/ui/articles.go Normal file
View File

@ -0,0 +1,153 @@
package ui
import (
"html/template"
"log"
"net/http"
"time"
"github.com/google/uuid"
"github.com/gorilla/feeds"
"streifling.com/jason/cpolis/cmd/data"
)
func ShowHub(s *data.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, err := s.Get(r, "cookie")
if err != nil {
tmpl, err := template.ParseFiles("web/templates/login.html")
msg := "Session nicht mehr gültig. Bitte erneut anmelden."
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
}
tmpl, err := template.ParseFiles("web/templates/hub.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", session.Values["role"])
}
}
func WriteArticle(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("web/templates/editor.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil)
}
func FinishArticle(l *data.ArticleList, s *data.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
article := new(data.Article)
var err error
article.Title, err = data.ConvertToPlain(r.PostFormValue("editor-title"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
article.Desc, err = data.ConvertToPlain(r.PostFormValue("editor-desc"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
article.Content, err = data.ConvertToHTML(r.PostFormValue("editor-text"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session, err := s.Get(r, "cookie")
if err != nil {
tmpl, err := template.ParseFiles("web/templates/login.html")
msg := "Session nicht mehr gültig. Bitte erneut anmelden."
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
}
article.UUID = uuid.New()
article.Author = session.Values["name"].(string)
article.Created = time.Now()
article.AuthorID = session.Values["id"].(int64)
l.Add(article)
tmpl, err := template.ParseFiles("web/templates/hub.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", session.Values["role"])
}
}
func ShowUnpublishedArticles(l *data.ArticleList) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("web/templates/unpublished-articles.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", l.Get())
}
}
func ReviewArticle(l *data.ArticleList, s *data.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uuid, err := uuid.Parse(r.PostFormValue("uuid"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, article := range l.Get() {
if article.UUID == uuid {
tmpl, err := template.ParseFiles("web/templates/to-be-published.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", article)
return
}
}
session, err := s.Get(r, "cookie")
if err != nil {
tmpl, err := template.ParseFiles("web/templates/login.html")
msg := "Session nicht mehr gültig. Bitte erneut anmelden."
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
}
tmpl, err := template.ParseFiles("web/templates/hub.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", session.Values["role"])
}
}
func PublishArticle(f *data.Feed, l *data.ArticleList, s *data.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uuid, err := uuid.Parse(r.PostFormValue("uuid"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
article, ok := l.Release(uuid)
if !ok {
// TODO: Warnung anzeigen
// msg = "Alle Felder müssen ausgefüllt werden."
// tmpl, err := template.ParseFiles("web/templates/add-user.html")
// template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
return
}
f.Add(&feeds.Item{
Title: article.Title,
Created: article.Created,
Description: article.Desc,
Content: article.Content,
})
f.Save("tmp/rss.gob")
session, err := s.Get(r, "cookie")
if err != nil {
tmpl, err := template.ParseFiles("web/templates/login.html")
msg := "Session nicht mehr gültig. Bitte erneut anmelden."
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
}
tmpl, err := template.ParseFiles("web/templates/hub.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", session.Values["role"])
}
}

25
cmd/ui/rss.go Normal file
View File

@ -0,0 +1,25 @@
package ui
import (
"html/template"
"log"
"net/http"
"streifling.com/jason/cpolis/cmd/data"
)
func ShowRSS(f *data.Feed) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
feed := f.Get()
rss, err := feed.ToRss()
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
files := []string{"web/templates/index.html", "web/templates/feed.rss"}
tmpl, err := template.ParseFiles(files...)
template.Must(tmpl, err).Execute(w, rss)
}
}

83
cmd/ui/sessions.go Normal file
View File

@ -0,0 +1,83 @@
package ui
import (
"html/template"
"log"
"net/http"
"streifling.com/jason/cpolis/cmd/data"
)
func HomePage(db *data.DB, s *data.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
numRows, err := db.CountEntries()
if err != nil {
log.Fatalln(err)
}
files := []string{"web/templates/index.html"}
if numRows == 0 {
files = append(files, "web/templates/add-user.html")
tmpl, err := template.ParseFiles(files...)
template.Must(tmpl, err).Execute(w, nil)
} else {
session, _ := s.Get(r, "cookie")
if auth, ok := session.Values["authenticated"].(bool); auth && ok {
files = append(files, "web/templates/hub.html")
tmpl, err := template.ParseFiles(files...)
template.Must(tmpl, err).Execute(w, session.Values["role"])
} else {
files = append(files, "web/templates/login.html")
tmpl, err := template.ParseFiles(files...)
template.Must(tmpl, err).Execute(w, nil)
}
}
}
}
func Login(db *data.DB, s *data.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userName := r.PostFormValue("username")
password := r.PostFormValue("password")
id, err := db.GetID(userName)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := db.CheckPassword(id, password); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user, err := db.GetUser(id)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session, err := s.Get(r, "cookie")
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
session.Values["authenticated"] = true
session.Values["id"] = user.ID
session.Values["name"] = user.FirstName + user.LastName
session.Values["role"] = user.Role
if err := session.Save(r, w); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl, err := template.ParseFiles("web/templates/hub.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", user.Role)
}
}

19
go.mod
View File

@ -1,3 +1,22 @@
module streifling.com/jason/cpolis
go 1.22.0
require (
github.com/go-sql-driver/mysql v1.7.1
github.com/google/uuid v1.6.0
github.com/gorilla/feeds v1.1.2
github.com/gorilla/sessions v1.2.2
github.com/microcosm-cc/bluemonday v1.0.26
github.com/yuin/goldmark v1.7.0
golang.org/x/crypto v0.14.0
golang.org/x/term v0.17.0
)
require (
github.com/aymerick/douceur v0.2.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.17.0 // indirect
)

34
go.sum Normal file
View File

@ -0,0 +1,34 @@
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
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/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
github.com/gorilla/feeds v1.1.2 h1:pxzZ5PD3RJdhFH2FsJJ4x6PqMqbgFk1+Vez4XWBW8Iw=
github.com/gorilla/feeds v1.1.2/go.mod h1:WMib8uJP3BbY+X8Szd1rA5Pzhdfh+HCCAYT2z7Fza6Y=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3rQ0k/Khz58=
github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/yuin/goldmark v1.7.0 h1:EfOIvIMZIzHdB/R/zVrikYLPPwJlfMcNczJFMs1m6sA=
github.com/yuin/goldmark v1.7.0/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=

64
main.go
View File

@ -1,8 +1,68 @@
package main
import "net/http"
import (
"encoding/gob"
"log"
"net/http"
"os"
"streifling.com/jason/cpolis/cmd/data"
"streifling.com/jason/cpolis/cmd/ui"
)
func init() {
gob.Register(data.User{})
}
func main() {
logFile, err := os.Create("tmp/cpolis.log")
if err != nil {
log.Fatalln(err)
}
defer logFile.Close()
log.SetOutput(logFile)
db, err := data.OpenDB("cpolis")
if err != nil {
log.Fatalln(err)
}
defer db.Close()
feed, err := data.OpenFeed("tmp/rss.gob")
if err != nil {
log.Println(err)
feed = data.NewFeed("Freimaurer Distrikt Niedersachsen und Sachsen-Anhalt",
"https://distrikt-ni-st.de",
"Freiheit, Gleichheit, Brüderlichkeit, Toleranz und Humanität")
}
key, err := data.LoadKey("tmp/key.gob")
if err != nil {
key, err = data.NewKey()
if err != nil {
log.Fatalln(err)
}
data.SaveKey(key, "tmp/key.gob")
}
store := data.NewCookieStore(key)
articleList := data.NewArticleList()
mux := http.NewServeMux()
http.ListenAndServe(":8080", mux)
mux.Handle("/web/static/", http.StripPrefix("/web/static/", http.FileServer(http.Dir("web/static/"))))
mux.HandleFunc("/", ui.HomePage(db, store))
mux.HandleFunc("GET /hub/", ui.ShowHub(store))
mux.HandleFunc("GET /rss/", ui.ShowRSS(feed))
mux.HandleFunc("POST /add-user/", ui.AddUser(db))
mux.HandleFunc("POST /create-user/", ui.CreateUser())
mux.HandleFunc("POST /finish-article/", ui.FinishArticle(articleList, store))
mux.HandleFunc("POST /login/", ui.Login(db, store))
mux.HandleFunc("POST /review-article/", ui.ReviewArticle(articleList, store))
mux.HandleFunc("POST /publish-article/", ui.PublishArticle(feed, articleList, store))
mux.HandleFunc("POST /unpublished-articles/", ui.ShowUnpublishedArticles(articleList))
mux.HandleFunc("POST /write-article/", ui.WriteArticle)
log.Fatalln(http.ListenAndServe(":8080", mux))
}

0
web/static/css/style.css Normal file
View File

1
web/static/js/htmx.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,27 @@
{{define "page-content"}}
<h2>Neuer Benutzer</h2>
<form>
<input required name="username" placeholder="Benutzername" type="text" value="{{.UserName}}" />
<input required name="password" placeholder="Passwort" type="password" />
<input required name="password2" placeholder="Passwort wiederholen" type="password" />
<input required name="first-name" placeholder="Vorname" type="text" value="{{.FirstName}}" />
<input required name="last-name" placeholder="Nachname" type="text" value="{{.LastName}}" />
<label for="writer">Schreiber</label>
<input required id="writer" name="role" type="radio" value="2" {{if eq .Role "2" }}checked{{end}} />
<label for="editor">Redakteur</label>
<input required id="editor" name="role" type="radio" value="1" {{if eq .Role "1" }}checked{{end}} />
<label for="admin">Admin</label>
<input required id="admin" name="role" type="radio" value="0" {{if eq .Role "0" }}checked{{end}} />
<input type="submit" value="Anlegen" hx-post="/add-user/" hx-target="#page-content" />
</form>
<script>
var msg = "{{.Msg}}";
if (msg != "") {
alert(msg);
}
</script>
{{end}}

13
web/templates/editor.html Normal file
View File

@ -0,0 +1,13 @@
{{define "page-content"}}
<h2>Editor</h2>
<form>
<input name="editor-title" placeholder="Titel" type="text" />
<textarea name="editor-desc" placeholder="Beschreibung"></textarea>
<textarea name="editor-text" placeholder="Artikel"></textarea>
<input type="submit" value="Senden" hx-post="/finish-article/" hx-target="#page-content" />
</form>
{{end}}
{{define "html-result"}}
{{.}}
{{end}}

3
web/templates/feed.rss Normal file
View File

@ -0,0 +1,3 @@
{{define "page-content"}}
{{.}}
{{end}}

11
web/templates/hub.html Normal file
View File

@ -0,0 +1,11 @@
{{define "page-content"}}
<h2>Hub</h2>
<button hx-post="/write-article/" hx-target="#page-content">Artikel schreiben</button>
<button hx-post="/rss/" hx-target="#page-content">RSS Feed</button>
{{if eq . 0}}
<button hx-post="/create-user/" hx-target="#page-content">Benutzer hinzufügen</button>
{{end}}
{{if lt . 2}}
<button hx-post="/unpublished-articles/" hx-target="#page-content">Unveröffentlichte Artikel</button>
{{end}}
{{end}}

21
web/templates/index.html Normal file
View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orient Editor</title>
<link href="web/static/css/style.css" rel="stylesheet">
</head>
<body>
<h1>Orient Editor</h1>
<div id="page-content">
{{template "page-content" .}}
</div>
<script src="web/static/js/htmx.min.js"></script>
</body>
</html>

8
web/templates/login.html Normal file
View File

@ -0,0 +1,8 @@
{{define "page-content"}}
<h2>Anmeldung</h2>
<form>
<input name="username" placeholder="Benutzername" type="text" />
<input name="password" placeholder="Passwort" type="password" />
<input type="submit" value="Anmelden" hx-post="/login/" hx-target="#page-content" />
</form>
{{end}}

View File

@ -0,0 +1,11 @@
{{define "page-content"}}
<form>
<input name="editor-title" type="text" value="{{.Title}}" />
<textarea name="editor-desc">{{.Desc}}</textarea>
<textarea name="editor-text">{{.Content}}</textarea>
<input name="uuid" type="hidden" value="{{.UUID}}" />
<input type="submit" value="Veröffentlichen" hx-post="/publish-article/" hx-target="#page-content" />
<input type="submit" value="Ablehnen" hx-post="/reject-article/" hx-target="#page-content" />
</form>
<button hx-get="/hub/" hx-target="#page-content">Zurück</button>
{{end}}

View File

@ -0,0 +1,10 @@
{{define "page-content"}}
<form>
{{range .}}
<input required id="{{.UUID}}" name="uuid" type="radio" value="{{.UUID}}" />
<label for="{{.UUID}}">{{.Title}}</label>
{{end}}
<input type="submit" value="Auswählen" hx-post="/review-article/" hx-target="#page-content" />
</form>
<button hx-get="/hub/" hx-target="#page-content">Zurück</button>
{{end}}