Clean up error handling, migrate to log/slog, add todo for flash message system in post controller

This commit is contained in:
Maximilian 2023-09-03 15:45:12 -05:00
parent ee4c9f9199
commit ed712a5344
10 changed files with 51 additions and 68 deletions

View File

@ -3,7 +3,7 @@ package config
import ( import (
"encoding/json" "encoding/json"
"flag" "flag"
"log" "log/slog"
"os" "os"
) )
@ -33,13 +33,13 @@ func LoadConfig() Configuration {
flag.Parse() flag.Parse()
file, err := os.Open(*c) file, err := os.Open(*c)
if err != nil { if err != nil {
log.Fatal("Unable to open JSON config file: ", err) panic("Unable to open JSON config file: " + err.Error())
} }
defer func(file *os.File) { defer func(file *os.File) {
err := file.Close() err := file.Close()
if err != nil { if err != nil {
log.Fatal("Unable to close JSON config file: ", err) slog.Error("Unable to close JSON config file: ", err)
} }
}(file) }(file)
@ -47,7 +47,7 @@ func LoadConfig() Configuration {
Config := Configuration{} Config := Configuration{}
err = decoder.Decode(&Config) err = decoder.Decode(&Config)
if err != nil { if err != nil {
log.Fatal("Unable to decode JSON config file: ", err) panic("Unable to decode JSON config file: " + err.Error())
} }
return Config return Config

View File

@ -3,7 +3,7 @@ package controllers
import ( import (
"GoWeb/app" "GoWeb/app"
"GoWeb/models" "GoWeb/models"
"log" "log/slog"
"net/http" "net/http"
"time" "time"
) )
@ -19,15 +19,12 @@ func (p *Post) Login(w http.ResponseWriter, r *http.Request) {
remember := r.FormValue("remember") == "on" remember := r.FormValue("remember") == "on"
if username == "" || password == "" { if username == "" || password == "" {
log.Println("Tried to login user with empty username or password") http.Redirect(w, r, "/login", http.StatusUnauthorized)
http.Redirect(w, r, "/login", http.StatusFound)
} }
_, err := models.AuthenticateUser(p.App, w, username, password, remember) _, err := models.AuthenticateUser(p.App, w, username, password, remember)
if err != nil { if err != nil {
log.Println("Error authenticating user") http.Redirect(w, r, "/login", http.StatusUnauthorized)
log.Println(err)
http.Redirect(w, r, "/login", http.StatusFound)
return return
} }
@ -41,15 +38,14 @@ func (p *Post) Register(w http.ResponseWriter, r *http.Request) {
updatedAt := time.Now() updatedAt := time.Now()
if username == "" || password == "" { if username == "" || password == "" {
log.Println("Tried to create user with empty username or password") http.Redirect(w, r, "/register", http.StatusUnauthorized)
http.Redirect(w, r, "/register", http.StatusFound)
} }
_, err := models.CreateUser(p.App, username, password, createdAt, updatedAt) _, err := models.CreateUser(p.App, username, password, createdAt, updatedAt)
if err != nil { if err != nil {
log.Println("Error creating user") // TODO: if err == bcrypt.ErrPasswordTooLong display error to user, this will require a flash message system with cookies
log.Println(err) slog.Error("error creating user: " + err.Error())
return http.Redirect(w, r, "/register", http.StatusInternalServerError)
} }
http.Redirect(w, r, "/login", http.StatusFound) http.Redirect(w, r, "/login", http.StatusFound)

View File

@ -5,7 +5,7 @@ import (
"database/sql" "database/sql"
"fmt" "fmt"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"log" "log/slog"
) )
// Connect returns a new database connection // Connect returns a new database connection
@ -24,7 +24,7 @@ func Connect(app *app.App) *sql.DB {
panic(err) panic(err)
} }
log.Println("Connected to database successfully on " + app.Config.Db.Ip + ":" + app.Config.Db.Port + " using database " + app.Config.Db.Name) slog.Info("Connected to database successfully on " + app.Config.Db.Ip + ":" + app.Config.Db.Port + " using database " + app.Config.Db.Name)
return db return db
} }

View File

