Merge branch 'wip' into 'main'

WIP Branch completed: Overhaul of site logic, removed comments, repositories

See merge request rawleyIfowler/rawleydotxyz!1
This commit is contained in:
2022-03-09 04:20:27 +00:00
40 changed files with 730 additions and 564 deletions

2
.gitignore vendored
View File

@@ -5,3 +5,5 @@ dsn
*.pem *.pem
api_key.pem api_key.pem
admin_hash.pem admin_hash.pem
create_admin_form.html
error.log

View File

@@ -1,101 +1,179 @@
package controllers package controllers
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import ( import (
"crypto/sha256"
"fmt"
"net/http" "net/http"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gitlab.com/rawleyifowler/site-rework/models" "gitlab.com/rawleyifowler/site-rework/models"
"gitlab.com/rawleyifowler/site-rework/repos"
"gitlab.com/rawleyifowler/site-rework/utils" "gitlab.com/rawleyifowler/site-rework/utils"
) )
var ( var (
key string = utils.LoadApiKey("api_key.pem") api_key string = utils.LoadApiKey("api_key.pem")
admin_hash [32]byte = utils.LoadAdminHash("admin_hash.pem")
att map[string]uint32 = make(map[string]uint32)
) )
// Ensure is logged in type AdminController struct {
func AdminOnly() gin.HandlerFunc { Repository *repos.AdminRepo
return func(c *gin.Context) { BlogRepository *repos.BlogRepo
var status uint = http.StatusOK ActiveLogins map[string]int64
k, err := c.Cookie("admin_key") LoginAttemptsByIp map[string]uint
if err != nil {
status = http.StatusForbidden
}
fmt.Println(k)
if k == key && status == http.StatusOK {
c.Next()
} else {
c.HTML(int(status), "forbidden.tmpl", models.Page{Title: " | forbidden"})
c.Abort()
return
}
} }
func NewAdminController(r *repos.AdminRepo) *AdminController {
var a AdminController
a.Repository = r
a.ActiveLogins = map[string]int64{}
a.LoginAttemptsByIp = map[string]uint{}
go utils.TimeClearMap(a.ActiveLogins, 850)
return &a
} }
func RegisterAdminGroup(r *gin.RouterGroup) { func RegisterAdminGroup(r *gin.RouterGroup) {
a := NewAdminController(repos.NewAdminRepo("dsn"))
r.Use(a.UserBannedMiddleware)
r.GET("/", utils.ServePage("login.tmpl")) r.GET("/", utils.ServePage("login.tmpl"))
r.POST("/login", HandleLogin) r.POST("/login", a.AdminLogin)
r.GET("/post", AdminOnly(), utils.ServePage("create_post.tmpl")) r.GET("/post", a.AuthMiddleware, utils.ServePage("create_post.tmpl"))
r.POST("/post", AdminOnly(), CreatePost) r.POST("/post", a.AuthMiddleware, a.CRUDPost)
r.POST("/user", a.CreateAdmin)
} }
func HandleLogin(c *gin.Context) { func (a *AdminController) AuthMiddleware(c *gin.Context) {
if att[c.ClientIP()] > 5 { cookie, err := c.Request.Cookie("token")
c.HTML(http.StatusForbidden, "forbidden.tmpl", models.Page{Title: " | forbidden"}) if err != nil {
c.HTML(http.StatusForbidden, "forbidden.tmpl", &gin.H{})
c.Abort()
return return
} }
if a.ActiveLogins[cookie.Value] == 0 {
c.HTML(http.StatusForbidden, "session_revoked.tmpl", &gin.H{})
c.Abort()
return
}
c.Next()
}
func (a *AdminController) UserBannedMiddleware(c *gin.Context) {
if a.IpIsBanned(c.ClientIP()) {
c.HTML(http.StatusForbidden, "forbidden.tmpl", &gin.H{})
c.Abort()
return
}
c.Next()
}
func (a *AdminController) IpIsBanned(ip string) bool {
return a.LoginAttemptsByIp[ip] >= 3
}
func (a *AdminController) AdminLogin(c *gin.Context) {
err := c.Request.ParseForm() err := c.Request.ParseForm()
if err != nil { if err != nil {
c.HTML(http.StatusForbidden, "forbidden.tmpl", models.Page{Title: " | forbidden"}) c.HTML(http.StatusForbidden, "forbidden.tmpl", &gin.H{})
a.LoginAttemptsByIp[c.ClientIP()]++
return return
} }
f := c.Request.Form f := c.Request.Form
for _, v := range []string{"username", "password"} { if !f.Has("username") ||
if !f.Has(v) { !f.Has("password") {
c.AbortWithStatus(http.StatusNotAcceptable) c.HTML(http.StatusNotAcceptable, "admin_success_redirect.tmpl", false)
a.LoginAttemptsByIp[c.ClientIP()]++
return return
} }
ad, err := a.Repository.GetAdminByCredentials(f.Get("username"), f.Get("password"))
if err != nil ||
ad == nil {
c.HTML(http.StatusNotAcceptable, "admin_success_redirect.tmpl", false)
a.LoginAttemptsByIp[c.ClientIP()]++
return
} }
str := f.Get("username") + f.Get("password") a.ActiveLogins[ad.Token] = time.Now().UnixMilli() + (3600 * 1000)
s := sha256.Sum256([]byte(str)) c.SetCookie("token", ad.Token, 3600*1000, "/", "rawley.xyz", true, true)
var success bool c.HTML(http.StatusAccepted, "admin_success_redirect.tmpl", true)
if s == admin_hash {
c.SetCookie("admin_key", key, 3600, "/", "rawley.xyz", false, true)
success = true
} else {
att[c.ClientIP()]++
success = false
}
c.HTML(http.StatusOK, "admin_success_redirect.tmpl", struct {
Success bool
Title string
}{Success: success, Title: "login"})
} }
func CreatePost(c *gin.Context) { func (a *AdminController) CRUDPost(c *gin.Context) {
err := c.Request.ParseForm() err := c.Request.ParseForm()
if err != nil { if err != nil {
c.AbortWithStatus(http.StatusBadRequest) c.HTML(http.StatusNotAcceptable, "post_success.tmpl", false)
return return
} }
f := c.Request.Form f := c.Request.Form
for _, v := range []string{"title", "content", "url"} { if f.Get("url") == "" ||
if !f.Has(v) { f.Get("op") == "" {
c.AbortWithStatus(http.StatusNotAcceptable) c.HTML(http.StatusNotAcceptable, "post_success.tmpl", false)
return return
} }
} tempBlogRepo := repos.NewBlogRepo("dsn")
b := AddBlogPost(&models.BlogPost{ tempPost := &models.BlogPost{
Title: f.Get("title"),
Content: f.Get("content"),
Url: f.Get("url"), Url: f.Get("url"),
}) Content: f.Get("content"),
c.HTML(http.StatusOK, "post_success.tmpl", struct { Title: f.Get("title"),
Url string }
Success bool switch f.Get("op") {
Title string case "create":
}{Url: f.Get("url"), Success: b, Title: " | post attempt"}) err = tempBlogRepo.CreateBlogPost(tempPost)
break
case "update":
err = tempBlogRepo.UpdateExistingPost(tempPost)
break
case "delete":
err = tempBlogRepo.DeleteExistingPost(tempPost)
break
default:
c.HTML(http.StatusNotAcceptable, "post_success.tmpl", false)
return
}
if err != nil {
c.HTML(http.StatusNotAcceptable, "post_success.tmpl", false)
return
}
c.HTML(http.StatusAccepted, "post_success.tmpl", true)
}
func (a *AdminController) CreateAdmin(c *gin.Context) {
err := c.Request.ParseForm()
if err != nil {
c.HTML(http.StatusNotAcceptable, "forbidden.tmpl", &gin.H{})
return
}
var at models.Administrator
f := c.Request.Form
if !f.Has("password") ||
!f.Has("username") ||
!f.Has("api_key") {
c.HTML(http.StatusBadRequest, "forbidden.tmpl", &gin.H{})
return
}
at.Username = f.Get("username")
at.Password = f.Get("password")
if f.Get("api_key") != api_key {
c.HTML(http.StatusForbidden, "forbidden.tmpl", &gin.H{})
return
}
err = a.Repository.CreateAdmin(&at)
if err != nil {
c.HTML(http.StatusForbidden, "forbidden.tmpl", &gin.H{})
return
}
c.HTML(http.StatusAccepted, "post_success.tmpl", true)
} }

