Browse Source

Merge branch 'develop'

master v0.7.17
Lars Hoogestraat 1 month ago
parent
commit
385c1207d3
59 changed files with 511 additions and 625 deletions
  1. +0
    -3
      .gitignore
  2. +7
    -1
      Makefile
  3. +27
    -33
      clt/createuser/create_user.go
  4. +2
    -2
      clt/initdatabase/init_database.go
  5. +18
    -33
      crypt/crypt.go
  6. +2
    -7
      database/database.go
  7. +7
    -8
      go.mod
  8. +20
    -19
      go.sum
  9. +11
    -11
      handler/account.go
  10. +5
    -5
      handler/account_test.go
  11. +6
    -5
      handler/article.go
  12. +10
    -10
      handler/article_test.go
  13. +2
    -2
      handler/category.go
  14. +7
    -7
      handler/category_test.go
  15. +1
    -1
      handler/const.go
  16. +3
    -3
      handler/file.go
  17. +6
    -6
      handler/file_test.go
  18. +2
    -2
      handler/form_util.go
  19. +1
    -1
      handler/login.go
  20. +3
    -3
      handler/login_test.go
  21. +2
    -2
      handler/site.go
  22. +10
    -10
      handler/site_test.go
  23. +0
    -0
      handler/testdata/color.png
  24. +6
    -6
      handler/user.go
  25. +1
    -1
      handler/user_invite.go
  26. +5
    -5
      handler/user_invite_test.go
  27. +6
    -6
      handler/user_test.go
  28. +8
    -8
      handler/utils_test.go
  29. +0
    -17
      httperror/error.go
  30. +3
    -8
      logger/log.go
  31. +1
    -1
      mail/mail.go
  32. +3
    -3
      main.go
  33. +17
    -17
      middleware/json_handler.go
  34. +10
    -6
      middleware/middleware_util.go
  35. +6
    -8
      middleware/template.go
  36. +12
    -10
      middleware/template_handler.go
  37. +5
    -5
      middleware/xml_handler.go
  38. +17
    -19
      models/article.go
  39. +4
    -3
      models/article_sqlite.go
  40. +6
    -6
      models/category.go
  41. +3
    -3
      models/category_sqlite.go
  42. +37
    -4
      models/file.go
  43. +1
    -4
      models/file_sqlite.go
  44. +2
    -2
      models/html.go
  45. +3
    -4
      models/mail.go
  46. +13
    -15
      models/pagination.go
  47. +5
    -4
      models/site.go
  48. +4
    -8
      models/site_sqlite.go
  49. +1
    -1
      models/sql.go
  50. +9
    -7
      models/token.go
  51. +23
    -19
      models/user.go
  52. +5
    -5
      models/user_invite.go
  53. +5
    -10
      models/user_invite_sqlite.go
  54. +4
    -12
      models/user_sqlite.go
  55. +78
    -78
      routers/router.go
  56. +3
    -7
      settings/config.go
  57. +50
    -0
      slug/slug.go
  58. +3
    -3
      slug/slug_test.go
  59. +0
    -136
      utils/strings.go

+ 0
- 3
.gitignore View File

@ -32,9 +32,6 @@ releases
.idea
.csrftoken
/clt/createUser
/clt/initDatabase
/go-blog
releases
db/


+ 7
- 1
Makefile View File

@ -1,8 +1,14 @@
BINARYNAME=go-blog
TMP=tmp
DIST=release
GITHASH=$(shell git rev-parse HEAD)
BUILD_VERSION=$(shell git describe --tags)
ifndef $(GOPATH)
GOPATH=$(shell go env GOPATH)
export GOPATH
endif
RELEASE="releases"
LDFLAGS=-ldflags '-X main.BuildVersion=${BUILD_VERSION} -X main.GitHash=${GITHASH}'
@ -24,7 +30,7 @@ install:
package:
-rm -r ${TMP}
mkdir -p ${TMP}/clt
-mkdir -p releases
-mkdir -p releases/custom
cp ${GOPATH}/bin/go-blog ${TMP}/
cp ${GOPATH}/bin/create_user ${TMP}/clt
cp ${GOPATH}/bin/init_database ${TMP}/clt


+ 27
- 33
clt/createuser/create_user.go View File

