Compare commits

..

No commits in common. "21fd3403b27a2d23337a4d2e63efcd5e50db8ff9" and "783d59805b1a37cf7fa4cd0a2af158dc16bb2560" have entirely different histories.

19 changed files with 139 additions and 582 deletions

View File

@ -5,7 +5,7 @@ tmp_dir = "tmp"
[build] [build]
args_bin = [ args_bin = [
"-desc 'Freiheit, Gleichheit, Brüderlichkeit, Toleranz und Humanität'", "-desc 'Freiheit, Gleichheit, Brüderlichkeit, Toleranz und Humanität'",
"-domain localhost", "-domain localhost:8080",
"-key tmp/key.gob", "-key tmp/key.gob",
"-link https://distrikt-ni-st.de", "-link https://distrikt-ni-st.de",
"-log tmp/cpolis.log", "-log tmp/cpolis.log",

68
cmd/control/cli.go Normal file
View File

@ -0,0 +1,68 @@
package control
import (
"flag"
"fmt"
"path/filepath"
)
type CliArgs struct {
Description string
DBName string
Domain string
KeyFile string
Link string
LogFile string
Port string
PicsDir string
RSSFile string
Title string
WebDir string
}
func HandleCliArgs() (*CliArgs, error) {
var err error
cliArgs := new(CliArgs)
flag.StringVar(&cliArgs.DBName, "db", "cpolis", "DB name")
flag.StringVar(&cliArgs.Description, "desc", "Description", "Channel description")
flag.StringVar(&cliArgs.Domain, "domain", "", "domain name")
keyFile := flag.String("key", "/var/www/cpolis/cpolis.key", "key file")
flag.StringVar(&cliArgs.Link, "link", "Link", "Channel Link")
logFile := flag.String("log", "/var/log/cpolis.log", "log file")
flag.StringVar(&cliArgs.PicsDir, "pics", "pics", "pictures directory")
port := flag.Int("port", 8080, "port")
rssFile := flag.String("rss", "/var/www/cpolis/cpolis.rss", "RSS file")
flag.StringVar(&cliArgs.Title, "title", "Title", "Channel title")
webDir := flag.String("web", "/var/www/cpolis/web", "web directory")
flag.Parse()
cliArgs.KeyFile, err = filepath.Abs(*keyFile)
if err != nil {
return nil, fmt.Errorf("error finding absolute path for KeyFile: %v", err)
}
cliArgs.LogFile, err = filepath.Abs(*logFile)
if err != nil {
return nil, fmt.Errorf("error finding absolute path for LogFile: %v", err)
}
_, err = filepath.Abs(cliArgs.PicsDir)
if err != nil {
return nil, fmt.Errorf("error finding absolute path for PicsDir: %v", err)
}
cliArgs.Port = fmt.Sprint(":", *port)
cliArgs.RSSFile, err = filepath.Abs(*rssFile)
if err != nil {
return nil, fmt.Errorf("error finding absolute path for RSSFile: %v", err)
}
cliArgs.WebDir, err = filepath.Abs(*webDir)
if err != nil {
return nil, fmt.Errorf("error finding absolute path for WebDir: %v", err)
}
return cliArgs, nil
}

View File

@ -1,131 +0,0 @@
package control
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
)
type Config struct {
DBName string
Description string
Domain string
KeyFile string
Link string
LogFile string
PicsDir string
Port string
RSSFile string
Title string
WebDir string
}
func newConfig() *Config {
return &Config{
DBName: "cpolis",
KeyFile: "/var/www/cpolis/cpolis.key",
LogFile: "/var/log/cpolis.log",
PicsDir: "/var/www/cpolis/pics",
RSSFile: "/var/www/cpolis/cpolis.rss",
WebDir: "/var/www/cpolis/web",
}
}
func (c *Config) readFile() error {
cfgFile, err := filepath.Abs(os.Getenv("HOME") + "/.config/cpolis/config.toml")
if err != nil {
return fmt.Errorf("error getting absolute path for config file: %v", err)
}
_, err = os.Stat(cfgFile)
if os.IsNotExist(err) {
fileStrings := strings.Split(cfgFile, "/")
dir := strings.Join(fileStrings[0:len(fileStrings)-1], "/")
if err = os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("error creating config directory: %v", err)
}
fileName := fileStrings[len(fileStrings)-1]
file, err := os.Create(dir + "/" + fileName)
if err != nil {
return fmt.Errorf("error creating config file: %v", err)
}
defer file.Close()
if err = file.Chmod(0644); err != nil {
return fmt.Errorf("error setting permissions for config file: %v", err)
}
} else {
_, err = toml.DecodeFile(cfgFile, c)
if err != nil {
return fmt.Errorf("error reading config file: %v", err)
}
}
return nil
}
func (c *Config) handleCliArgs() error {
var err error
port := 8080
flag.StringVar(&c.DBName, "db", c.DBName, "DB name")
flag.StringVar(&c.Description, "desc", c.Description, "Channel description")
flag.StringVar(&c.Domain, "domain", c.Domain, "domain name")
flag.StringVar(&c.KeyFile, "key", c.KeyFile, "key file")
flag.StringVar(&c.Link, "link", c.Link, "Channel Link")
flag.StringVar(&c.LogFile, "log", c.LogFile, "log file")
flag.StringVar(&c.PicsDir, "pics", c.PicsDir, "pictures directory")
flag.StringVar(&c.RSSFile, "rss", c.RSSFile, "RSS file")
flag.StringVar(&c.Title, "title", c.Title, "Channel title")
flag.StringVar(&c.WebDir, "web", c.WebDir, "web directory")
flag.IntVar(&port, "port", port, "port")
flag.Parse()
c.KeyFile, err = filepath.Abs(c.KeyFile)
if err != nil {
return fmt.Errorf("error finding absolute path for key file: %v", err)
}
c.LogFile, err = filepath.Abs(c.LogFile)
if err != nil {
return fmt.Errorf("error finding absolute path for log file: %v", err)
}
c.PicsDir, err = filepath.Abs(c.PicsDir)
if err != nil {
return fmt.Errorf("error finding absolute path for pics dir: %v", err)
}
c.Port = fmt.Sprint(":", port)
c.RSSFile, err = filepath.Abs(c.RSSFile)
if err != nil {
return fmt.Errorf("error finding absolute path for RSS file: %v", err)
}
c.WebDir, err = filepath.Abs(c.WebDir)
if err != nil {
return fmt.Errorf("error finding absolute path for web dir: %v", err)
}
return nil
}
func HandleConfig() (*Config, error) {
config := newConfig()
if err := config.readFile(); err != nil {
return nil, fmt.Errorf("error reading config file: %v", err)
}
if err := config.handleCliArgs(); err != nil {
return nil, fmt.Errorf("error handling cli arguments: %v", err)
}
return config, nil
}

