Browse Source

some formatting / equality replaces with error.Is

cleanup
Lars Hoogestraat 1 month ago
parent
commit
c9a9d0f638
14 changed files with 48 additions and 74 deletions
  1. +0
    -6
      go.sum
  2. +5
    -13
      models/article.go
  3. +4
    -3
      models/article_sqlite.go
  4. +3
    -3
      models/category_sqlite.go
  5. +1
    -4
      models/file_sqlite.go
  6. +2
    -2
      models/html.go
  7. +1
    -0
      models/site.go
  8. +3
    -7
      models/site_sqlite.go
  9. +1
    -1
      models/sql.go
  10. +5
    -3
      models/token.go
  11. +13
    -9
      models/user.go
  12. +1
    -1
      models/user_invite.go
  13. +5
    -10
      models/user_invite_sqlite.go
  14. +4
    -12
      models/user_sqlite.go

+ 0
- 6
go.sum View File

@ -38,22 +38,16 @@ github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1
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-20201124201722-c8d3bf9c5392 h1:xYJJ3S178yv++9zXV/hnr29plCAGO9vAFG9dorqaFQc=
golang.org/x/crypto v0.0.0-20201124201722-c8d3bf9c5392/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
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-20201110031124-69a78807bb2b h1:uwuIcX0g4Yl1NC5XAz37xsr2lTtcqevgzYNVt49waME=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
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-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-20201126233918-771906719818 h1:f1CIuDlJhwANEC2MM87MBEVMr3jl5bifgsfj90XAF9c=
golang.org/x/sys v0.0.0-20201126233918-771906719818/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=


+ 5
- 13
models/article.go View File