@ -12,10 +12,9 @@ import (
"os"
"syscall"
"git.hoogi.eu/snafu/go-blog/components/database"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/database"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/models"
"git.hoogi.eu/snafu/go-blog/utils"
"golang.org/x/crypto/ssh/terminal"
)
@ -38,14 +37,31 @@ func main() {
fmt.Printf("create_user version %s\n", BuildVersion)
username := flag.String("username", "", "Username for the admin user ")
email := flag.String("email", "", "Email for the created user ")
displayName := flag.String("displayname", "", "Display name for the admin user ")
isAdmin := flag.Bool("admin", false, "If set a new administrator will be created; otherwise a non-admin is created")
file := flag.String("sqlite", "", "Location to the sqlite3 database file")
username := flag.String("username", "", "Username for the admin user. (required)")
email := flag.String("email", "", "Email for the created user. (required)")
displayName := flag.String("displayname", "", "Display name for the admin user. (required)")
isAdmin := flag.Bool("admin", false, "If set a new user with admin permissions will be created; otherwise a non-admin is created.")
file := flag.String("sqlite", "", "Location to the sqlite3 database file. (required)")
flag.Parse()
if *username == "" {
fmt.Println("the username (-username) must be specified")
os.Exit(1)
}
if *email == "" {
fmt.Println("the email (-email) must be specified")
os.Exit(1)
}
if *displayName == "" {
fmt.Println("the display name (-displayname) must be specified")
os.Exit(1)
}
if *file == "" {
fmt.Println("the argument -sqlite is empty. Please specify the location of the sqlite3 database file")
os.Exit(1)
}
if flag.Parsed() {
initUser := createUserFlag{
username: *username,
@ -55,16 +71,13 @@ func main() {
sqlite: *file,
}
if err := initUser.validate(); err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Password: ")
pw, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Println("")
if err != nil {
fmt.Printf("could not read password %v", err)
fmt.Printf("could not read password %v\n", err)
os.Exit(1)
}
@ -85,26 +98,7 @@ func main() {
}
}
func (userFlags createUserFlag) validate() error {
if utils.TrimmedStringIsEmpty(userFlags.username) {
return fmt.Errorf("the username (-username) must be specified")
}
if utils.TrimmedStringIsEmpty(userFlags.email) {
return fmt.Errorf("the email (-email) must be specified")
}
if utils.TrimmedStringIsEmpty(userFlags.displayName) {
return fmt.Errorf("the display name (-displayname) must be specified")
}
if utils.TrimmedStringIsEmpty(userFlags.sqlite) {
return fmt.Errorf("the argument -sqlite is empty. Please specify the location of the sqlite3 database file")
}
return nil
}
func (userFlags createUserFlag) CreateUser() error {
var userService models.UserService
dbConfig := database.SQLiteConfig{


+ 2
- 2
clt/initdatabase/init_database.go View File

@ -12,8 +12,8 @@ import (
"os"
"strings"
"git.hoogi.eu/snafu/go-blog/components/database"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/database"
"git.hoogi.eu/snafu/go-blog/logger"
)
var (


utils/crypt.go → crypt/crypt.go View File

@ -2,46 +2,45 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package utils
//package crypt
package crypt
import (
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"math/big"
"golang.org/x/crypto/bcrypt"
)
const (
var (
//AlphaUpper all upper alphas chars
AlphaUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
AlphaUpper = RandomSource("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
//AlphaLower all lowers alphas chars
AlphaLower = "abcdefghijklmnopqrstuvwxyz"
AlphaLower = RandomSource("abcdefghijklmnopqrstuvwxyz")
//AlphaUpperLower all upper and lowers aplhas chars
AlphaUpperLower = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
AlphaUpperLower = RandomSource("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
//AlphaUpperLowerNumeric all upper lowers alphas and numerics
AlphaUpperLowerNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz"
//AlphaUpperLowerNumericSpecial all upper lowers alphas, numerics and special chas
AlphaUpperLowerNumericSpecial = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456890" +
"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
AlphaUpperLowerNumeric = RandomSource("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz")
//AlphaUpperLowerNumericSpecial all upper lowers alphas, numerics and special chars
AlphaUpperLowerNumericSpecial = RandomSource("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456890" +
"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
)
//RandomSource express which chars should be considered
type RandomSource struct {
CharsToGen string
}
//RandomSource string containing which characters should be considered when generating random sequences
type RandomSource string
//RandomSequence returns random character with given length;
//random source express which chars should be considered
func (r RandomSource) RandomSequence(length int) []byte {
result := make([]byte, length)
for i := 0; i < length; i++ {
char, _ := rand.Int(rand.Reader, big.NewInt(int64(len(r.CharsToGen))))
result[i] = r.CharsToGen[int(char.Int64())]
char, _ := rand.Int(rand.Reader, big.NewInt(int64(len(r))))
result[i] = r[int(char.Int64())]
}
fmt.Println(result)
return result
}
@ -54,7 +53,7 @@ func RandomSecureKey(length int) []byte {
return k
}
//CryptPassword bcrypts a password at given costs
//CryptPassword hashes a password with bcrypt and a given cost
func CryptPassword(password []byte, cost int) ([]byte, error) {
s, err := bcrypt.GenerateFromPassword(password, cost)
@ -67,21 +66,7 @@ func CryptPassword(password []byte, cost int) ([]byte, error) {
//GenerateSalt generates a random salt with alphanumerics and some special characters
func GenerateSalt() []byte {
r := RandomSource{
CharsToGen: AlphaUpperLowerNumericSpecial,
}
return r.RandomSequence(32)
}
//EncodeBase64 encodes a string to base64
func EncodeBase64(input string) string {
return base64.StdEncoding.EncodeToString([]byte(input))
}
//DecodeBase64 descodes a string to base64
func DecodeBase64(b64 string) (string, error) {
out, err := base64.StdEncoding.DecodeString(b64)
return string(out), err
return AlphaUpperLowerNumericSpecial.RandomSequence(32)
}
func RandomHash(length int) string {

components/database/database.go → database/database.go View File

@ -17,13 +17,7 @@ type SQLiteConfig struct {
//Open receives handle for sqlite database, returns an error if connection failed
func (d SQLiteConfig) Open() (*sql.DB, error) {
db, err := sql.Open("sqlite3", d.File)
if err != nil {
return nil, err
}
return db, nil
return sql.Open("sqlite3", d.File)
}
//InitTables creates the tables
@ -148,5 +142,6 @@ func InitTables(db *sql.DB) error {
");"); err != nil {
return err
}
return nil
}

+ 7
- 8
go.mod View File

@ -4,17 +4,16 @@ go 1.15
require (
git.hoogi.eu/snafu/cfg v1.0.6
git.hoogi.eu/snafu/session v1.1.2
git.hoogi.eu/snafu/session v1.2.0
github.com/gorilla/csrf v1.7.0
github.com/gorilla/handlers v1.5.1
github.com/gorilla/mux v1.8.0
github.com/justinas/alice v1.2.0
github.com/mattn/go-sqlite3 v1.14.3
github.com/mattn/go-sqlite3 v1.14.5
github.com/microcosm-cc/bluemonday v1.0.4
github.com/russross/blackfriday/v2 v2.0.1
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/sirupsen/logrus v1.6.0
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a
golang.org/x/net v0.0.0-20200904194848-62affa334b73 // indirect
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009 // indirect
github.com/russross/blackfriday/v2 v2.1.0
github.com/sirupsen/logrus v1.7.0
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb // indirect
golang.org/x/sys v0.0.0-20201204225414-ed752295db88 // indirect
)

+ 20
- 19
go.sum View File

@ -2,6 +2,8 @@ git.hoogi.eu/snafu/cfg v1.0.6 h1:O34hYFqjwfnMjEwB4M8GaQQmBtf3H+AA0RFHb7PoMNs=
git.hoogi.eu/snafu/cfg v1.0.6/go.mod h1:LQolv8bqH8ZPz7h9PSVswdBXj1BIM+kW79AVS/jpE7A=
git.hoogi.eu/snafu/session v1.1.2 h1:MclTbSqD/9JodRUqFc4OwyJGk5AtonqB6BaG5RRJHf8=
git.hoogi.eu/snafu/session v1.1.2/go.mod h1:kgRDrnHcKc9H18G9533BXy6qO+81eBf6e9gkUzBMDuA=
git.hoogi.eu/snafu/session v1.2.0 h1:qmZXMCAZRrzcOOLsOltwPUeA4ckpjwjjJ8fQpFDSx+w=
git.hoogi.eu/snafu/session v1.2.0/go.mod h1:kgRDrnHcKc9H18G9533BXy6qO+81eBf6e9gkUzBMDuA=
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/chris-ramon/douceur v0.2.0 h1:IDMEdxlEUUBYBKE4z/mJnFyVXox+MjuEVDJNN27glkU=
@ -22,37 +24,36 @@ github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyC
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/mattn/go-sqlite3 v1.14.3 h1:j7a/xn1U6TKA/PHHxqZuzh64CdtRc7rU9M+AvkOl5bA=
github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/microcosm-cc/bluemonday v1.0.4 h1:p0L+CTpo/PLFdkoPcJemLXG+fpMD7pYOoDEq1axMbGg=
github.com/microcosm-cc/bluemonday v1.0.4/go.mod h1:8iwZnFn2CDDNZ0r6UXhF4xawGvzaqzCRa1n3/lO3W2w=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c h1:9HhBz5L/UjnK9XLtiZhYAdue5BVKep3PMmS2LuPDt8k=
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200904194848-62affa334b73 h1:MXfv8rhZWmFeqX3GNZRsd6vOLoaCHjYEX3qkRo3YBUA=
golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009 h1:W0lCpv29Hv0UaM1LXb9QlBHLNP8UFfcKjblhVCWftOM=
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88 h1:KmZPnMocC93w341XZp26yTJg8Za7lhb2KhkYmixoeso=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
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/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

controllers/account.go → handler/account.go View File

@ -1,4 +1,4 @@
package controllers
package handler
import (
"bytes"
@ -8,8 +8,8 @@ import (
"net/http"
"time"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -57,7 +57,7 @@ func AdminProfilePostHandler(ctx *middleware.AppContext, w http.ResponseWriter,
if len(u.PlainPassword) > 0 {
changePassword = true
// Password change
u.PlainPassword = []byte(r.FormValue("password"))
if !bytes.Equal(u.PlainPassword, []byte(r.FormValue("retyped_password"))) {
@ -81,11 +81,11 @@ func AdminProfilePostHandler(ctx *middleware.AppContext, w http.ResponseWriter,
session.SetValue("userid", u.ID)
sids := ctx.SessionService.SessionProvider.SessionIDsFromValues("userid", u.ID)
sessions := ctx.SessionService.SessionProvider.FindSessionsByValue("userid", u.ID)
for _, sid := range sids {
if sid != session.SessionID() {
ctx.SessionService.SessionProvider.Remove(sid)
for _, sid := range sessions {
if sid.SessionID() != session.SessionID() {
ctx.SessionService.SessionProvider.Remove(sid.SessionID())
}
}
}
@ -230,7 +230,7 @@ func ResetPasswordHandler(ctx *middleware.AppContext, w http.ResponseWriter, r *
//ResetPasswordPostHandler handles the resetting of the password
func ResetPasswordPostHandler(ctx *middleware.AppContext, w http.ResponseWriter, r *http.Request) *middleware.Template {
password := r.FormValue("password")
repassword := r.FormValue("password_repeat")
password2 := r.FormValue("password_repeat")
hash := getVar(r, "hash")
t, err := ctx.TokenService.Get(hash, models.PasswordReset, time.Duration(1)*time.Hour)
@ -251,7 +251,7 @@ func ResetPasswordPostHandler(ctx *middleware.AppContext, w http.ResponseWriter,
}
}
if password != repassword {
if password != password2 {
return &middleware.Template{
Name: tplAdminResetPassword,
Err: httperror.New(http.StatusUnprocessableEntity, "The passwords entered do not match.", errors.New("the password entered did not match")),
@ -297,7 +297,7 @@ func ForgotPasswordPostHandler(ctx *middleware.AppContext, w http.ResponseWriter
u, err := ctx.UserService.GetByMail(email)
if err != nil {
if httperror.Equals(err, sql.ErrNoRows) {
if errors.Is(err, sql.ErrNoRows) {
logger.Log.Error(err)
return &middleware.Template{
RedirectPath: "admin",

controllers/account_test.go → handler/account_test.go View File

@ -1,11 +1,11 @@
package controllers_test
package handler_test
import (
"net/http/httptest"
"net/url"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -94,7 +94,7 @@ func doAdminProfileRequest(user reqUser, u *models.User, currentPassword string)
rw := httptest.NewRecorder()
re := r.buildRequest()
tpl := controllers.AdminProfilePostHandler(ctx, rw, re)
tpl := handler.AdminProfilePostHandler(ctx, rw, re)
if tpl.Err != nil {
return tpl.Err
@ -122,7 +122,7 @@ func doActivateAccountRequest(user reqUser, password, passwordRepeat, hash strin
}
rw := httptest.NewRecorder()
tpl := controllers.ActivateAccountPostHandler(ctx, rw, r.buildRequest())
tpl := handler.ActivateAccountPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -150,7 +150,7 @@ func doResetPasswordRequest(user reqUser, password, passwordRepeat, hash string)
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSiteEditPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSiteEditPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err

controllers/article.go → handler/article.go View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers
package handler
import (
"database/sql"
@ -10,10 +10,9 @@ import (
"net/http"
"time"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
"git.hoogi.eu/snafu/go-blog/utils"
)
//GetArticleHandler returns a specific article
@ -21,9 +20,11 @@ import (
func GetArticleHandler(ctx *middleware.AppContext, w http.ResponseWriter, r *http.Request) *middleware.Template {
year := getVar(r, "year")
month := getVar(r, "month")
slug := getVar(r, "slug")
headline := getVar(r, "slug")
a, err := ctx.ArticleService.GetBySlug(utils.AppendString(year, "/", month, "/", slug), nil, models.OnlyPublished)
slug := year + "/" + month + "/" + headline
a, err := ctx.ArticleService.GetBySlug(slug, nil, models.OnlyPublished)
if err != nil {
return &middleware.Template{

controllers/article_test.go → handler/article_test.go View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers_test
package handler_test
import (
"fmt"
@ -13,7 +13,7 @@ import (
"strconv"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -143,7 +143,7 @@ func doGetArticleBySlugRequest(user reqUser, article *models.Article) (*models.A
}
rw := httptest.NewRecorder()
tpl := controllers.GetArticleHandler(ctx, rw, r.buildRequest())
tpl := handler.GetArticleHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -166,7 +166,7 @@ func doGetArticleByIDRequest(user reqUser, articleID int) (*models.Article, erro
}
rw := httptest.NewRecorder()
tpl := controllers.GetArticleByIDHandler(ctx, rw, r.buildRequest())
tpl := handler.GetArticleByIDHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -196,7 +196,7 @@ func doAdminEditArticleRequest(user reqUser, articleID int, article *models.Arti
rw := httptest.NewRecorder()
tpl := controllers.AdminArticleEditPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminArticleEditPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -222,7 +222,7 @@ func doAdminCreateArticleRequest(user reqUser, article *models.Article) (int, er
}
rw := httptest.NewRecorder()
tpl := controllers.AdminArticleNewPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminArticleNewPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return 0, tpl.Err
@ -249,7 +249,7 @@ func doAdminGetArticleByIDRequest(user reqUser, articleID int) (*models.Article,
}
rw := httptest.NewRecorder()
tpl := controllers.AdminPreviewArticleByIDHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminPreviewArticleByIDHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -266,7 +266,7 @@ func doAdminListArticleRequest(user reqUser) ([]models.Article, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminListArticlesHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminListArticlesHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -289,7 +289,7 @@ func doAdminPublishArticleRequest(user reqUser, articleID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminArticlePublishPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminArticlePublishPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -312,7 +312,7 @@ func doAdminRemoveArticleRequest(user reqUser, articleID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminArticleDeletePostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminArticleDeletePostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err

controllers/category.go → handler/category.go View File

@ -2,13 +2,13 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers
package handler
import (
"fmt"
"net/http"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
)

controllers/category_test.go → handler/category_test.go View File

@ -1,4 +1,4 @@
package controllers_test
package handler_test
import (
"net/http/httptest"
@ -6,7 +6,7 @@ import (
"strconv"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -82,7 +82,7 @@ func doAdminGetCategoryRequest(user reqUser, categoryID int) (*models.Category,
}
rw := httptest.NewRecorder()
tpl := controllers.AdminGetCategoryHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminGetCategoryHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -99,7 +99,7 @@ func doAdminListCategoriesRequest(user reqUser) ([]models.Category, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminListCategoriesHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminListCategoriesHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -119,7 +119,7 @@ func doAdminCategoryNewRequest(user reqUser, c *models.Category) (int, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminCategoryNewPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminCategoryNewPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return -1, tpl.Err
@ -144,7 +144,7 @@ func doAdminCategoryEditRequest(user reqUser, c *models.Category) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminCategoryEditPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminCategoryEditPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -166,7 +166,7 @@ func doAdminDeleteCategoryRequest(user reqUser, categoryID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminCategoryDeletePostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminCategoryDeletePostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err

controllers/const.go → handler/const.go View File

@ -1,4 +1,4 @@
package controllers
package handler
const (
tplArticle = "front/article"

controllers/file.go → handler/file.go View File

@ -1,4 +1,4 @@
package controllers
package handler
import (
"errors"
@ -9,8 +9,8 @@ import (
"path/filepath"
"syscall"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
)

controllers/file_test.go → handler/file_test.go View File

@ -1,4 +1,4 @@
package controllers_test
package handler_test
import (
"fmt"
@ -7,7 +7,7 @@ import (
"strconv"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -63,7 +63,7 @@ func doAdminListFilesRequest(user reqUser) ([]models.File, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminListFilesHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminListFilesHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -87,7 +87,7 @@ func doAdminGetFileRequest(user reqUser, uniquename string) (*httptest.ResponseR
rw := httptest.NewRecorder()
fh := controllers.FileHandler{
fh := handler.FileHandler{
Context: ctx,
}
@ -116,7 +116,7 @@ func doAdminUploadFileRequest(user reqUser, file string) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUploadFilePostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUploadFilePostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -139,7 +139,7 @@ func doAdminFileDeleteRequest(user reqUser, fileID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUploadDeletePostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUploadDeletePostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err

controllers/form_util.go → handler/form_util.go View File

@ -2,13 +2,13 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers
package handler
import (
"net/http"
"strconv"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/logger"
"github.com/gorilla/mux"
)

controllers/login.go → handler/login.go View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers
package handler
import (
"net/http"

controllers/login_test.go → handler/login_test.go View File

@ -1,4 +1,4 @@
package controllers_test
package handler_test
import (
"fmt"
@ -6,7 +6,7 @@ import (
"net/url"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
)
func TestLogin(t *testing.T) {
@ -71,7 +71,7 @@ func doLoginRequest(user reqUser, login, password string) (responseWrapper, erro
}
rr := httptest.NewRecorder()
tpl := controllers.LoginPostHandler(ctx, rr, r.buildRequest())
tpl := handler.LoginPostHandler(ctx, rr, r.buildRequest())
if tpl.Err != nil {
return responseWrapper{response: rr, template: tpl}, tpl.Err

controllers/site.go → handler/site.go View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers
package handler
import (
"database/sql"
@ -10,7 +10,7 @@ import (
"fmt"
"net/http"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
)

controllers/site_test.go → handler/site_test.go View File

@ -1,4 +1,4 @@
package controllers_test
package handler_test
import (
"fmt"
@ -7,7 +7,7 @@ import (
"strconv"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -92,7 +92,7 @@ func doGetSiteRequest(user reqUser, link string) (*models.Site, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.GetSiteHandler(ctx, rw, r.buildRequest())
tpl := handler.GetSiteHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -115,7 +115,7 @@ func doAdminGetSiteRequest(user reqUser, siteID int) (*models.Site, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminGetSiteHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminGetSiteHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -132,7 +132,7 @@ func doAdminListSitesRequest(user reqUser) ([]models.Site, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSitesHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSitesHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -156,7 +156,7 @@ func doAdminSiteCreateRequest(user reqUser, s *models.Site) (int, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSiteNewPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSiteNewPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return 0, tpl.Err
@ -185,7 +185,7 @@ func doAdminSitePublishRequest(user reqUser, siteID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSitePublishPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSitePublishPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -215,7 +215,7 @@ func doAdminSiteEditRequest(user reqUser, s *models.Site) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSiteEditPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSiteEditPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -238,7 +238,7 @@ func doAdminSiteDeleteRequest(user reqUser, siteID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSiteDeletePostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSiteDeletePostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -261,7 +261,7 @@ func doAdminSiteOrderRequest(user reqUser, siteID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminSiteOrderHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminSiteOrderHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err

controllers/testdata/color.png → handler/testdata/color.png View File


controllers/user.go → handler/user.go View File

@ -2,13 +2,13 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers
package handler
import (
"fmt"
"net/http"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -196,11 +196,11 @@ func AdminUserEditPostHandler(ctx *middleware.AppContext, w http.ResponseWriter,
}
}
sids := ctx.SessionService.SessionProvider.SessionIDsFromValues("userid", u.ID)
sessions := ctx.SessionService.SessionProvider.FindSessionsByValue("userid", u.ID)
for _, id := range sids {
if session.SessionID() != id {
ctx.SessionService.SessionProvider.Remove(id)
for _, s := range sessions {
if session.SessionID() != s.SessionID() {
ctx.SessionService.SessionProvider.Remove(s.SessionID())
}
}
}

controllers/user_invite.go → handler/user_invite.go View File

@ -1,4 +1,4 @@
package controllers
package handler
import (
"fmt"

controllers/user_invite_test.go → handler/user_invite_test.go View File

@ -1,4 +1,4 @@
package controllers_test
package handler_test
import (
"net/http/httptest"
@ -6,7 +6,7 @@ import (
"strconv"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -70,7 +70,7 @@ func doAdminCreateUserInviteRequest(user reqUser, ui *models.UserInvite) (int, s
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUserInviteNewPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUserInviteNewPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return -1, "", tpl.Err
@ -93,7 +93,7 @@ func doAdminResendUserInviteRequest(user reqUser, inviteID int) (int, string, er
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUserInviteResendPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUserInviteResendPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return -1, "", tpl.Err
@ -116,7 +116,7 @@ func doAdminRemoveUserInviteRequest(user reqUser, inviteID int) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUserInviteDeletePostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUserInviteDeletePostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err

controllers/user_test.go → handler/user_test.go View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers_test
package handler_test
import (
"fmt"
@ -11,7 +11,7 @@ import (
"strconv"
"testing"
"git.hoogi.eu/snafu/go-blog/controllers"
"git.hoogi.eu/snafu/go-blog/handler"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -110,7 +110,7 @@ func doAdminGetUserRequest(user reqUser, userID int) (*models.User, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUserEditHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUserEditHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -156,7 +156,7 @@ func doAdminEditUsersRequest(user reqUser, u *models.User) error {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUserEditPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUserEditPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return tpl.Err
@ -176,7 +176,7 @@ func doAdminListUsersRequest(user reqUser) ([]models.User, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUsersHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUsersHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return nil, tpl.Err
@ -202,7 +202,7 @@ func doAdminCreateUserRequest(user reqUser, u *models.User) (int, error) {
}
rw := httptest.NewRecorder()
tpl := controllers.AdminUserNewPostHandler(ctx, rw, r.buildRequest())
tpl := handler.AdminUserNewPostHandler(ctx, rw, r.buildRequest())
if tpl.Err != nil {
return 0, tpl.Err

controllers/utils_test.go → handler/utils_test.go View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package controllers_test
package handler_test
import (
"bytes"
@ -20,13 +20,13 @@ import (
"path/filepath"
"testing"
"git.hoogi.eu/snafu/go-blog/components/database"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/components/mail"
"git.hoogi.eu/snafu/go-blog/crypt"
"git.hoogi.eu/snafu/go-blog/database"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/mail"
"git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
"git.hoogi.eu/snafu/go-blog/settings"
"git.hoogi.eu/snafu/go-blog/utils"
"git.hoogi.eu/snafu/session"
_ "github.com/mattn/go-sqlite3"
@ -145,9 +145,9 @@ func teardown() {
}
func fillSeeds(db *sql.DB) error {
salt := utils.GenerateSalt()
saltedPassword := utils.AppendBytes([]byte("123456789012"), salt)
password, err := utils.CryptPassword([]byte(saltedPassword), 12)
salt := crypt.GenerateSalt()
saltedPassword := append([]byte("123456789012"), salt[:]...)
password, err := crypt.CryptPassword([]byte(saltedPassword), 12)
if err != nil {
return err

components/httperror/error.go → httperror/error.go View File

@ -84,23 +84,6 @@ func ValueRequired(param string) *Error {
}
}
func Equals(a error, b error) bool {
v, ok := a.(*Error)
v2, ok2 := b.(*Error)
if ok && ok2 {
return v.Err == v2.Err
} else if !ok && !ok2 {
return v == v2
} else if ok && !ok2 {
return v.Err == b
} else if !ok && ok2 {
return a == v2.Err
}
return false
}
func (e Error) Error() string {
return fmt.Sprintf("code=[%d], error=[%s], displayMsg=[%s]", e.HTTPStatus, e.Err.Error(), e.DisplayMsg)
}

components/logger/log.go → logger/log.go View File

@ -14,14 +14,9 @@ import (
//Log returns a new logrus instance
var Log = logrus.New()
//InitLogger initializes the logger. Writes to file with the specified log level
//Valid log levels are:
// debug
// info (fallback)
// warn
// error
// fatal
// panic
//InitLogger initializes the logger
//Valid log levels are: debug|info|warn|error|fatal|panic
//Fallback: info
func InitLogger(w io.Writer, level string) {
level = strings.ToLower(level)

components/mail/mail.go → mail/mail.go View File

@ -6,7 +6,7 @@ import (
"fmt"
"net/smtp"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/logger"
)
//Service holds configuration for the SMTP server

+ 3
- 3
main.go View File

@ -13,9 +13,9 @@ import (
"time"
"git.hoogi.eu/snafu/cfg"
"git.hoogi.eu/snafu/go-blog/components/database"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/components/mail"
"git.hoogi.eu/snafu/go-blog/database"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/mail"
m "git.hoogi.eu/snafu/go-blog/middleware"
"git.hoogi.eu/snafu/go-blog/models"
"git.hoogi.eu/snafu/go-blog/routers"


+ 17
- 17
middleware/json_handler.go View File

@ -8,8 +8,8 @@ import (
"encoding/json"
"net/http"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -23,7 +23,7 @@ type JSONHandler struct {
type JHandler func(*AppContext, http.ResponseWriter, *http.Request) (*models.JSONData, error)
func (fn JSONHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
statusCode := 200
code := http.StatusOK
rw.Header().Set("Content-Type", "application/json")
@ -32,34 +32,34 @@ func (fn JSONHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if err != nil {
switch e := err.(type) {
case *httperror.Error:
statusCode = e.HTTPStatus
code = e.HTTPStatus
default:
statusCode = 500
code = http.StatusInternalServerError
logger.Log.Error(e)
}
logger.Log.Error(err)
mjson, err2 := json.Marshal(err)
if err2 != nil {
logger.Log.Error(err2)
http.Error(rw, err2.Error(), http.StatusInternalServerError)
j, err := json.Marshal(err)
if err != nil {
logger.Log.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.WriteHeader(statusCode)
rw.Write(mjson)
rw.WriteHeader(code)
rw.Write(j)
return
}
mjson, err2 := json.Marshal(data)
j, err := json.Marshal(data)
if err2 != nil {
http.Error(rw, err2.Error(), http.StatusInternalServerError)
rw.WriteHeader(500)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(statusCode)
rw.Write(mjson)
rw.WriteHeader(code)
rw.Write(j)
}

+ 10
- 6
middleware/middleware_util.go View File

@ -5,13 +5,13 @@
package middleware
import (
"encoding/base64"
"net"
"net/http"
"strings"
"time"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/utils"
"git.hoogi.eu/snafu/go-blog/logger"
)
var locals = [...]net.IPNet{
@ -72,7 +72,7 @@ func setCookie(rw http.ResponseWriter, name, path, data string) {
c := &http.Cookie{
Name: name,
Path: path,
Value: utils.EncodeBase64(data),
Value: base64.StdEncoding.EncodeToString([]byte(data)),
}
http.SetCookie(rw, c)
@ -80,6 +80,7 @@ func setCookie(rw http.ResponseWriter, name, path, data string) {
func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, error) {
c, err := r.Cookie(name)
if err != nil {
switch err {
case http.ErrNoCookie:
@ -88,7 +89,9 @@ func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, erro
return "", err
}
}
value, err := utils.DecodeBase64(c.Value)
value, err := base64.StdEncoding.DecodeString(c.Value)
if err != nil {
return "", err
}
@ -98,9 +101,10 @@ func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, erro
Name: name,
MaxAge: -1,
Expires: time.Unix(1, 0),
Path: "/"}
Path: "/",
}
http.SetCookie(w, dc)
return value, nil
return string(value), nil
}

+ 6
- 8
middleware/template.go View File

@ -16,11 +16,10 @@ import (
"time"
"git.hoogi.eu/snafu/cfg"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/models"
"git.hoogi.eu/snafu/go-blog/settings"
"git.hoogi.eu/snafu/go-blog/utils"
)
// Template contains the information about the template to render.
@ -50,6 +49,7 @@ func NotFound(ctx *AppContext, rw http.ResponseWriter, r *http.Request) *Templat
getFlash(rw, r, "SuccessMsg")
session, _ := ctx.SessionService.Get(rw, r)
if session != nil && strings.HasPrefix(r.URL.EscapedPath(), "/admin") {
return &Template{
Name: "admin/error",
@ -157,8 +157,7 @@ func FuncMap(ss models.SiteService, settings *settings.Settings) template.FuncMa
return t.Time.In(time.Local).Format("January 2, 2006 at 3:04 PM")
},
"HumanizeFilesize": func(size int64) string {
fs := cfg.FileSize(size)
return fs.HumanReadable()
return cfg.FileSize(size).HumanReadable()
},
"FormatDateTime": func(t time.Time) string {
return t.In(time.Local).Format("January 2, 2006 at 3:04 PM")
@ -185,8 +184,7 @@ func FuncMap(ss models.SiteService, settings *settings.Settings) template.FuncMa
return template.HTML(models.MarkdownToHTML([]byte(s)))
},
"NToBr": func(in string) template.HTML {
out := models.NewlineToBr(models.EscapeHTML(in))
return template.HTML(out)
return template.HTML(models.NewlineToBr(models.EscapeHTML(in)))
},
"EscapeHTML": func(in string) string {
return html.EscapeString(in)
@ -234,5 +232,5 @@ func (t Template) RedirectURL() string {
if t.RedirectPath[0] == byte('/') {
return t.RedirectPath
}
return utils.AppendString("/", t.RedirectPath)
return "/" + t.RedirectPath
}

+ 12
- 10
middleware/template_handler.go View File

@ -12,8 +12,8 @@ import (
"github.com/gorilla/csrf"
"git.hoogi.eu/snafu/go-blog/components/httperror"
"git.hoogi.eu/snafu/go-blog/components/logger"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/models"
)
@ -34,7 +34,8 @@ type Handler func(*AppContext, http.ResponseWriter, *http.Request) *Template
func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
var errorMsg, warnMsg, successMsg string
statusCode := 200
code := http.StatusOK
ip := getIP(r)
en := logger.Log.WithField("ip", ip)
@ -60,7 +61,7 @@ func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
switch e := t.Err.(type) {
case *httperror.Error:
statusCode = e.HTTPStatus
code = e.HTTPStatus
en.Error(e)
errorMsg = e.DisplayMsg
default:
@ -99,14 +100,14 @@ func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
t.Data[csrf.TemplateTag] = csrf.TemplateField(r)
t.Data["active"] = t.Active
rw.WriteHeader(statusCode)
rw.WriteHeader(code)
if err := fn.AppCtx.Templates.ExecuteTemplate(rw, t.Name, t.Data); err != nil {
en.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
} else {
statusCode = http.StatusFound
code = http.StatusFound
if len(errorMsg) > 0 {
setCookie(rw, "ErrorMsg", "/", errorMsg)
} else if len(warnMsg) > 0 {
@ -114,7 +115,7 @@ func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
} else if len(successMsg) > 0 {
setCookie(rw, "SuccessMsg", "/", successMsg)
}
http.Redirect(rw, r, path.Clean(t.RedirectURL()), statusCode)
http.Redirect(rw, r, path.Clean(t.RedirectURL()), code)
}
}