View File

@ -121,9 +121,7 @@ func SaveRSS(filename string, feed *string) error {
return fmt.Errorf("error creating file for RSS feed: %v", err) return fmt.Errorf("error creating file for RSS feed: %v", err)
} }
defer file.Close() defer file.Close()
if err = file.Chmod(0644); err != nil { file.Chmod(0644)
return fmt.Errorf("error setting permissions for RSS file: %v", err)
}
if _, err = io.WriteString(file, *feed); err != nil { if _, err = io.WriteString(file, *feed); err != nil {
return fmt.Errorf("error writing to RSS file: %v", err) return fmt.Errorf("error writing to RSS file: %v", err)

View File

@ -16,71 +16,66 @@ func init() {
} }
func main() { func main() {
config, err := control.HandleConfig() args, err := control.HandleCliArgs()
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
logFile, err := os.OpenFile(config.LogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) logFile, err := os.OpenFile(args.LogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
defer logFile.Close() defer logFile.Close()
log.SetOutput(logFile) log.SetOutput(logFile)
db, err := model.OpenDB(config.DBName) db, err := model.OpenDB(args.DBName)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
defer db.Close() defer db.Close()
key, err := control.LoadKey(config.KeyFile) key, err := control.LoadKey(args.KeyFile)
if err != nil { if err != nil {
key, err = control.NewKey() key, err = control.NewKey()
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
control.SaveKey(key, config.KeyFile) control.SaveKey(key, args.KeyFile)
} }
store := control.NewCookieStore(key) store := control.NewCookieStore(key)
mux := http.NewServeMux() mux := http.NewServeMux()
mux.Handle("/web/static/", http.StripPrefix("/web/static/", mux.Handle("/web/static/", http.StripPrefix("/web/static/",
http.FileServer(http.Dir(config.WebDir+"/static/")))) http.FileServer(http.Dir(args.WebDir+"/static/"))))
mux.HandleFunc("/", view.HomePage(config, db, store)) mux.HandleFunc("/", view.HomePage(args, db, store))
mux.HandleFunc("GET /create-tag", view.CreateTag(config)) mux.HandleFunc("GET /create-tag", view.CreateTag(args))
mux.HandleFunc("GET /create-user", view.CreateUser(config)) mux.HandleFunc("GET /create-user", view.CreateUser(args))
mux.HandleFunc("GET /edit-self", view.EditSelf(config, db, store)) mux.HandleFunc("GET /edit-user", view.EditUser(args, db, store))
mux.HandleFunc("GET /edit-user/{id}", view.EditUser(config, db)) mux.HandleFunc("GET /hub", view.ShowHub(args, db, store))
mux.HandleFunc("GET /delete-user/{id}", view.DeleteUser(config, db, store)) mux.HandleFunc("GET /logout", view.Logout(args, store))
mux.HandleFunc("GET /hub", view.ShowHub(config, db, store)) mux.HandleFunc("GET /publish-article/{id}", view.PublishArticle(args, db, store))
mux.HandleFunc("GET /logout", view.Logout(config, store)) mux.HandleFunc("GET /publish-issue", view.PublishLatestIssue(args, db, store))
mux.HandleFunc("GET /pics/{pic}", view.ServeImage(config, store)) mux.HandleFunc("GET /reject-article/{id}", view.RejectArticle(args, db, store))
mux.HandleFunc("GET /publish-article/{id}", view.PublishArticle(config, db, store)) mux.HandleFunc("GET /rejected-articles", view.ShowRejectedArticles(args, db, store))
mux.HandleFunc("GET /publish-issue", view.PublishLatestIssue(config, db, store)) mux.HandleFunc("GET /review-rejected-article/{id}", view.ReviewRejectedArticle(args, db, store))
mux.HandleFunc("GET /reject-article/{id}", view.RejectArticle(config, db, store)) mux.HandleFunc("GET /review-unpublished-article/{id}", view.ReviewUnpublishedArticle(args, db, store))
mux.HandleFunc("GET /rejected-articles", view.ShowRejectedArticles(config, db, store))
mux.HandleFunc("GET /review-rejected-article/{id}", view.ReviewRejectedArticle(config, db, store))
mux.HandleFunc("GET /review-unpublished-article/{id}", view.ReviewUnpublishedArticle(config, db, store))
mux.HandleFunc("GET /rss", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /rss", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, config.RSSFile) http.ServeFile(w, r, args.RSSFile)
}) })
mux.HandleFunc("GET /show-all-users-edit", view.ShowAllUsers(config, db, store, "edit-user")) mux.HandleFunc("GET /pics/{pic}", view.ServeImage(args, store))
mux.HandleFunc("GET /show-all-users-delete", view.ShowAllUsers(config, db, store, "delete-user")) mux.HandleFunc("GET /this-issue", view.ShowCurrentArticles(args, db))
mux.HandleFunc("GET /this-issue", view.ShowCurrentArticles(config, db)) mux.HandleFunc("GET /unpublished-articles", view.ShowUnpublishedArticles(args, db))
mux.HandleFunc("GET /unpublished-articles", view.ShowUnpublishedArticles(config, db)) mux.HandleFunc("GET /write-article", view.WriteArticle(args, db))
mux.HandleFunc("GET /write-article", view.WriteArticle(config, db))
mux.HandleFunc("POST /add-first-user", view.AddFirstUser(config, db, store)) mux.HandleFunc("POST /add-first-user", view.AddFirstUser(args, db, store))
mux.HandleFunc("POST /add-tag", view.AddTag(config, db, store)) mux.HandleFunc("POST /add-tag", view.AddTag(args, db, store))
mux.HandleFunc("POST /add-user", view.AddUser(config, db, store)) mux.HandleFunc("POST /add-user", view.AddUser(args, db, store))
mux.HandleFunc("POST /login", view.Login(config, db, store)) mux.HandleFunc("POST /login", view.Login(args, db, store))
mux.HandleFunc("POST /resubmit-article/{id}", view.ResubmitArticle(config, db, store)) mux.HandleFunc("POST /resubmit-article/{id}", view.ResubmitArticle(args, db, store))
mux.HandleFunc("POST /submit-article", view.SubmitArticle(config, db, store)) mux.HandleFunc("POST /submit-article", view.SubmitArticle(args, db, store))
mux.HandleFunc("POST /update-self", view.UpdateSelf(config, db, store)) mux.HandleFunc("POST /update-user", view.UpdateUser(args, db, store))
mux.HandleFunc("POST /update-user/{id}", view.UpdateUser(config, db, store)) mux.HandleFunc("POST /upload-image", view.UploadImage(args))
mux.HandleFunc("POST /upload-image", view.UploadImage(config))
log.Fatalln(http.ListenAndServe(config.Port, mux)) log.Fatalln(http.ListenAndServe(args.Port, mux))
} }