18
controllers/admin_test.go Normal file
View File

@@ -0,0 +1,18 @@
package controllers
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/

View File

@@ -17,158 +17,47 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fow
import ( import (
"net/http" "net/http"
"strconv"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gitlab.com/rawleyifowler/site-rework/models" "gitlab.com/rawleyifowler/site-rework/repos"
"gitlab.com/rawleyifowler/site-rework/utils"
"gorm.io/driver/mysql"
"gorm.io/gorm"
) )
type CommentDto struct { type CommentDto struct {
Url string Url string
} }
var ( type BlogController struct {
db *gorm.DB Repository *repos.BlogRepo
recentPosters map[string]uint }
captchaVals [2]int
) func NewBlogController(r *repos.BlogRepo) *BlogController {
c := new(BlogController)
c.Repository = r
return c
}
func RegisterBlogGroup(r *gin.RouterGroup) { func RegisterBlogGroup(r *gin.RouterGroup) {
// Initialize recent posters cache c := NewBlogController(repos.NewBlogRepo("dsn"))
recentPosters = make(map[string]uint) r.GET("/", c.IndexBlogPage)
// Load dsn and initialize database r.GET("/post/:url", c.IndividualBlogPage)
dsn := utils.LoadDSN("dsn") }
var err error
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) func (bc *BlogController) IndexBlogPage(c *gin.Context) {
posts, err := bc.Repository.GetAllBlogPosts()
if err != nil { if err != nil {
panic("Database connection failed...") c.HTML(http.StatusInternalServerError, "internal_server_error.tmpl", &gin.H{})
}
utils.PerformMigrations(db)
r.GET("/", RenderBlogPage)
r.GET("/post/:url", RenderIndividualBlogPost)
r.POST("/post")
r.POST("/post/comment", CreateComment)
// Clear the commenters cache every 15 minutes
go utils.TimedClearMap(&recentPosters, 320000*5)
go utils.UpdateCaptcha(&captchaVals)
}
func RenderBlogPage(c *gin.Context) {
posts := GetAllBlogPosts()
if posts == nil {
c.HTML(http.StatusInternalServerError, "internal_server_error.tmpl", models.Page{Title: " | 500"})
} else {
c.HTML(http.StatusOK, "blog.tmpl", struct {
Posts []models.BlogPost
Title string
}{Posts: *posts, Title: " | blog"})
}
}
func RenderIndividualBlogPost(c *gin.Context) {
bp := GetBlogPostById(c.Param("url"))
if bp == nil {
c.HTML(http.StatusNotFound, "not_found.tmpl", models.Page{Title: "404"})
return
} else {
// Blog posts handle the title themselves
c.HTML(http.StatusOK, "blog_post.tmpl", struct {
Post *models.BlogPost
Captcha [2]int
}{Post: bp, Captcha: captchaVals})
}
}
func CreateComment(c *gin.Context) {
if c.Request.ParseForm() != nil {
c.AbortWithStatus(http.StatusNotAcceptable)
return return
} }
a := []string{c.Request.Form.Get("author"), c.HTML(http.StatusOK, "blog.tmpl", *posts)
c.Request.Form.Get("content"),
c.Request.Form.Get("url"),
c.Request.Form.Get("captcha")}
// If the length of the comment is great enough, and the comment already exists we can safely assume it is spam.
if len(a[1]) > 20 && len(*GetCommentsByContent(a[1], a[2])) > 0 {
c.HTML(http.StatusNotAcceptable, "comment_post_failed.tmpl", CommentDto{Url: a[2]})
return
}
i, err := strconv.ParseInt(a[3], 10, 32)
if err != nil || int(i) != (captchaVals[0]+captchaVals[1]) {
c.HTML(http.StatusNotAcceptable, "comment_post_failed.tmpl", CommentDto{Url: a[2]})
return
}
if GetNumberOfRecentPosts(c) >= 2 {
c.HTML(http.StatusNotAcceptable, "comment_post_spam.tmpl", CommentDto{Url: a[2]})
return
}
for _, v := range a {
if len(v) == 0 {
c.HTML(http.StatusNotAcceptable, "comment_post_failed.tmpl", CommentDto{Url: a[2]})
return
}
}
comment := models.Comment{
Author: a[0],
Content: a[1],
AssociatedPost: a[2],
}
db.Create(&comment)
// Something was wrong with c.ClientIP() with trusted?? Weird.
recentPosters[c.ClientIP()]++
// Pass the associated post to the template to add to the href
c.HTML(http.StatusOK, "comment_post.tmpl", CommentDto{Url: comment.AssociatedPost})
} }
func GetNumberOfRecentPosts(c *gin.Context) uint { func (bc *BlogController) IndividualBlogPage(c *gin.Context) {
return recentPosters[c.ClientIP()] post, err := bc.Repository.GetBlogByUrl(c.Param("url"))
}
func AddBlogPost(bp *models.BlogPost) bool {
err := db.Create(bp).Error
return err == nil
}
func DeleteBlogPostById(id string) bool {
err := db.Model(&models.BlogPost{}).Delete(&models.BlogPost{Url: id}).Error
return err == nil
}
func GetAllBlogPosts() *[]models.BlogPost {
var posts []models.BlogPost
// Select title, date, and url fields from the blog post records an store them in posts.
// This is so we don't grab the entire blog post when we render them on the overview page. Saves a couple ms.
err := db.Model(&models.BlogPost{}).Select("title, date, url").Order("date DESC").Scan(&posts).Error
if err != nil { if err != nil {
return nil c.HTML(http.StatusNotFound, "not_found.tmpl", &gin.H{})
return
} }
return &posts // TODO: Re implement captcha here. It is already included on the blog post model, though not in the database.
} // The idea is to generate a captcha for each post, and index them by title. The async service should then update each captcha every hour.
c.HTML(http.StatusOK, "blog_post.tmpl", post)
func GetBlogPostById(id string) *models.BlogPost {
var post models.BlogPost = models.BlogPost{}
err := db.Model(&post).Where(&models.BlogPost{Url: id}).Find(&post).Error
if err != nil || post.Equals(&models.BlogPost{}) {
return nil
}
// TODO: Figure out gorm joins!
// gorm joins are not working at all, just going to do another query to make it work for now.
err = db.Model(&models.Comment{}).Where(&models.Comment{AssociatedPost: id}).Find(&post.Comments).Error
if err != nil {
return nil
}
return &post
}
func GetCommentsByContent(content string, url string) *[]models.Comment {
// This is used to make sure people don't paste the same thing over and over.
var comments []models.Comment
err := db.Model(&comments).Where("content like ? and associated_post like ?", "%"+content[1:]+"%", url).Scan(&comments).Error
if err != nil {
return &[]models.Comment{}
}
return &comments
} }