@ -5,7 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/lib/pq" "github.com/lib/pq"
"log" "log/slog"
"reflect" "reflect"
) )
@ -39,23 +39,23 @@ func createTable(app *app.App, tableName string) error {
var tableExists bool var tableExists bool
err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ $1 AND pg_catalog.pg_table_is_visible(c.oid))", "^"+tableName+"$").Scan(&tableExists) err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ $1 AND pg_catalog.pg_table_is_visible(c.oid))", "^"+tableName+"$").Scan(&tableExists)
if err != nil { if err != nil {
log.Println("Error checking if table exists: " + tableName) slog.Error("Error checking if table exists: " + tableName)
return err return err
} }
if tableExists { if tableExists {
log.Println("Table already exists: " + tableName) slog.Info("Table already exists: " + tableName)
return nil return nil
} else { } else {
sanitizedTableQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS \"%s\" (\"Id\" serial primary key)", tableName) sanitizedTableQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS \"%s\" (\"Id\" serial primary key)", tableName)
_, err := app.Db.Query(sanitizedTableQuery) _, err := app.Db.Query(sanitizedTableQuery)
if err != nil { if err != nil {
log.Println("Error creating table: " + tableName) slog.Error("Error creating table: " + tableName)
return err return err
} }
log.Println("Table created successfully: " + tableName) slog.Info("Table created successfully: " + tableName)
return nil return nil
} }
} }
@ -65,17 +65,17 @@ func createColumn(app *app.App, tableName, columnName, columnType string) error
var columnExists bool var columnExists bool
err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2)", tableName, columnName).Scan(&columnExists) err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2)", tableName, columnName).Scan(&columnExists)
if err != nil { if err != nil {
log.Println("Error checking if column exists: " + columnName + " in table: " + tableName) slog.Error("Error checking if column exists: " + columnName + " in table: " + tableName)
return err return err
} }
if columnExists { if columnExists {
log.Println("Column already exists: " + columnName + " in table: " + tableName) slog.Info("Column already exists: " + columnName + " in table: " + tableName)
return nil return nil
} else { } else {
postgresType, err := getPostgresType(columnType) postgresType, err := getPostgresType(columnType)
if err != nil { if err != nil {
log.Println("Error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType) slog.Error("Error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType)
return err return err
} }
@ -84,11 +84,11 @@ func createColumn(app *app.App, tableName, columnName, columnType string) error
_, err = app.Db.Query(query) _, err = app.Db.Query(query)
if err != nil { if err != nil {
log.Println("Error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType) slog.Error("Error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType)
return err return err
} }
log.Println("Column created successfully:", columnName) slog.Info("Column created successfully:", columnName)
return nil return nil
} }

View File