View File

@ -14,7 +14,6 @@ const (
Publisher Publisher
Editor Editor
Author Author
NonExistent
) )
type User struct { type User struct {
@ -146,7 +145,7 @@ func (db *DB) GetUser(id int64) (*User, error) {
return user, nil return user, nil
} }
func (db *DB) UpdateOwnAttributes(id int64, user, first, last, oldPass, newPass, newPass2 string) error { func (db *DB) UpdateUserAttributes(id int64, user, first, last, oldPass, newPass, newPass2 string) error {
passwordEmpty := true passwordEmpty := true
if len(newPass) > 0 || len(newPass2) > 0 { if len(newPass) > 0 || len(newPass2) > 0 {
if newPass != newPass2 { if newPass != newPass2 {
@ -269,112 +268,3 @@ func (db *DB) AddFirstUser(u *User, pass string) (int64, error) {
} }
return 0, fmt.Errorf("error: %v unsuccessful retries for DB operation, aborting", TxMaxRetries) return 0, fmt.Errorf("error: %v unsuccessful retries for DB operation, aborting", TxMaxRetries)
} }
func (db *DB) GetAllUsers() (map[int64]*User, error) {
query := "SELECT id, username, first_name, last_name, role FROM users"
rows, err := db.Query(query)
if err != nil {
return nil, fmt.Errorf("error getting all users from DB: %v", err)
}
users := make(map[int64]*User, 0)
for rows.Next() {
user := new(User)
if err = rows.Scan(&user.ID, &user.UserName, &user.FirstName,
&user.LastName, &user.Role); err != nil {
return nil, fmt.Errorf("error getting user info: %v", err)
}
users[user.ID] = user
}
return users, nil
}
func (tx *Tx) SetPassword(id int64, newPass string) error {
hashedPass, err := bcrypt.GenerateFromPassword([]byte(newPass), bcrypt.DefaultCost)
if err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
}
return fmt.Errorf("error creating password hash: %v", err)
}
setQuery := "UPDATE users SET password = ? WHERE id = ?"
if _, err = tx.Exec(setQuery, string(hashedPass), id); err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
}
return fmt.Errorf("error updating password in DB: %v", err)
}
return nil
}
func (db *DB) UpdateUserAttributes(id int64, user, first, last, newPass, newPass2 string, role int) error {
passwordEmpty := true
if len(newPass) > 0 || len(newPass2) > 0 {
if newPass != newPass2 {
return fmt.Errorf("error: passwords do not match")
}
passwordEmpty = false
}
tx := new(Tx)
var err error
for i := 0; i < TxMaxRetries; i++ {
err := func() error {
tx.Tx, err = db.Begin()
if err != nil {
return fmt.Errorf("error starting transaction: %v", err)
}
if !passwordEmpty {
if err = tx.SetPassword(id, newPass); err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
}
return fmt.Errorf("error changing password: %v", err)
}
}
if err = tx.UpdateAttributes(
&Attribute{Table: "users", ID: id, AttName: "username", Value: user},
&Attribute{Table: "users", ID: id, AttName: "first_name", Value: first},
&Attribute{Table: "users", ID: id, AttName: "last_name", Value: last},
&Attribute{Table: "users", ID: id, AttName: "role", Value: role},
); err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
}
return fmt.Errorf("error updating attributes in DB: %v", err)
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("error committing transaction: %v", err)
}
return nil
}()
if err == nil {
return nil
}
log.Println(err)
wait(i)
}
return fmt.Errorf("error: %v unsuccessful retries for DB operation, aborting", TxMaxRetries)
}
func (db *DB) DeleteUser(id int64) error {
query := "DELETE FROM users WHERE id = ?"
_, err := db.Exec(query, id)
if err != nil {
return fmt.Errorf("error deleting user %v from DB: %v", id, err)
}
return nil
}