View File

@@ -1 +1,18 @@
package controllers package controllers
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/

View File

@@ -1 +0,0 @@
package controllers

1
go.mod
View File

@@ -4,6 +4,7 @@ go 1.15
require ( require (
github.com/gin-gonic/gin v1.7.7 github.com/gin-gonic/gin v1.7.7
github.com/google/uuid v1.3.0 // indirect
gorm.io/driver/mysql v1.2.3 gorm.io/driver/mysql v1.2.3
gorm.io/gorm v1.22.5 gorm.io/gorm v1.22.5
) )

2
go.sum
View File

@@ -16,6 +16,8 @@ github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LB
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.3/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jinzhu/now v1.1.3/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=

11
models/administrator.go Normal file
View File

@@ -0,0 +1,11 @@
package models
import "gorm.io/gorm"
type Administrator struct {
gorm.Model
Id uint `json:"id" gorm:"primaryKey AUTO_INCREMENT"`
Token string `json:"token" gorm:"unique"`
Username string `gorm:"unique"`
Password string
}

View File

@@ -26,7 +26,7 @@ type BlogPost struct {
Title string `json:"title" gorm:"unique"` Title string `json:"title" gorm:"unique"`
Date string `json:"date" gorm:"default:NOW()"` Date string `json:"date" gorm:"default:NOW()"`
Content string `json:"content"` Content string `json:"content"`
Comments []Comment `gorm:"foreignKey:AssociatedPost;references:Url;type:varchar(191)"` Captcha [2]int `gorm:"-"`
} }
func (b BlogPost) Equals(m *BlogPost) bool { func (b BlogPost) Equals(m *BlogPost) bool {

93
repos/admin_repo.go Normal file
View File

@@ -0,0 +1,93 @@
package repos
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import (
"crypto/sha256"
"errors"
"fmt"
"github.com/google/uuid"
"gitlab.com/rawleyifowler/site-rework/models"
"gitlab.com/rawleyifowler/site-rework/utils"
"gorm.io/gorm"
)
type AdminRepo struct {
DB *gorm.DB
}
func NewAdminRepo(dsnPath string) *AdminRepo {
c := AdminRepo{}
var err error
c.DB, err = utils.CreateDatabase(utils.LoadDSN(dsnPath))
if err != nil {
panic(err)
}
c.DB.AutoMigrate(&models.Administrator{})
return &c
}
func (ar *AdminRepo) CreateAdmin(a *models.Administrator) error {
if a.Password == "" ||
a.Username == "" {
return errors.New("Administrators must have a valid username and password")
}
if len(a.Password) < 8 {
return errors.New("Passwords must have a length of atleast 8")
}
a.Token = uuid.New().String()
a.Password = fmt.Sprintf("%x", string(sha256.New().Sum([]byte(a.Password))))
err := ar.DB.Table("administrators").Create(a).Error
if err != nil {
return err
}
return nil
}
func (ar *AdminRepo) GetAdminByToken(k string) (*models.Administrator, error) {
if k == "" {
return nil, errors.New("Session key cannot be blank")
}
if len(k) != 36 {
return nil, errors.New("Valid sessions keys are always 36 byte utf-8 strings")
}
var a *models.Administrator
err := ar.DB.Table("administrators").Where(&models.Administrator{Token: k}).Scan(a).Error
if err != nil {
return nil, err
}
return a, nil
}
func (ar *AdminRepo) GetAdminByCredentials(uname, pword string) (*models.Administrator, error) {
if uname == "" ||
pword == "" {
return nil, errors.New("Username or password mustn't be empty")
}
if len(pword) < 8 {
return nil, errors.New("Password length must be no less than 8")
}
pword = fmt.Sprintf("%x", string(sha256.New().Sum([]byte(pword))))
var a models.Administrator
err := ar.DB.Table("administrators").Where(&models.Administrator{Username: uname, Password: pword}).First(&a).Error
if err != nil {
return nil, err
}
return &a, nil
}

67
repos/admin_repo_test.go Normal file
View File

@@ -0,0 +1,67 @@
package repos
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import (
"testing"
"gitlab.com/rawleyifowler/site-rework/models"
)
var test_admin_repo = NewAdminRepo("dsn")
func TestCreateAdmin(t *testing.T) {
err := test_admin_repo.CreateAdmin(&models.Administrator{})
if err == nil {
t.Fatalf("Expected: You cannot create an admin with empty credentials")
}
err = test_admin_repo.CreateAdmin(&models.Administrator{Username: "", Password: "12345678"})
if err == nil {
t.Fatalf("Expected: You cannot create an admin with empty credentials")
}
err = test_admin_repo.CreateAdmin(&models.Administrator{Username: "12345678", Password: ""})
if err == nil {
t.Fatalf("Expected: You cannot create an admin with empty credentials")
}
err = test_admin_repo.CreateAdmin(&models.Administrator{Username: "valid_username", Password: "invalid"})
if err == nil {
t.Fatalf("Expected: You cannot create an admin with a password less than 8 characters")
}
}
func TestGetAdminByToken(t *testing.T) {
_, err := test_admin_repo.GetAdminByToken("")
if err == nil {
t.Fatalf("Expected: Error should be thrown when an empty session key is provided")
}
}
func TestGetAdminByCredentials(t *testing.T) {
_, err := test_admin_repo.GetAdminByCredentials("", "")
if err == nil {
t.Fatalf("Expected: Error should be thrown if empty credentials are given")
}
_, err = test_admin_repo.GetAdminByCredentials("1234", "")
if err == nil {
t.Fatalf("Expected: Error should be thrown if empty credentials are given")
}
_, err = test_admin_repo.GetAdminByCredentials("", "123456789")
if err == nil {
t.Fatalf("Expected: Error should be thrown if empty credentials are given")
}
}

View File

@@ -1 +1,107 @@
package repos package repos
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import (
"errors"
"gitlab.com/rawleyifowler/site-rework/models"
"gitlab.com/rawleyifowler/site-rework/utils"
"gorm.io/gorm"
)
type BlogRepo struct {
DB *gorm.DB
initialized bool
}
func NewBlogRepo(dsnPath string) *BlogRepo {
b := BlogRepo{}
var err error
b.DB, err = utils.CreateDatabase(utils.LoadDSN(dsnPath))
if err != nil {
panic(err)
}
b.DB.AutoMigrate(&models.BlogPost{})
return &b
}
func (b *BlogRepo) CreateBlogPost(p *models.BlogPost) error {
if p == nil {
return errors.New("Blog post must not be nil")
}
if p.Title == "" ||
p.Content == "" ||
p.Url == "" {
return errors.New("Blog posts must be fully formed")
}
err := b.DB.Table("blog_posts").Create(p).Error
if err != nil {
return err
}
return nil
}
func (b *BlogRepo) GetBlogByUrl(url string) (*models.BlogPost, error) {
if url == "" {
return nil, errors.New("Cannot query by empty value")
}
var post models.BlogPost
err := b.DB.Table("blog_posts").Where(&models.BlogPost{Url: url}).Scan(&post).Error
if err != nil {
return nil, err
}
return &post, nil
}
func (b *BlogRepo) GetAllBlogPosts() (*[]models.BlogPost, error) {
posts := new([]models.BlogPost)
err := b.DB.Table("blog_posts").Scan(posts).Error
if err != nil {
return nil, errors.New("Could not load all posts from database")
}
return posts, nil
}
func (b *BlogRepo) UpdateExistingPost(p *models.BlogPost) error {
if p == nil {
return errors.New("Cannot update with nil value for post")
}
if p.Url == "" {
return errors.New("Url must exist to update a blog post record")
}
err := b.DB.Table("blog_posts").Save(p).Error
if err != nil {
return err
}
return nil
}
func (b *BlogRepo) DeleteExistingPost(p *models.BlogPost) error {
if p == nil {
return errors.New("Cannot delete with nil value for post")
}
if p.Url == "" {
return errors.New("Url must exist to delete a blog post record")
}
err := b.DB.Table("blog_posts").Delete(p).Error
if err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,50 @@
package repos
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import (
"testing"
"gitlab.com/rawleyifowler/site-rework/models"
)
var test_blog_repo = NewBlogRepo("dsn")
func TestGetBlogByUrl(t *testing.T) {
_, err := test_blog_repo.GetBlogByUrl("")
if err == nil {
t.Fatalf("Expected: Empty values of url for get blog by url should return an error")
}
}
func TestCreateBlogPost(t *testing.T) {
err := test_blog_repo.CreateBlogPost(&models.BlogPost{})
if err == nil {
t.Fatalf("Expected: Blog posts must be fully formed")
}
err = test_blog_repo.CreateBlogPost(&models.BlogPost{Title: "abc"})
if err == nil {
t.Fatalf("Expected: Blog posts must be fully formed, title, content, url")
}
err = test_blog_repo.CreateBlogPost(nil)
if err == nil {
t.Fatalf("Expected: Cannot create blog posts from nil values")
}
}

View File

@@ -1,80 +0,0 @@
package repos
import (
"errors"
"gitlab.com/rawleyifowler/site-rework/models"
"gitlab.com/rawleyifowler/site-rework/utils"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type CommentRepo struct {
DB *gorm.DB
Initialized bool
}
func NewCommentRepo(dsnPath string) (*CommentRepo, error) {
c := CommentRepo{}
err := c.Initialize(dsnPath)
if err != nil {
return &c, err
}
return &c, nil
}
func (c *CommentRepo) Initialize(path string) error {
dsn := utils.LoadDSN(path)
var err error
c.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return err
}
c.Initialized = true
return nil
}
func (c *CommentRepo) GetCommentById(id uint) (*models.Comment, error) {
if id == 0 {
return nil, nil
}
var comm models.Comment
c.DB.Where(&models.Comment{Id: id}).First(&comm)
return &comm, nil
}
func (c *CommentRepo) CreateComment(comm *models.Comment) error {
if comm == nil {
return errors.New("nil comment")
}
err := c.DB.Create(comm).Error
if err != nil {
return err
}
// nil return means no errors, yay!
return nil
}
func (c *CommentRepo) GetCommentsByAssociatedPost(title string) (*[]models.Comment, error) {
if len(title) < 1 {
return nil, errors.New("empty associated post title")
}
var comms []models.Comment
err := c.DB.Where(&models.Comment{AssociatedPost: title}).Scan(&comms).Error
if err != nil {
return nil, err
}
return &comms, nil
}
func (c *CommentRepo) GetCommentsByAuthor(auth string) (*[]models.Comment, error) {
if len(auth) < 1 {
return nil, errors.New("empty author name")
}
var comms []models.Comment
err := c.DB.Where(&models.Comment{Author: auth}).Scan(&comms).Error
if err != nil {
return nil, err
}
return &comms, nil
}

View File

@@ -1,76 +0,0 @@
package repos
import (
"testing"
"gitlab.com/rawleyifowler/site-rework/models"
)
var cr *CommentRepo
func TestInitialize(t *testing.T) {
var err error
cr, err = NewCommentRepo("dsn")
if err != nil {
}
}
func TestGetCommentById(t *testing.T) {
const ID uint = 1
const AUTHOR string = "Whoops"
const CONTENT string = "Uhhhhhhhh that wasn't supposed to happen..."
// This comment will exist forever on the database, it's part of the test blog post.
x := models.Comment{Id: ID, Author: AUTHOR, Content: CONTENT}
y, err := cr.GetCommentById(ID)
if err != nil {
t.Fatalf("Expected: Comment with id: %d should be found without errors.", ID)
}
if x.Id != y.Id ||
x.Author != y.Author ||
x.Content != y.Content {
t.Fatalf("Expected(left expected, right result):\nid -> %d == %d\nauthor -> %s == %s\ncontent -> %s == %s",
ID, y.Id, AUTHOR, y.Author, CONTENT, y.Content)
}
_, err := cr.GetCommentById(0)
if err == nil {
t.Fatalf("Expected: Values of less than or equal to 0 are considered illegal values for comment id")
}
}
func TestGetCommentsByAssociatedPost(t *testing.T) {
_, err := cr.GetCommentsByAssociatedPost("")
if err == nil {
t.Fatalf("Expected: Empty values are considered illegal for associated post")
}
// Wild associated post should return empty array
post, err := cr.GetCommentsByAssociatedPost("kjdoJDOWIJWKIJALSKAJSAKIJDOIAj")
if len(*post) > 0 {
t.Fatalf("Expected: Should return empty array")
}
if err != nil {
t.Fatalf("Expected: Non existant post should not throw error, just empty array")
}
}
func TestGetCommentsByAuthor(t *testing.T) {
_, err := cr.GetCommentsByAuthor("")
if err == nil {
t.Fatalf("Expected: An empty author value should throw an error")
}
}
func TestCreateComment(t *testing.T) {
err := cr.CreateComment(nil)
if err == nil {
t.Fatalf("Expected: Nil values should result in errors when trying to create comments")
}
err = cr.CreateComment(&models.Comment{})
if err == nil {
t.Fatalf("Expected: Empty or incomplete models should result in errors.")
}
err = cr.CreateComment(&models.Comment{Author: "Chuck"})
if err == nil {
t.Fatalf("Expected: Empty or incomplete models should result in errors.")
}
}

View File

@@ -164,13 +164,9 @@ a:hover:after {
content: "' "; content: "' ";
} }
.comment { @media (prefers-color-scheme: dark) {
margin-top: 3px; body {
margin-bottom: 3px; color: #fafafa;
border: 2px solid #454545; background-color: #242124;
} }
.comment-body {
background-color: rgba(222, 222, 222, 0.5);
word-wrap: break-word;
} }

View File

@@ -1,9 +1,19 @@
{{ template "header.tmpl" . }} <html>
{{ if .Success }} <head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>admin login</title>
</head>
<body>
{{ template "nav.tmpl" . }}
{{ if . }}
<h2>Login was <u>successful</u>!</h2> <h2>Login was <u>successful</u>!</h2>
<p>Click <a href="/admin/post">here</a> to go to the post creation area.</p> <p>Click <a href="/admin/post">here</a> to go to the post creation area.</p>
{{ else }} {{ else }}
<h2>Login was <u>not</u> successful!</h2> <h2>Login was <u>not</u> successful...</h2>
<p>Click <a href="/admin/">here</a> to return to the login page to try again.</p> <p>Click <a href="/admin/">here</a> to return to the login page to try again.</p>
{{ end }} {{ end }}
</body> </body>

View File

@@ -1,6 +1,16 @@
{{ template "header.tmpl" . }} <html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>rawley.xyz | blog</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>Blog posts</h2> <h2>Blog posts</h2>
{{ range $val := .Posts }} {{ range $val := . }}
<div class="post-record"> <div class="post-record">
<div> <div>
<a class="post-record-title" href="/blog/post/{{ $val.Url }}">{{ $val.Title }}</a> <a class="post-record-title" href="/blog/post/{{ $val.Url }}">{{ $val.Title }}</a>

View File

@@ -5,33 +5,15 @@
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ"> <meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css"> <link href="/static/index.css" rel="stylesheet" type="text/css">
<title>{{ .Post.Title }}</title> <title>{{ .Title }}</title>
</head> </head>
<body> <body>
{{ template "nav.tmpl" . }} {{ template "nav.tmpl" . }}
<div> <div>
<h2>{{ .Post.Title }}</h2> <h2>{{ .Title }}</h2>
<div>{{ .Post.Content | UnescapeHTML }}</div> <div>{{ .Content | UnescapeHTML }}</div>
<h4>Comments</h4> <hr/>
{{ range $comment := .Post.Comments }} <p>
<div class="comment"> This site used to have comments. Unfortunatley maintaining a comment system that can resist bots, spammers, and other hooligans is quite tiresome. Until I figure out a way to efficiently handle comments, they are disabled. Sorry for the inconvenience.
<div> </p>
{{ $comment.Author }} at {{ $comment.Date }}
</div>
<div class="comment-body">
{{ $comment.Content }}
</div>
</div>
{{ else }}
<p>No comments...</p>
{{ end }}
<h4>Leave a comment!</h4>
<form method="POST" action="/blog/post/comment">
<input type="text" required pattern=".{3,}" title="Author name must be atleast 3 chars" placeholder="Name" maxlength="50" name="author"/>
<input type="field" required pattern=".{15,}" title="Your comment must be atleast 15 chars" placeholder="Comment" maxlength="500" name="content" />
<input type="text" class="captcha" required pattern="^\d+" title="The captcha must be a number" placeholder="What is {{ index .Captcha 0 }} plus {{ index .Captcha 1 }}" maxlength="10" name="captcha" />
<input type="text" required style="display: none;" name="url" value="{{ .Post.Url }}" readonly />
<button type="submit">Post</button>
</form>
</div>
{{ template "footer_no_banners.tmpl" . }} {{ template "footer_no_banners.tmpl" . }}

View File

@@ -1,22 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>Comment success</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>Your comment is being posted...</h2>
<p>You will be redirected or, click <a href="/blog/post/{{ .Url }}">here</a> to return to the blog post.</p>
<input value="{{ .Url }}" readonly style="display: none;" id="url"/>
<script>
setTimeout(() => {
window.location.replace("/blog/post/" + document.getElementById("url").value)
}, 1500)
</script>
</body>
</html>

View File

@@ -1,25 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>Comment failed</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>Your comment <u>failed</u> to be posted...</h2>
<p>You will be redirected or, click <a href="/blog/post/{{ .Url }}">here</a> to return to the blog post.</p>
<p>
<h3>Your comment failed for one of these reasons:</h3>
</p>
<ul>
<li>You failed the captcha.</li>
<li>Your post had links in it.</li>
<li>The name on your comment was "rawley" or "admin".</li>
<li>You're spamming!</li>
</ul>
</body>
</html>

View File

@@ -1,10 +1,26 @@
{{ template "header.tmpl" . }} <html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>crud post</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>Create post</h2> <h2>Create post</h2>
<form action="/admin/post" method="POST"> <form action="/admin/post" method="POST">
<input type="text" placeholder="url" name="url" /> <input required type="text" placeholder="url" name="url" />
<input type="text" placeholder="title" name="title" /> <input type="text" placeholder="title" name="title" />
<textarea placeholder="post" name="content"></textarea> <textarea placeholder="post" name="content"></textarea>
<select required name="op">
<option value="create">create</option>
<option value="update">update</option>
<option value="delete">delete</option>
</select>
<button type="submit">Make post</button> <button type="submit">Make post</button>
<button type="clear">Clear form</button> <button type="clear">Clear form</button>
</form> </form>
{{ template "footer.tmpl" . }} </body>
</html>

View File

@@ -1,4 +1,14 @@
{{ template "header.tmpl" . }} <html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>forbidden</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>403 You're not allowed here >:(</h2> <h2>403 You're not allowed here >:(</h2>
<p>Click <a href="/">here</a> to return home.</p> <p>Click <a href="/">here</a> to return home.</p>
</body> </body>

View File

@@ -4,7 +4,7 @@
I am an independent software engineer, and self proclaimed systems administrator from Canada. Currently, I am pursuing a degree in Computer Science, with hopes of participating in a graduate program later down the road. I am an independent software engineer, and self proclaimed systems administrator from Canada. Currently, I am pursuing a degree in Computer Science, with hopes of participating in a graduate program later down the road.
</p> </p>
<p> <p>
I am a GNU/Linux and OpenBSD enthusiast. You'll find me active in the Debian Linux, Void Linux and OpenBSD communities. My favourite programming languages are Go and Clojure. Currently, I am working on my <a href="https://gitlab.com/rawleyIfowler/rawleydotxyz">website</a>, and an open-source community based blogging network called <a href="https://gitlab.com/xrn">xrn</a>. You can check out my work on <a href="https://gitlab.com/rawleyIfowler">GitLab</a>. I am a GNU/Linux and OpenBSD enthusiast. You'll find me active in the Debian Linux, Void Linux and OpenBSD communities. My favourite programming languages are Go and Clojure. Currently, I am working on my <a href="https://gitlab.com/rawleyIfowler/rawleydotxyz">website</a>, and an open-source community based blogging network called <a href="https://gitlab.com/xrn">xrn</a>. All of my work is open source, you can check it out on my <a href="https://gitlab.com/rawleyIfowler">GitLab</a>.
</p> </p>
<p> <p>
When I'm not programming, I'm either reading, cooking, playing table-top games, or walking my dog. When I'm not programming, I'm either reading, cooking, playing table-top games, or walking my dog.

View File

@@ -1,4 +1,15 @@
{{ template "header.tmpl" . }} <html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>internal server error</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>500 Internal server error :(</h2> <h2>500 Internal server error :(</h2>
<p>Click <a href="/">here</a> to return home.</p> <p>Click <a href="/">here</a> to return home.</p>
{{ template "footer.tmpl" . }} </body>
</html>

View File

@@ -5,4 +5,4 @@
<input type="password" name="password" placeholder="password" /> <input type="password" name="password" placeholder="password" />
<button type="submit">Login</button> <button type="submit">Login</button>
</form> </form>
{{ template "footer.tmpl" . }} {{ template "footer_no_banners.tmpl" . }}

View File

@@ -1,7 +1,19 @@
<!--not_found.html--> <!--not_found.html-->
{{ template "header.tmpl" . }} <html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>not found</title>
</head>
<body>
{{ template "nav.tmpl" . }}
<h2>404 Not found :(</h2> <h2>404 Not found :(</h2>
<p> <p>
Click <a href="/">here</a> to return home. Click <a href="/">here</a> to return home.
</p> </p>
{{ template "footer.tmpl" . }} </body>
</html>

View File

@@ -1,11 +1,20 @@
{{ template "header.tmpl" . }} <html>
{{ if .Success }} <head>
<h2>Post created successfully!</h2> <meta lang="en">
<p>Click <a href="/blog/post/{{ .Url }}">here</a> to view the post.</p> <meta charset="UTF-8">
<p>Click <a href="/admin/post">here</a> to return to the posting page.</p> <meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css">
<title>forbidden</title>
</head>
<body>
{{ template "nav.tmpl" . }}
{{ if . }}
<h2>Operation performced successfuly!</h2>
<p>Click <a href="/admin/post">here</a> to return to the management page.</p>
{{ else }} {{ else }}
<h2>Post failed to be created...</h2> <h2>Operation failed to perform...</h2>
<p>Click <a href="/admin/post">here</a> to return to the posting page.</p> <p>Click <a href="/admin/post">here</a> to return to the management page.</p>
{{ end }} {{ end }}
</body> </body>
</html> </html>

View File

@@ -1,4 +1,3 @@
<!DOCTYPE html>
<html> <html>
<head> <head>
<meta lang="en"> <meta lang="en">
@@ -6,11 +5,11 @@
<meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ"> <meta name="keywords" content="blog resume rawley-fowler rawleyportfolio rawleyxyz rawleyfowler RF rawley fowler Rawley Fowler portfolio RawleyFowler RawleyXYZ rawleyXYZ RawleyXYZ">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/index.css" rel="stylesheet" type="text/css"> <link href="/static/index.css" rel="stylesheet" type="text/css">
<title>Comment spam</title> <title>session revoked</title>
</head> </head>
<body> <body>
{{ template "nav.tmpl" . }} {{ template "nav.tmpl" . }}
<h2>You've commented too many times, too quickly. Your comment will <u>not</u> be posted.</h2> <h2>403 Your session no longer exists</h2>
<p>Click <a href="/blog/post/{{ .Url }}">here</a> to return to the post.<p> <p>Click <a href="/">here</a> to return home.</p>
</body> </body>
</html> </html>

View File

@@ -1,24 +0,0 @@
package utils
import (
"bufio"
"os"
)
func LoadAdminHash(path string) [32]byte {
file, err := os.Open(path)
if err != nil {
panic("Could not find admin hash...")
}
defer file.Close()
reader := bufio.NewScanner(file)
// The dsn should be the first line of the file
if reader.Scan() {
var buff [32]byte
for i, b := range reader.Bytes() {
buff[i] = b
}
return buff
}
panic(path + " is empty...")
}

View File

@@ -16,6 +16,7 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022 along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/ */
import ( import (
"bufio" "bufio"
"os" "os"
@@ -23,10 +24,10 @@ import (
func LoadApiKey(path string) string { func LoadApiKey(path string) string {
file, err := os.Open(path) file, err := os.Open(path)
defer file.Close()
if err != nil { if err != nil {
panic("Could not find file: " + path) panic("Could not find DSN for database...")
} }
defer file.Close()
reader := bufio.NewScanner(file) reader := bufio.NewScanner(file)
if reader.Scan() { if reader.Scan() {
return reader.Text() return reader.Text()

View File

@@ -1,17 +0,0 @@
package utils
import (
"math/rand"
"time"
)
func GenerateCaptchaValues() (int, int) {
return rand.Intn(100), rand.Intn(100)
}
func UpdateCaptcha(captcha *[2]int) {
for {
captcha[0], captcha[1] = GenerateCaptchaValues()
time.Sleep(30 * time.Minute)
}
}

View File

@@ -1,4 +1,5 @@
package utils package utils
/* /*
Copyright (C) 2022 Rawley Fowler Copyright (C) 2022 Rawley Fowler
@@ -15,13 +16,17 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022 along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/ */
import ( import (
"gitlab.com/rawleyifowler/site-rework/models" "gorm.io/driver/mysql"
"gorm.io/gorm" "gorm.io/gorm"
) )
// Performs migrations of all models func CreateDatabase(dsn string) (*gorm.DB, error) {
func PerformMigrations(db *gorm.DB) { var err error
db.AutoMigrate(&models.BlogPost{}) db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db.AutoMigrate(&models.Comment{}) if err != nil {
return nil, err
}
return db, nil
} }

View File

@@ -16,6 +16,7 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022 along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/ */
import ( import (
"bufio" "bufio"
"os" "os"

View File

@@ -1,4 +1,4 @@
package models package utils
/* /*
Copyright (C) 2022 Rawley Fowler Copyright (C) 2022 Rawley Fowler
@@ -16,15 +16,16 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022 along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/ */
import ( import (
"gorm.io/driver/mysql"
"gorm.io/gorm" "gorm.io/gorm"
) )
type Comment struct { func InitializeDatabase(dsn string) *gorm.DB {
gorm.Model db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
Id uint `json:"id" gorm:"primaryKey, AUTO_INCREMENT"` if err != nil {
Date string `json:"date" gorm:"default:NOW()"` panic("Failed to open database with dsn -> " + dsn)
Author string `json:"author" form:"author" gorm:"type:varchar(50)"` }
Content string `json:"content" form:"content" gorm:"type:varchar(500)"` return db
AssociatedPost string
} }

View File

@@ -1,5 +1,22 @@
package utils package utils
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import ( import (
"net/http" "net/http"
"strings" "strings"
@@ -7,21 +24,14 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Returns a handler function to serve a page based on the template that is inputted func ServePage(t string) gin.HandlerFunc {
func ServePage(temp string) gin.HandlerFunc { title := strings.Split(t, ".")[0]
title := strings.Split(temp, ".")[0]
if title == "index" { if title == "index" {
// Index is the home page so we don't care
title = "" title = ""
} else { } else {
// Else title it accordingly
title = " | " + title title = " | " + title
} }
return func(c *gin.Context) { return func(c *gin.Context) {
c.HTML( c.HTML(http.StatusOK, t, struct{ Title string }{Title: title})
http.StatusOK,
temp,
struct{ Title string }{Title: title},
)
} }
} }

View File

@@ -1,6 +0,0 @@
package utils
// TODO: Implement a spam checking module
func IsSpam(t string) bool {
return false
}

View File

@@ -1,19 +0,0 @@
package utils
import (
"strconv"
"time"
)
func TimedClearMap(m *map[string]uint, timer uint) {
for {
t, err := time.ParseDuration(strconv.FormatUint(uint64(timer), 10) + "ms")
if err != nil {
panic("Something went wrong initializing time!!")
}
time.Sleep(t)
for key := range *m {
delete(*m, key)
}
}
}

29
utils/timed_clear_map.go Normal file
View File

@@ -0,0 +1,29 @@
package utils
/*
Copyright (C) 2022 Rawley Fowler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.Rawley Fowler, 2022
*/
import "time"
func TimeClearMap(m map[string]int64, t int64) {
time.Sleep(time.Duration(t) * time.Millisecond)
for k := range m {
if m[k] < time.Now().UnixMilli()+t {
delete(m, k)
}
}
}