@ -2,7 +2,7 @@ package middleware
import ( import (
"GoWeb/security" "GoWeb/security"
"log" "log/slog"
"net/http" "net/http"
) )
@ -11,7 +11,7 @@ func Csrf(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWr
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
_, err := security.VerifyCsrfToken(r) _, err := security.VerifyCsrfToken(r)
if err != nil { if err != nil {
log.Println("Error verifying csrf token") slog.Info("error verifying csrf token")
http.Error(w, "Forbidden", http.StatusForbidden) http.Error(w, "Forbidden", http.StatusForbidden)
return return
} }

View File

@ -4,7 +4,7 @@ import (
"GoWeb/app" "GoWeb/app"
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"log" "log/slog"
"net/http" "net/http"
"time" "time"
) )
@ -42,20 +42,19 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember b
var existingAuthToken bool var existingAuthToken bool
err := app.Db.QueryRow(selectAuthTokenIfExists, session.AuthToken).Scan(&existingAuthToken) err := app.Db.QueryRow(selectAuthTokenIfExists, session.AuthToken).Scan(&existingAuthToken)
if err != nil { if err != nil {
log.Println("Error checking for existing auth token") slog.Error("error checking for existing auth token" + err.Error())
log.Println(err)
return Session{}, err return Session{}, err
} }
// If duplicate token found, recursively call function until unique token is generated // If duplicate token found, recursively call function until unique token is generated
if existingAuthToken == true { if existingAuthToken == true {
log.Println("Duplicate token found in sessions table, generating new token...") slog.Warn("duplicate token found in sessions table, generating new token...")
return CreateSession(app, w, userId, remember) return CreateSession(app, w, userId, remember)
} }
err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.RememberMe, session.CreatedAt).Scan(&session.Id) err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.RememberMe, session.CreatedAt).Scan(&session.Id)
if err != nil { if err != nil {
log.Println("Error inserting session into database") slog.Error("error inserting session into database")
return Session{}, err return Session{}, err
} }
@ -68,7 +67,6 @@ func GetSessionByAuthToken(app *app.App, authToken string) (Session, error) {
err := app.Db.QueryRow(selectSessionByAuthToken, authToken).Scan(&session.Id, &session.UserId, &session.AuthToken, &session.RememberMe, &session.CreatedAt) err := app.Db.QueryRow(selectSessionByAuthToken, authToken).Scan(&session.Id, &session.UserId, &session.AuthToken, &session.RememberMe, &session.CreatedAt)
if err != nil { if err != nil {
log.Println("Error getting session by auth token")
return Session{}, err return Session{}, err
} }
@ -80,7 +78,7 @@ func generateAuthToken(app *app.App) string {
b := make([]byte, 64) b := make([]byte, 64)
_, err := rand.Read(b) _, err := rand.Read(b)
if err != nil { if err != nil {
log.Println("Error generating random bytes") slog.Error("error generating random bytes for auth token")
} }
return hex.EncodeToString(b) return hex.EncodeToString(b)
@ -128,7 +126,7 @@ func deleteSessionCookie(app *app.App, w http.ResponseWriter) {
func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken string) error { func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken string) error {
_, err := app.Db.Exec(deleteSessionByAuthToken, authToken) _, err := app.Db.Exec(deleteSessionByAuthToken, authToken)
if err != nil { if err != nil {
log.Println("Error deleting session from database") slog.Error("error deleting session from database")
return err return err
} }
@ -142,16 +140,14 @@ func ScheduledSessionCleanup(app *app.App) {
// Delete sessions older than 30 days (remember me sessions) // Delete sessions older than 30 days (remember me sessions)
_, err := app.Db.Exec(deleteSessionsOlderThan30Days) _, err := app.Db.Exec(deleteSessionsOlderThan30Days)
if err != nil { if err != nil {
log.Println("Error deleting 30 day expired sessions from database") slog.Error("error deleting 30 day expired sessions from database" + err.Error())
log.Println(err)
} }
// Delete sessions older than 6 hours // Delete sessions older than 6 hours
_, err = app.Db.Exec(deleteSessionsOlderThan6Hours) _, err = app.Db.Exec(deleteSessionsOlderThan6Hours)
if err != nil { if err != nil {
log.Println("Error deleting 6 hour expired sessions from database") slog.Error("error deleting 6 hour expired sessions from database" + err.Error())
log.Println(err)
} }
log.Println("Deleted expired sessions from database") slog.Info("deleted expired sessions from database")
} }

View File

@ -2,9 +2,8 @@ package models
import ( import (
"GoWeb/app" "GoWeb/app"
"log" "log/slog"
"net/http" "net/http"
"strconv"
"time" "time"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@ -32,13 +31,11 @@ const (
func GetCurrentUser(app *app.App, r *http.Request) (User, error) { func GetCurrentUser(app *app.App, r *http.Request) (User, error) {
cookie, err := r.Cookie("session") cookie, err := r.Cookie("session")
if err != nil { if err != nil {
log.Println("Error getting session cookie")
return User{}, err return User{}, err
} }
session, err := GetSessionByAuthToken(app, cookie.Value) session, err := GetSessionByAuthToken(app, cookie.Value)
if err != nil { if err != nil {
log.Println("Error getting session by auth token")
return User{}, err return User{}, err
} }
@ -51,7 +48,6 @@ func GetUserById(app *app.App, id int64) (User, error) {
err := app.Db.QueryRow(selectUserById, id).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt) err := app.Db.QueryRow(selectUserById, id).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
if err != nil { if err != nil {
log.Println("Get user error (user not found) for user id:" + strconv.FormatInt(id, 10))
return User{}, err return User{}, err
} }
@ -64,7 +60,6 @@ func GetUserByUsername(app *app.App, username string) (User, error) {
err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt) err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
if err != nil { if err != nil {
log.Println("Get user error (user not found) for user:" + username)
return User{}, err return User{}, err
} }
@ -75,7 +70,7 @@ func GetUserByUsername(app *app.App, username string) (User, error) {
func CreateUser(app *app.App, username string, password string, createdAt time.Time, updatedAt time.Time) (User, error) { func CreateUser(app *app.App, username string, password string, createdAt time.Time, updatedAt time.Time) (User, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil { if err != nil {
log.Println("Error hashing password when creating user") slog.Error("error hashing password: " + err.Error())
return User{}, err return User{}, err
} }
@ -83,7 +78,7 @@ func CreateUser(app *app.App, username string, password string, createdAt time.T
err = app.Db.QueryRow(insertUser, username, string(hash), createdAt, updatedAt).Scan(&lastInsertId) err = app.Db.QueryRow(insertUser, username, string(hash), createdAt, updatedAt).Scan(&lastInsertId)
if err != nil { if err != nil {
log.Println("Error creating user row") slog.Error("error creating user row: " + err.Error())
return User{}, err return User{}, err
} }
@ -96,13 +91,13 @@ func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, pass
err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt) err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
if err != nil { if err != nil {
log.Println("Authentication error (user not found) for user:" + username) slog.Info("user not found: " + username)
return Session{}, err return Session{}, err
} }
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil { // Failed to validate password, doesn't match if err != nil { // Failed to validate password, doesn't match
log.Println("Authentication error (incorrect password) for user:" + username) slog.Info("incorrect password:" + username)
return Session{}, err return Session{}, err
} else { } else {
return CreateSession(app, w, user.Id, remember) return CreateSession(app, w, user.Id, remember)
@ -113,13 +108,11 @@ func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, pass
func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) { func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session") cookie, err := r.Cookie("session")
if err != nil { if err != nil {
log.Println("Error getting cookie from request")
return return
} }
err = DeleteSessionByAuthToken(app, w, cookie.Value) err = DeleteSessionByAuthToken(app, w, cookie.Value)
if err != nil { if err != nil {
log.Println("Error deleting session by AuthToken")
return return
} }
} }

View File

@ -4,7 +4,7 @@ import (
"GoWeb/app" "GoWeb/app"
"GoWeb/controllers" "GoWeb/controllers"
"io/fs" "io/fs"
"log" "log/slog"
"net/http" "net/http"
) )
@ -18,12 +18,12 @@ func Get(app *app.App) {
// Serve static files // Serve static files
staticFS, err := fs.Sub(app.Res, "static") staticFS, err := fs.Sub(app.Res, "static")
if err != nil { if err != nil {
log.Println(err) slog.Error(err.Error())
return return
} }
staticHandler := http.FileServer(http.FS(staticFS)) staticHandler := http.FileServer(http.FS(staticFS))
http.Handle("/static/", http.StripPrefix("/static/", staticHandler)) http.Handle("/static/", http.StripPrefix("/static/", staticHandler))
log.Println("Serving static files from embedded file system /static") slog.Info("Serving static files from embedded file system /static")
// Pages // Pages
http.HandleFunc("/", getController.ShowHome) http.HandleFunc("/", getController.ShowHome)

View File

@ -3,7 +3,7 @@ package security
import ( import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"log" "log/slog"
"math" "math"
"net/http" "net/http"
) )
@ -13,8 +13,7 @@ func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
buff := make([]byte, int(math.Ceil(float64(64)/2))) buff := make([]byte, int(math.Ceil(float64(64)/2)))
_, err := rand.Read(buff) _, err := rand.Read(buff)
if err != nil { if err != nil {
log.Println("Error creating random buffer for csrf token value") slog.Error("Error creating random buffer for csrf token value" + err.Error())
log.Println(err)
return "", err return "", err
} }
str := hex.EncodeToString(buff) str := hex.EncodeToString(buff)
@ -38,8 +37,7 @@ func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
func VerifyCsrfToken(r *http.Request) (bool, error) { func VerifyCsrfToken(r *http.Request) (bool, error) {
cookie, err := r.Cookie("csrf_token") cookie, err := r.Cookie("csrf_token")
if err != nil { if err != nil {
log.Println("Error getting csrf_token cookie") slog.Info("Unable to get csrf_token cookie" + err.Error())
log.Println(err)
return false, err return false, err
} }

View File

@ -3,7 +3,7 @@ package templating
import ( import (
"GoWeb/app" "GoWeb/app"
"html/template" "html/template"
"log" "log/slog"
"net/http" "net/http"
) )
@ -13,35 +13,35 @@ func RenderTemplate(app *app.App, w http.ResponseWriter, contentPath string, dat
templateContent, err := app.Res.ReadFile(templatePath) templateContent, err := app.Res.ReadFile(templatePath)
if err != nil { if err != nil {
log.Println(err) slog.Error(err.Error())
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }
t, err := template.New(templatePath).Parse(string(templateContent)) t, err := template.New(templatePath).Parse(string(templateContent))
if err != nil { if err != nil {
log.Println(err) slog.Error(err.Error())
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }
content, err := app.Res.ReadFile(contentPath) content, err := app.Res.ReadFile(contentPath)
if err != nil { if err != nil {
log.Println(err) slog.Error(err.Error())
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }
t, err = t.Parse(string(content)) t, err = t.Parse(string(content))
if err != nil { if err != nil {
log.Println(err) slog.Error(err.Error())
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }
err = t.Execute(w, data) err = t.Execute(w, data)
if err != nil { if err != nil {
log.Println(err) slog.Error(err.Error())
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return return
} }