View File

@ -17,7 +17,7 @@ import (
"streifling.com/jason/cpolis/cmd/model" "streifling.com/jason/cpolis/cmd/model"
) )
func ShowHub(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func ShowHub(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
session, err := s.Get(r, "cookie") session, err := s.Get(r, "cookie")
if err != nil { if err != nil {
@ -31,7 +31,7 @@ func ShowHub(c *control.Config, db *model.DB, s *control.CookieStore) http.Handl
} }
} }
func WriteArticle(c *control.Config, db *model.DB) http.HandlerFunc { func WriteArticle(c *control.CliArgs, db *model.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
tags, err := db.GetTagList() tags, err := db.GetTagList()
if err != nil { if err != nil {
@ -45,7 +45,7 @@ func WriteArticle(c *control.Config, db *model.DB) http.HandlerFunc {
} }
} }
func SubmitArticle(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func SubmitArticle(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
session, err := s.Get(r, "cookie") session, err := s.Get(r, "cookie")
if err != nil { if err != nil {
@ -93,7 +93,7 @@ func SubmitArticle(c *control.Config, db *model.DB, s *control.CookieStore) http
} }
} }
func ResubmitArticle(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func ResubmitArticle(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil { if err != nil {
@ -147,7 +147,7 @@ func ResubmitArticle(c *control.Config, db *model.DB, s *control.CookieStore) ht
} }
} }
func ShowUnpublishedArticles(c *control.Config, db *model.DB) http.HandlerFunc { func ShowUnpublishedArticles(c *control.CliArgs, db *model.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
unpublishedArticles, err := db.GetCertainArticles(false, false) unpublishedArticles, err := db.GetCertainArticles(false, false)
if err != nil { if err != nil {
@ -162,7 +162,7 @@ func ShowUnpublishedArticles(c *control.Config, db *model.DB) http.HandlerFunc {
} }
} }
func ShowRejectedArticles(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func ShowRejectedArticles(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
type htmlData struct { type htmlData struct {
MyIDs map[int64]bool MyIDs map[int64]bool
@ -197,7 +197,7 @@ func ShowRejectedArticles(c *control.Config, db *model.DB, s *control.CookieStor
} }
} }
func ReviewUnpublishedArticle(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func ReviewUnpublishedArticle(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
type htmlData struct { type htmlData struct {
Title string Title string
@ -259,7 +259,7 @@ func ReviewUnpublishedArticle(c *control.Config, db *model.DB, s *control.Cookie
} }
} }
func ReviewRejectedArticle(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func ReviewRejectedArticle(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
type htmlData struct { type htmlData struct {
Selected map[int64]bool Selected map[int64]bool
@ -306,7 +306,7 @@ func ReviewRejectedArticle(c *control.Config, db *model.DB, s *control.CookieSto
} }
} }
func PublishArticle(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func PublishArticle(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil { if err != nil {
@ -356,7 +356,7 @@ func PublishArticle(c *control.Config, db *model.DB, s *control.CookieStore) htt
} }
} }
func RejectArticle(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func RejectArticle(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil { if err != nil {
@ -386,7 +386,7 @@ func RejectArticle(c *control.Config, db *model.DB, s *control.CookieStore) http
} }
} }
func ShowCurrentArticles(c *control.Config, db *model.DB) http.HandlerFunc { func ShowCurrentArticles(c *control.CliArgs, db *model.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
articles, err := db.GetCurrentIssueArticles() articles, err := db.GetCurrentIssueArticles()
if err != nil { if err != nil {
@ -400,7 +400,7 @@ func ShowCurrentArticles(c *control.Config, db *model.DB) http.HandlerFunc {
} }
} }
func UploadImage(c *control.Config) http.HandlerFunc { func UploadImage(c *control.CliArgs) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("article-image") file, header, err := r.FormFile("article-image")
if err != nil { if err != nil {

View File

@ -8,14 +8,14 @@ import (
"streifling.com/jason/cpolis/cmd/model" "streifling.com/jason/cpolis/cmd/model"
) )
func CreateTag(c *control.Config) http.HandlerFunc { func CreateTag(c *control.CliArgs) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles(c.WebDir + "/templates/add-tag.html") tmpl, err := template.ParseFiles(c.WebDir + "/templates/add-tag.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil) template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil)
} }
} }
func AddTag(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func AddTag(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
db.AddTag(r.PostFormValue("tag")) db.AddTag(r.PostFormValue("tag"))

View File

@ -8,7 +8,7 @@ import (
"streifling.com/jason/cpolis/cmd/control" "streifling.com/jason/cpolis/cmd/control"
) )
func ServeImage(c *control.Config, s *control.CookieStore) http.HandlerFunc { func ServeImage(c *control.CliArgs, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
absFilepath, err := filepath.Abs(c.PicsDir) absFilepath, err := filepath.Abs(c.PicsDir)
if err != nil { if err != nil {

View File

@ -9,7 +9,7 @@ import (
"streifling.com/jason/cpolis/cmd/model" "streifling.com/jason/cpolis/cmd/model"
) )
func PublishLatestIssue(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func PublishLatestIssue(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if err := db.PublishLatestIssue(); err != nil { if err := db.PublishLatestIssue(); err != nil {
log.Println(err) log.Println(err)

View File

@ -27,7 +27,7 @@ func saveSession(w http.ResponseWriter, r *http.Request, s *control.CookieStore,
return nil return nil
} }
func HomePage(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func HomePage(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
numRows, err := db.CountEntries("users") numRows, err := db.CountEntries("users")
if err != nil { if err != nil {
@ -54,7 +54,7 @@ func HomePage(c *control.Config, db *model.DB, s *control.CookieStore) http.Hand
} }
} }
func Login(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func Login(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
userName := r.PostFormValue("username") userName := r.PostFormValue("username")
password := r.PostFormValue("password") password := r.PostFormValue("password")
@ -89,7 +89,7 @@ func Login(c *control.Config, db *model.DB, s *control.CookieStore) http.Handler
} }
} }
func Logout(c *control.Config, s *control.CookieStore) http.HandlerFunc { func Logout(c *control.CliArgs, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
session, err := s.Get(r, "cookie") session, err := s.Get(r, "cookie")
if err != nil { if err != nil {

View File

@ -31,14 +31,14 @@ func checkUserStrings(user *model.User) (string, int, bool) {
} }
} }
func CreateUser(c *control.Config) http.HandlerFunc { func CreateUser(c *control.CliArgs) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles(c.WebDir + "/templates/add-user.html") tmpl, err := template.ParseFiles(c.WebDir + "/templates/add-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil) template.Must(tmpl, err).ExecuteTemplate(w, "page-content", nil)
} }
} }
func AddUser(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func AddUser(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
role, err := strconv.Atoi(r.PostFormValue("role")) role, err := strconv.Atoi(r.PostFormValue("role"))
if err != nil { if err != nil {
@ -95,20 +95,12 @@ func AddUser(c *control.Config, db *model.DB, s *control.CookieStore) http.Handl
return return
} }
session, err := s.Get(r, "cookie")
if err != nil {
tmpl, err := template.ParseFiles(c.WebDir + "/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(c.WebDir + "/templates/hub.html") tmpl, err := template.ParseFiles(c.WebDir + "/templates/hub.html")
tmpl = template.Must(tmpl, err) template.Must(tmpl, err).ExecuteTemplate(w, "page-content", 0)
tmpl.ExecuteTemplate(w, "page-content", session.Values["role"].(int))
} }
} }
func EditSelf(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func EditUser(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
session, err := s.Get(r, "cookie") session, err := s.Get(r, "cookie")
if err != nil { if err != nil {
@ -124,12 +116,12 @@ func EditSelf(c *control.Config, db *model.DB, s *control.CookieStore) http.Hand
return return
} }
tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-self.html") tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", user) template.Must(tmpl, err).ExecuteTemplate(w, "page-content", user)
} }
} }
func UpdateSelf(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func UpdateUser(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
session, err := s.Get(r, "cookie") session, err := s.Get(r, "cookie")
if err != nil { if err != nil {
@ -180,7 +172,7 @@ func UpdateSelf(c *control.Config, db *model.DB, s *control.CookieStore) http.Ha
} }
} }
if err = db.UpdateOwnAttributes( if err = db.UpdateUserAttributes(
userData.ID, userData.ID,
userData.UserName, userData.UserName,
userData.FirstName, userData.FirstName,
@ -199,7 +191,7 @@ func UpdateSelf(c *control.Config, db *model.DB, s *control.CookieStore) http.Ha
} }
} }
func AddFirstUser(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc { func AddFirstUser(c *control.CliArgs, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var err error var err error
@ -273,165 +265,3 @@ func AddFirstUser(c *control.Config, db *model.DB, s *control.CookieStore) http.
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", 0) template.Must(tmpl, err).ExecuteTemplate(w, "page-content", 0)
} }
} }
func ShowAllUsers(c *control.Config, db *model.DB, s *control.CookieStore, action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
type htmlData struct {
Users map[int64]*model.User
Action string
}
data := &htmlData{Action: action}
data.Users, err = db.GetAllUsers()
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(c.WebDir + "/templates/login.html")
msg := "Session nicht mehr gültig. Bitte erneut anmelden."
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
}
delete(data.Users, session.Values["id"].(int64))
tmpl, err := template.ParseFiles(c.WebDir + "/templates/show-all-users.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", data)
}
}
func EditUser(c *control.Config, db *model.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if 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
}
tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", user)
}
}
func UpdateUser(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
role, err := strconv.Atoi(r.PostFormValue("role"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userData := UserData{
User: &model.User{
ID: id,
UserName: r.PostFormValue("username"),
FirstName: r.PostFormValue("first-name"),
LastName: r.PostFormValue("last-name"),
Role: role,
},
}
newPass := r.PostFormValue("password")
newPass2 := r.PostFormValue("password2")
if len(userData.UserName) == 0 || len(userData.FirstName) == 0 ||
len(userData.LastName) == 0 {
userData.Msg = "Alle Felder mit * müssen ausgefüllt sein."
tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-user.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", userData.Msg)
return
}
userString, stringLen, ok := checkUserStrings(userData.User)
if !ok {
userData.Msg = fmt.Sprint(userString, " ist zu lang. Maximal ",
stringLen, " Zeichen erlaubt.")
tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-user.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", userData)
return
}
if id, ok := db.GetID(userData.UserName); ok {
if id != userData.ID {
userData.Msg = "Benutzername bereits vergeben."
userData.UserName = ""
tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-user.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", userData)
return
}
}
if err = db.UpdateUserAttributes(
userData.ID,
userData.UserName,
userData.FirstName,
userData.LastName,
newPass,
newPass2,
userData.Role); err != nil {
userData.Msg = "Aktualisierung der Benutzerdaten fehlgeschlagen."
tmpl, err := template.ParseFiles(c.WebDir + "/templates/edit-user.html")
template.Must(tmpl, err).ExecuteTemplate(w, "page-content", userData)
}
session, err := s.Get(r, "cookie")
if err != nil {
tmpl, err := template.ParseFiles(c.WebDir + "/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(c.WebDir + "/templates/hub.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", session.Values["role"].(int))
}
}
func DeleteUser(c *control.Config, db *model.DB, s *control.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = db.DeleteUser(id); 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(c.WebDir + "/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(c.WebDir + "/templates/hub.html")
tmpl = template.Must(tmpl, err)
tmpl.ExecuteTemplate(w, "page-content", session.Values["role"].(int))
}
}

1
go.mod
View File

@ -4,7 +4,6 @@ go 1.22.0
require ( require (
git.streifling.com/jason/rss v0.1.2 git.streifling.com/jason/rss v0.1.2
github.com/BurntSushi/toml v1.3.2
github.com/go-sql-driver/mysql v1.7.1 github.com/go-sql-driver/mysql v1.7.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/gorilla/sessions v1.2.2 github.com/gorilla/sessions v1.2.2

2
go.sum
View File

@ -1,7 +1,5 @@
git.streifling.com/jason/rss v0.1.2 h1:UB3UHJXMt5WDDh9y8n0Z6nS1XortbPXjEr7QZTdovY4= git.streifling.com/jason/rss v0.1.2 h1:UB3UHJXMt5WDDh9y8n0Z6nS1XortbPXjEr7QZTdovY4=
git.streifling.com/jason/rss v0.1.2/go.mod h1:gpZF0nZbQSstMpyHD9DTAvlQEG7v4pjO5c7aIMWM4Jg= git.streifling.com/jason/rss v0.1.2/go.mod h1:gpZF0nZbQSstMpyHD9DTAvlQEG7v4pjO5c7aIMWM4Jg=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= 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/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 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=

View File

@ -40,7 +40,7 @@
</div> </div>
<div> <div>
<input required id="admin" name="role" type="radio" value="0" {{if eq .Role 0 }}checked{{end}} /> <input required id="admin" name="role" type="radio" value="0" {{if eq .Role 0 }}checked{{end}} />
<label for="admin">Administrator</label> <label for="admin">Admin</label>
</div> </div>
</div> </div>

View File

@ -1,43 +0,0 @@
{{define "page-content"}}
<h2>Profil bearbeiten</h2>
<form>
<div class="grid grid-cols-3 gap-4">
<div>
<label for="username">Benutzername</label>
<input class="w-full" name="username" type="text" value="{{.UserName}}" />
</div>
<div>
<label for="first-name">Vorname</label>
<input class="w-full" name="first-name" type="text" value="{{.FirstName}}" />
</div>
<div>
<label for="last-name">Nachname</label>
<input class="w-full" name="last-name" type="text" value="{{.LastName}}" />
</div>
<div>
<label for="old-password">Altes Passwort</label>
<input class="w-full" name="old-password" placeholder="***" type="password" />
</div>
<div>
<label for="password">Passwort</label>
<input class="w-full" name="password" placeholder="***" type="password" />
</div>
<div>
<label for="password2">Passwort wiederholen</label>
<input class="w-full" name="password2" placeholder="***" type="password" />
</div>
</div>
<div class="btn-area">
<input class="action-btn" type="submit" value="Aktualisieren" hx-post="/update-self"
hx-target="#page-content" />
<button class="btn" hx-get="/hub" hx-target="#page-content">Abbrechen</button>
</div>
</form>
{{end}}

View File

@ -1,5 +1,5 @@
{{define "page-content"}} {{define "page-content"}}
<h2>Profil von {{.FirstName}} {{.LastName}} bearbeiten</h2> <h2>Benutzerdaten bearbeiten</h2>
<form> <form>
<div class="grid grid-cols-3 gap-4"> <div class="grid grid-cols-3 gap-4">
@ -7,49 +7,30 @@
<label for="username">Benutzername</label> <label for="username">Benutzername</label>
<input class="w-full" name="username" type="text" value="{{.UserName}}" /> <input class="w-full" name="username" type="text" value="{{.UserName}}" />
</div> </div>
<div> <div>
<label for="first-name">Vorname</label> <label for="first-name">Vorname</label>
<input class="w-full" name="first-name" type="text" value="{{.FirstName}}" /> <input class="w-full" name="first-name" type="text" value="{{.FirstName}}" />
</div> </div>
<div> <div>
<label for="last-name">Nachname</label> <label for="last-name">Nachname</label>
<input class="w-full" name="last-name" type="text" value="{{.LastName}}" /> <input class="w-full" name="last-name" type="text" value="{{.LastName}}" />
</div> </div>
<div>
<label for="old-password">Altes Passwort</label>
<input class="w-full" name="old-password" placeholder="***" type="password" />
</div>
<div> <div>
<label for="password">Passwort</label> <label for="password">Passwort</label>
<input class="w-full" name="password" placeholder="***" type="password" /> <input class="w-full" name="password" placeholder="***" type="password" />
</div> </div>
<div> <div>
<label for="password2">Passwort wiederholen</label> <label for="password2">Passwort wiederholen</label>
<input class="w-full" name="password2" placeholder="***" type="password" /> <input class="w-full" name="password2" placeholder="***" type="password" />
</div> </div>
</div> </div>
<div class="flex gap-4">
<div>
<input required id="author" name="role" type="radio" value="3" {{if eq .Role 3 }}checked{{end}} />
<label for="author">Autor</label>
</div>
<div>
<input required id="editor" name="role" type="radio" value="2" {{if eq .Role 2 }}checked{{end}} />
<label for="editor">Redakteur</label>
</div>
<div>
<input required id="publisher" name="role" type="radio" value="1" {{if eq .Role 1 }}checked{{end}} />
<label for="publisher">Herausgeber</label>
</div>
<div>
<input required id="admin" name="role" type="radio" value="0" {{if eq .Role 0 }}checked{{end}} />
<label for="admin">Administrator</label>
</div>
</div>
<div class="btn-area"> <div class="btn-area">
<input class="action-btn" type="submit" value="Aktualisieren" hx-post="/update-user/{{.ID}}" <input class="action-btn" type="submit" value="Aktualisieren" hx-post="/update-user"
hx-target="#page-content" /> hx-target="#page-content" />
<button class="btn" hx-get="/hub" hx-target="#page-content">Abbrechen</button> <button class="btn" hx-get="/hub" hx-target="#page-content">Abbrechen</button>
</div> </div>

View File

@ -2,17 +2,15 @@
<div class="flex flex-col gap-4"> <div class="flex flex-col gap-4">
<button class="btn" hx-get="/logout" hx-target="#page-content">Abmelden</button> <button class="btn" hx-get="/logout" hx-target="#page-content">Abmelden</button>
{{if lt . 4}}
<div class="mb-3"> <div class="mb-3">
<h2>Autor</h2> <h2>Autor</h2>
<div class="grid grid-cols-2 gap-x-4 gap-y-2"> <div class="grid grid-cols-2 gap-x-4 gap-y-2">
<button class="btn" hx-get="/write-article" hx-target="#page-content">Artikel schreiben</button> <button class="btn" hx-get="/write-article" hx-target="#page-content">Artikel schreiben</button>
<button class="btn" hx-get="/rejected-articles" hx-target="#page-content">Abgelehnte Artikel</button> <button class="btn" hx-get="/rejected-articles" hx-target="#page-content">Abgelehnte Artikel</button>
<a class="btn text-center" href="/rss">RSS Feed</a> <a class="btn text-center" href="/rss">RSS Feed</a>
<button class="btn" hx-get="/edit-self" hx-target="#page-content">Profil bearbeiten</button> <button class="btn" hx-get="/edit-user" hx-target="#page-content">Benutzer bearbeiten</button>
</div> </div>
</div> </div>
{{end}}
{{if lt . 3}} {{if lt . 3}}
<div class="mb-3"> <div class="mb-3">
@ -38,10 +36,8 @@
{{if eq . 0}} {{if eq . 0}}
<div class="mb-3"> <div class="mb-3">
<h2>Administrator</h2> <h2>Administrator</h2>
<div class="grid grid-cols-3 gap-4"> <div class="grid grid-cols-2 gap-4">
<button class="btn" hx-get="/create-user" hx-target="#page-content">Benutzer hinzufügen</button> <button class="btn" hx-get="/create-user" hx-target="#page-content">Benutzer hinzufügen</button>
<button class="btn" hx-get="/show-all-users-edit" hx-target="#page-content">Benutzer bearbeiten</button>
<button class="btn" hx-get="/show-all-users-delete" hx-target="#page-content">Benutzer löschen</button>
</div> </div>
</div> </div>
{{end}} {{end}}

View File

@ -1,24 +0,0 @@
{{define "page-content"}}
<h2>Alle Benutzer</h2>
<div class="flex flex-col gap-4">
{{range .Users}}
<button class="btn" hx-get="/{{$.Action}}/{{.ID}}" hx-target="#page-content">
<h1 class="font-bold text-2xl">
{{.UserName}}
({{if eq .Role 0}}
Administrator
{{else if eq .Role 1}}
Herausgeber
{{else if eq .Role 2}}
Redakteur
{{else}}
Autor
{{end}})
</h1>
<p>{{.FirstName}} {{.LastName}}</p>
</button>
{{end}}
<button class="action-btn" hx-get="/hub" hx-target="#page-content">Zurück</button>
</div>
{{end}}