15 Commits

Author SHA1 Message Date
Maximilian
a1438f4fe2 Update README.md 2023-07-31 20:18:11 -05:00
Maximilian
052fa689c7 Merge branch 'middleware' 2023-07-31 18:41:49 -05:00
Maximilian
f1fad7e4e3 Pass in handler to middleware, create definition for MiddlewareFunc 2023-07-31 18:37:54 -05:00
Maximilian
b475da66da Fix nil error for GET requests 2023-07-26 13:09:01 -05:00
Maximilian
d0085ab2c3 Update crypto dependency 2023-07-25 15:36:25 -05:00
Maximilian
58514f4c5f Update client to handle GET (no body) requests, multipart requests, and JSON requests 2023-07-25 15:34:11 -05:00
Maximilian
606f5df45a Refactor name 2023-07-22 23:37:38 -05:00
Maximilian
2a32a1b3ce Add restclient package, and a simple function to send HTTP requests 2023-07-21 16:35:18 -05:00
Maximilian
eb36156c52 Change function name to ProcessGroup 2023-07-21 16:26:43 -05:00
Maximilian
bada24884a Use ungrouped CSRF middleware on register and login POST routes 2023-07-21 11:59:55 -05:00
Maximilian
05397c2b61 Initial middleware implementation for CSRF and update comment 2023-07-21 11:59:01 -05:00
Maximilian
3d80b95f55 Initial wrapper implementation 2023-07-07 18:05:17 -05:00
Maximilian
6da7d408f9 Add .gitattributes to force LF line endings 2023-05-05 12:19:17 -05:00
max
e993bcf317 Update dependency versions 2023-05-04 09:00:35 -05:00
Maximilian
9b231a73d6 Update README.md 2023-04-07 21:32:39 -05:00
10 changed files with 113 additions and 25 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

View File

@@ -12,9 +12,12 @@ fine with getting your hands dirty, but I plan on having it ready to go for more
- Routing/controllers - Routing/controllers
- Templating - Templating
- Simple database migration system - Simple database migration system
- Built in REST client
- CSRF protection - CSRF protection
- Middleware
- Minimal user login/registration + sessions - Minimal user login/registration + sessions
- Config file handling - Config file handling
- Scheduled tasks
- Entire website compiles into a single binary (~10mb) (excluding env.json) - Entire website compiles into a single binary (~10mb) (excluding env.json)
- Minimal dependencies (just standard library, postgres driver, and experimental package for bcrypt) - Minimal dependencies (just standard library, postgres driver, and experimental package for bcrypt)

View File