@ -73,9 +73,7 @@ func (a *Article) slug(as ArticleService, now time.Time) error {
for i := 0; i < 10; i++ {
a.Slug = a.buildSlug(now, i)
_, err := as.Datasource.GetBySlug(a.Slug, nil, All)
if err != nil {
if _, err := as.Datasource.GetBySlug(a.Slug, nil, All); err != nil {
if errors.Is(err, sql.ErrNoRows) {
break
}
@ -124,18 +122,11 @@ func (as ArticleService) Create(a *Article) (int, error) {
return 0, err
}
err := a.slug(as, now)
if err != nil {
if err := a.slug(as, now); err != nil {
return -1, err
}
artID, err := as.Datasource.Create(a)
if err != nil {
return 0, err
}
return artID, nil
return as.Datasource.Create(a)
}
//Update updates an article
@ -278,7 +269,8 @@ func (as ArticleService) RSSFeed(p *Pagination, pc PublishedCriteria) (RSS, erro
return RSS{}, err
}
items := []RSSItem{}
var items []RSSItem
for _, a := range articles {
link := fmt.Sprint(as.AppConfig.Domain, "/article/by-id/", a.ID)
item := RSSItem{


+ 4
- 3
models/article_sqlite.go View File

@ -76,10 +76,9 @@ func (rdb SQLiteArticleDatasource) List(u *User, c *Category, p *Pagination, pc
//the PublishedCritera specifies which articles should be considered
func (rdb SQLiteArticleDatasource) Count(u *User, c *Category, pc PublishedCriteria) (int, error) {
var total int
var args []interface{}
var stmt bytes.Buffer
stmt.WriteString("SELECT count(a.id) FROM article a ")
if c != nil {
@ -211,19 +210,21 @@ func selectArticleStmt(db *sql.DB, articleID int, slug string, u *User, pc Publi
stmt.WriteString("AND a.id=? ")
args = append(args, articleID)
}
if u != nil {
if !u.IsAdmin {
stmt.WriteString("AND a.user_id=? ")
args = append(args, u.ID)
}
}
stmt.WriteString("LIMIT 1")
return db.QueryRow(stmt.String(), args...)
}
func selectArticlesStmt(db *sql.DB, u *User, c *Category, p *Pagination, pc PublishedCriteria) (*sql.Rows, error) {
var stmt bytes.Buffer
var args []interface{}
stmt.WriteString("SELECT a.id, a.headline, a.teaser, a.content, a.published, a.published_on, a.slug, a.last_modified, ")


+ 3
- 3
models/category_sqlite.go View File

@ -33,9 +33,8 @@ func (rdb SQLiteCategoryDatasource) Create(c *Category) (int, error) {
}
func (rdb SQLiteCategoryDatasource) List(fc FilterCriteria) ([]Category, error) {
var stmt bytes.Buffer
var args []interface{}
var stmt bytes.Buffer
stmt.WriteString("SELECT DISTINCT c.id, c.name, c.slug, c.last_modified, ")
stmt.WriteString("u.id, u.display_name, u.username, u.email, u.is_admin ")
@ -63,7 +62,7 @@ func (rdb SQLiteCategoryDatasource) List(fc FilterCriteria) ([]Category, error)
defer rows.Close()
cs := []Category{}
var cs []Category
for rows.Next() {
var c Category
@ -139,6 +138,7 @@ func (rdb SQLiteCategoryDatasource) GetBySlug(slug string, fc FilterCriteria) (*
stmt.WriteString("FROM category as c ")
stmt.WriteString("INNER JOIN user as u ")
stmt.WriteString("ON u.id = c.user_id ")
if fc == CategoriesWithPublishedArticles {
stmt.WriteString("INNER JOIN article as a ")
stmt.WriteString("ON c.id = a.category_id ")


+ 1
- 4
models/file_sqlite.go View File

@ -15,7 +15,6 @@ type SQLiteFileDatasource struct {
//only file specific to this user is returned
func (rdb SQLiteFileDatasource) GetByUniqueName(uniqueName string, u *User) (*File, error) {
var stmt bytes.Buffer
var args []interface{}
stmt.WriteString("SELECT f.id, f.filename, f.unique_name, f.content_type, f.inline, f.size, f.last_modified, f.user_id, ")
@ -51,7 +50,6 @@ func (rdb SQLiteFileDatasource) GetByUniqueName(uniqueName string, u *User) (*Fi
//only file specific to this user is returned
func (rdb SQLiteFileDatasource) Get(fileID int, u *User) (*File, error) {
var stmt bytes.Buffer
var args []interface{}
stmt.WriteString("SELECT f.id, f.filename, f.unique_name, f.content_type, f.inline, f.size, f.last_modified, f.user_id, ")
@ -144,8 +142,7 @@ func (rdb SQLiteFileDatasource) List(u *User, p *Pagination) ([]File, error) {
defer rows.Close()
files := []File{}
var files []File
var f File
var us User


+ 2
- 2
models/html.go View File

@ -14,7 +14,7 @@ import (
)
// Defines the extensions that are used
var exts = bf.NoIntraEmphasis | bf.Tables | bf.FencedCode | bf.Autolink |
var ext = bf.NoIntraEmphasis | bf.Tables | bf.FencedCode | bf.Autolink |
bf.Strikethrough | bf.SpaceHeadings | bf.BackslashLineBreak |
bf.DefinitionLists | bf.Footnotes | bf.HardLineBreak
@ -33,7 +33,7 @@ func init() {
//MarkdownToHTML sanitizes and parses markdown to HTML
func MarkdownToHTML(md []byte) []byte {
md = bytes.Replace(md, []byte("\r\n"), []byte("\n"), -1)
unsafe := bf.Run((md), bf.WithExtensions(exts))
unsafe := bf.Run((md), bf.WithExtensions(ext))
return sanitize(unsafe)
}


+ 1
- 0
models/site.go View File

@ -174,6 +174,7 @@ func (ss SiteService) Update(s *Site) error {
}
changeLink := false
if oldSite.Link != s.Link {
changeLink = true
s.Link = s.safeLink()


+ 3
- 7
models/site_sqlite.go View File

@ -16,7 +16,6 @@ type SQLiteSiteDatasource struct {
//List returns a array of sites
func (rdb SQLiteSiteDatasource) List(pc PublishedCriteria, p *Pagination) ([]Site, error) {
var stmt bytes.Buffer
var args []interface{}
stmt.WriteString("SELECT s.id, s.title, s.link, s.section, s.content, s.published, s.published_on, s.last_modified, s.order_no, u.id, u.display_name, u.email, u.username ")
@ -40,14 +39,14 @@ func (rdb SQLiteSiteDatasource) List(pc PublishedCriteria, p *Pagination) ([]Sit
}
rows, err := rdb.SQLConn.Query(stmt.String(), args...)
if err != nil {
return nil, err
}
defer rows.Close()
sites := []Site{}
var sites []Site
var s Site
var u User
@ -129,6 +128,7 @@ func (rdb SQLiteSiteDatasource) GetByLink(link string, pc PublishedCriteria) (*S
//Publish publishes or unpublishes a site
func (rdb SQLiteSiteDatasource) Publish(s *Site) error {
publishOn := NullTime{Valid: false}
if !s.Published {
publishOn = NullTime{Time: time.Now(), Valid: true}
}
@ -172,10 +172,6 @@ func (rdb SQLiteSiteDatasource) Order(id int, d Direction) error {
}
}()
if err != nil {
return err
}
if d == Up {
if _, err = tx.Exec("UPDATE site "+
"SET order_no=(SELECT order_no AS order_no FROM site WHERE id=?) "+


+ 1
- 1
models/sql.go View File

@ -29,7 +29,7 @@ const (
All
)
//NullTime reprensents a time which may not valid if time is null
//NullTime represents a time which may not valid if time is null
type NullTime struct {
Time time.Time
Valid bool


+ 5
- 3
models/token.go View File

@ -70,9 +70,11 @@ type TokenService struct {
func (ts TokenService) Create(t *Token) error {
t.Hash = crypt.RandomHash(32)
_, err := ts.Datasource.Create(t)
if _, err := ts.Datasource.Create(t); err != nil {
return err
}
return err
return nil
}
//Get token for a defined token type expires after a defined time
@ -106,7 +108,7 @@ func (ts TokenService) RateLimit(userID int, tt TokenType) error {
now := time.Now()
rate := []Token{}
var rate []Token
for _, t := range tokens {
if now.Sub(t.RequestedAt) < time.Minute*15 {
rate = append(rate, t)


+ 13
- 9
models/user.go View File

@ -133,8 +133,9 @@ func (u *User) validate(us UserService, minPasswordLength int, v Validations) er
func (us UserService) duplicateMail(mail string) error {
user, err := us.Datasource.GetByMail(mail)
if err != nil {
if err != sql.ErrNoRows {
if !errors.Is(err, sql.ErrNoRows) {
return err
}
}
@ -149,7 +150,7 @@ func (us UserService) duplicateMail(mail string) error {
func (us UserService) duplicateUsername(username string) error {
user, err := us.Datasource.GetByUsername(username)
if err != nil {
if err != sql.ErrNoRows {
if !errors.Is(err, sql.ErrNoRows) {
return err
}
}
@ -175,8 +176,9 @@ func (us UserService) List(p *Pagination) ([]User, error) {
//GetByID gets the user based on the given id; will not contain the user password
func (us UserService) GetByID(userID int) (*User, error) {
u, err := us.Datasource.Get(userID)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, httperror.NotFound("user", fmt.Errorf("the user with id %d was not found", userID))
}
return nil, err
@ -189,7 +191,7 @@ func (us UserService) GetByID(userID int) (*User, error) {
func (us UserService) GetByUsername(username string) (*User, error) {
u, err := us.Datasource.GetByUsername(username)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, httperror.NotFound("user", err)
}
return nil, err
@ -203,7 +205,7 @@ func (us UserService) GetByMail(mail string) (*User, error) {
u, err := us.Datasource.GetByMail(mail)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, httperror.NotFound("user", err)
}
@ -270,7 +272,6 @@ func (us UserService) Update(u *User, changePassword bool) error {
}
if us.UserInterceptor != nil {
if err := us.UserInterceptor.PreUpdate(oldUser, u); err != nil {
return httperror.InternalServerError(fmt.Errorf("error while executing user interceptor 'PreUpdate' error %v", err))
}
@ -321,7 +322,9 @@ func (us UserService) Update(u *User, changePassword bool) error {
u.Salt = salt
}
err = us.Datasource.Update(u, changePassword)
if err = us.Datasource.Update(u, changePassword); err != nil {
return err
}
u.Password = nil
@ -330,9 +333,10 @@ func (us UserService) Update(u *User, changePassword bool) error {
logger.Log.Errorf("error while executing PostUpdate user interceptor method %v", err)
}
}
u.PlainPassword = nil
return err
return nil
}
// Authenticate authenticates the user by the given login method (email or username)
@ -353,7 +357,7 @@ func (us UserService) Authenticate(u *User, loginMethod settings.LoginMethod) (*
}
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
//Do some extra work
bcrypt.CompareHashAndPassword([]byte("$2a$12$bQlRnXTNZMp6kCyoAlnf3uZW5vtmSj9CHP7pYplRUVK2n0C5xBHBa"), password)
return nil, httperror.New(http.StatusUnauthorized, "Your username or password is invalid.", err)


+ 1
- 1
models/user_invite.go View File

@ -7,7 +7,7 @@ import (
"git.hoogi.eu/snafu/go-blog/mail"
)
//User represents a user
//UserInvite represents a new invited user
type UserInvite struct {
ID int
Hash string


+ 5
- 10
models/user_invite_sqlite.go View File

@ -14,6 +14,9 @@ type SQLiteUserInviteDatasource struct {
func (rdb SQLiteUserInviteDatasource) List() ([]UserInvite, error) {
var stmt bytes.Buffer
var args []interface{}
var invites []UserInvite
var ui UserInvite
var u User
stmt.WriteString("SELECT ui.id, ui.username, ui.email, ui.display_name, ui.created_at, ui.is_admin, ")
stmt.WriteString("u.id, u.username, u.email, u.display_name ")
@ -30,11 +33,6 @@ func (rdb SQLiteUserInviteDatasource) List() ([]UserInvite, error) {
defer rows.Close()
invites := []UserInvite{}
var ui UserInvite
var u User
for rows.Next() {
if err = rows.Scan(&ui.ID, &ui.Username, &ui.Email, &ui.DisplayName, &ui.CreatedAt, &ui.IsAdmin, &u.ID, &u.Username, &u.Email, &u.DisplayName); err != nil {
return nil, err
@ -111,6 +109,7 @@ func (rdb SQLiteUserInviteDatasource) Create(ui *UserInvite) (int, error) {
if err != nil {
return -1, err
}
return int(i), nil
}
@ -127,11 +126,7 @@ func (rdb SQLiteUserInviteDatasource) Count() (int, error) {
//Removes an user invitation
func (rdb SQLiteUserInviteDatasource) Remove(inviteID int) error {
var stmt bytes.Buffer
stmt.WriteString("DELETE FROM user_invite WHERE id=?")
if _, err := rdb.SQLConn.Exec(stmt.String(), inviteID); err != nil {
if _, err := rdb.SQLConn.Exec("DELETE FROM user_invite WHERE id=?", inviteID); err != nil {
return err
}


+ 4
- 12
models/user_sqlite.go View File

@ -15,6 +15,8 @@ type SQLiteUserDatasource struct {
func (rdb SQLiteUserDatasource) List(p *Pagination) ([]User, error) {
var stmt bytes.Buffer
var args []interface{}
var users []User
var u User
stmt.WriteString("SELECT id, username, email, display_name, last_modified, active, is_admin FROM user ORDER BY username ASC ")
@ -31,10 +33,6 @@ func (rdb SQLiteUserDatasource) List(p *Pagination) ([]User, error) {
defer rows.Close()
users := []User{}
var u User
for rows.Next() {
if err = rows.Scan(&u.ID, &u.Username, &u.Email, &u.DisplayName, &u.LastModified, &u.Active, &u.IsAdmin); err != nil {
return nil, err
@ -106,7 +104,6 @@ func (rdb SQLiteUserDatasource) Create(u *User) (int, error) {
//Update updates an user
func (rdb SQLiteUserDatasource) Update(u *User, changePassword bool) error {
var stmt bytes.Buffer
var args []interface{}
stmt.WriteString("UPDATE user SET display_name=?, username=?, email=?, last_modified=?, active=?, is_admin=? ")
@ -128,10 +125,9 @@ func (rdb SQLiteUserDatasource) Update(u *User, changePassword bool) error {
return nil
}
//Count retuns the amount of users matches the AdminCriteria
//Count returns the amount of users matches the AdminCriteria
func (rdb SQLiteUserDatasource) Count(ac AdminCriteria) (int, error) {
var stmt bytes.Buffer
stmt.WriteString("SELECT count(id) FROM user ")
if ac == OnlyAdmins {
@ -151,11 +147,7 @@ func (rdb SQLiteUserDatasource) Count(ac AdminCriteria) (int, error) {
//Removes an user
func (rdb SQLiteUserDatasource) Remove(userID int) error {
var stmt bytes.Buffer
stmt.WriteString("DELETE FROM user WHERE id=?")
if _, err := rdb.SQLConn.Exec(stmt.String(), userID); err != nil {
if _, err := rdb.SQLConn.Exec("DELETE FROM user WHERE id=?", userID); err != nil {
return err
}


Loading…
Cancel
Save