@@ -3,7 +3,6 @@ package controllers
import ( import (
"GoWeb/app" "GoWeb/app"
"GoWeb/models" "GoWeb/models"
"GoWeb/security"
"log" "log"
"net/http" "net/http"
"time" "time"
@@ -15,13 +14,6 @@ type PostController struct {
} }
func (postController *PostController) Login(w http.ResponseWriter, r *http.Request) { func (postController *PostController) Login(w http.ResponseWriter, r *http.Request) {
// Validate csrf token
_, err := security.VerifyCsrfToken(r)
if err != nil {
log.Println("Error verifying csrf token")
return
}
username := r.FormValue("username") username := r.FormValue("username")
password := r.FormValue("password") password := r.FormValue("password")
remember := r.FormValue("remember") == "on" remember := r.FormValue("remember") == "on"
@@ -31,7 +23,7 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
http.Redirect(w, r, "/login", http.StatusFound) http.Redirect(w, r, "/login", http.StatusFound)
} }
_, err = models.AuthenticateUser(postController.App, w, username, password, remember) _, err := models.AuthenticateUser(postController.App, w, username, password, remember)
if err != nil { if err != nil {
log.Println("Error authenticating user") log.Println("Error authenticating user")
log.Println(err) log.Println(err)
@@ -43,13 +35,6 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
} }
func (postController *PostController) Register(w http.ResponseWriter, r *http.Request) { func (postController *PostController) Register(w http.ResponseWriter, r *http.Request) {
// Validate csrf token
_, err := security.VerifyCsrfToken(r)
if err != nil {
log.Println("Error verifying csrf token")
return
}
username := r.FormValue("username") username := r.FormValue("username")
password := r.FormValue("password") password := r.FormValue("password")
createdAt := time.Now() createdAt := time.Now()
@@ -60,7 +45,7 @@ func (postController *PostController) Register(w http.ResponseWriter, r *http.Re
http.Redirect(w, r, "/register", http.StatusFound) http.Redirect(w, r, "/register", http.StatusFound)
} }
_, err = models.CreateUser(postController.App, username, password, createdAt, updatedAt) _, err := models.CreateUser(postController.App, username, password, createdAt, updatedAt)
if err != nil { if err != nil {
log.Println("Error creating user") log.Println("Error creating user")
log.Println(err) log.Println(err)

4
go.mod
View File

@@ -3,6 +3,6 @@ module GoWeb
go 1.20 go 1.20
require ( require (
github.com/lib/pq v1.10.7 github.com/lib/pq v1.10.9
golang.org/x/crypto v0.7.0 golang.org/x/crypto v0.11.0
) )

8
go.sum
View File

@@ -1,4 +1,4 @@
github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=

22
middleware/csrf.go Normal file
View File

@@ -0,0 +1,22 @@
package middleware
import (
"GoWeb/security"
"log"
"net/http"
)
// Csrf validates the CSRF token and returns the handler function if it succeded
func Csrf(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Verify csrf token
_, err := security.VerifyCsrfToken(r)
if err != nil {
log.Println("Error verifying csrf token")
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
f(w, r)
}
}

5
middleware/groups.go Normal file
View File

@@ -0,0 +1,5 @@
package middleware
import "net/http"
type MiddlewareFunc func(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)

14
middleware/wrapper.go Normal file
View File

@@ -0,0 +1,14 @@
package middleware
import "net/http"
// ProcessGroup is a wrapper function for the http.HandleFunc function
// that takes the function you want to execute (f) and the middleware you want
// to execute (m) this should be used when processing multiple groups of middleware at a time
func ProcessGroup(f func(w http.ResponseWriter, r *http.Request), m []MiddlewareFunc) func(w http.ResponseWriter, r *http.Request) {
for _, middleware := range m {
_ = middleware(f)
}
return f
}

57
restclient/client.go Normal file
View File

@@ -0,0 +1,57 @@
package restclient
import (
"bytes"
"encoding/json"
"mime/multipart"
"net/http"
)
// SendRequest sends an HTTP request to a URL and includes the specified headers and body.
// A body can be nil for GET requests, a map[string]string for multipart/form-data requests,
// or a struct for JSON requests
func SendRequest(url string, method string, headers map[string]string, body interface{}) (http.Response, error) {
var reqBody *bytes.Buffer
var contentType string
switch v := body.(type) {
case nil:
reqBody = bytes.NewBuffer([]byte(""))
case map[string]string:
reqBody = &bytes.Buffer{}
writer := multipart.NewWriter(reqBody)
for key, value := range v {
writer.WriteField(key, value)
}
writer.Close()
contentType = writer.FormDataContentType()
default:
jsonBody, err := json.Marshal(body)
if err != nil {
return http.Response{}, err
}
reqBody = bytes.NewBuffer(jsonBody)
contentType = "application/json"
}
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return http.Response{}, err
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
for key, value := range headers {
req.Header.Add(key, value)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return http.Response{}, err
}
return *resp, nil
}

View File

@@ -3,6 +3,7 @@ package routes
import ( import (
"GoWeb/app" "GoWeb/app"
"GoWeb/controllers" "GoWeb/controllers"
"GoWeb/middleware"
"net/http" "net/http"
) )
@@ -14,6 +15,6 @@ func PostRoutes(app *app.App) {
} }
// User authentication // User authentication
http.HandleFunc("/register-handle", postController.Register) http.HandleFunc("/register-handle", middleware.Csrf(postController.Register))
http.HandleFunc("/login-handle", postController.Login) http.HandleFunc("/login-handle", middleware.Csrf(postController.Login))
} }