From ed712a5344e5f1411bbdc27a193a5ad779810bef Mon Sep 17 00:00:00 2001 From: Maximilian Date: Sun, 3 Sep 2023 15:45:12 -0500 Subject: [PATCH] Clean up error handling, migrate to log/slog, add todo for flash message system in post controller --- config/config.go | 8 ++++---- controllers/post.go | 18 +++++++----------- database/connection.go | 4 ++-- database/migrate.go | 20 ++++++++++---------- middleware/csrf.go | 4 ++-- models/session.go | 22 +++++++++------------- models/user.go | 17 +++++------------ routes/get.go | 6 +++--- security/csrf.go | 8 +++----- templating/templateHelper.go | 12 ++++++------ 10 files changed, 51 insertions(+), 68 deletions(-) diff --git a/config/config.go b/config/config.go index 8ca2691..19c39e2 100644 --- a/config/config.go +++ b/config/config.go @@ -3,7 +3,7 @@ package config import ( "encoding/json" "flag" - "log" + "log/slog" "os" ) @@ -33,13 +33,13 @@ func LoadConfig() Configuration { flag.Parse() file, err := os.Open(*c) 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) { err := file.Close() if err != nil { - log.Fatal("Unable to close JSON config file: ", err) + slog.Error("Unable to close JSON config file: ", err) } }(file) @@ -47,7 +47,7 @@ func LoadConfig() Configuration { Config := Configuration{} err = decoder.Decode(&Config) if err != nil { - log.Fatal("Unable to decode JSON config file: ", err) + panic("Unable to decode JSON config file: " + err.Error()) } return Config diff --git a/controllers/post.go b/controllers/post.go index 523f64c..5b23050 100644 --- a/controllers/post.go +++ b/controllers/post.go @@ -3,7 +3,7 @@ package controllers import ( "GoWeb/app" "GoWeb/models" - "log" + "log/slog" "net/http" "time" ) @@ -19,15 +19,12 @@ func (p *Post) Login(w http.ResponseWriter, r *http.Request) { remember := r.FormValue("remember") == "on" if username == "" || password == "" { - log.Println("Tried to login user with empty username or password") - http.Redirect(w, r, "/login", http.StatusFound) + http.Redirect(w, r, "/login", http.StatusUnauthorized) } _, err := models.AuthenticateUser(p.App, w, username, password, remember) if err != nil { - log.Println("Error authenticating user") - log.Println(err) - http.Redirect(w, r, "/login", http.StatusFound) + http.Redirect(w, r, "/login", http.StatusUnauthorized) return } @@ -41,15 +38,14 @@ func (p *Post) Register(w http.ResponseWriter, r *http.Request) { updatedAt := time.Now() if username == "" || password == "" { - log.Println("Tried to create user with empty username or password") - http.Redirect(w, r, "/register", http.StatusFound) + http.Redirect(w, r, "/register", http.StatusUnauthorized) } _, err := models.CreateUser(p.App, username, password, createdAt, updatedAt) if err != nil { - log.Println("Error creating user") - log.Println(err) - return + // TODO: if err == bcrypt.ErrPasswordTooLong display error to user, this will require a flash message system with cookies + slog.Error("error creating user: " + err.Error()) + http.Redirect(w, r, "/register", http.StatusInternalServerError) } http.Redirect(w, r, "/login", http.StatusFound) diff --git a/database/connection.go b/database/connection.go index 372ae8e..12315db 100644 --- a/database/connection.go +++ b/database/connection.go @@ -5,7 +5,7 @@ import ( "database/sql" "fmt" _ "github.com/lib/pq" - "log" + "log/slog" ) // Connect returns a new database connection @@ -24,7 +24,7 @@ func Connect(app *app.App) *sql.DB { 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 } diff --git a/database/migrate.go b/database/migrate.go index b1885e0..e859d51 100644 --- a/database/migrate.go +++ b/database/migrate.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" "github.com/lib/pq" - "log" + "log/slog" "reflect" ) @@ -39,23 +39,23 @@ func createTable(app *app.App, tableName string) error { 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) if err != nil { - log.Println("Error checking if table exists: " + tableName) + slog.Error("Error checking if table exists: " + tableName) return err } if tableExists { - log.Println("Table already exists: " + tableName) + slog.Info("Table already exists: " + tableName) return nil } else { sanitizedTableQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS \"%s\" (\"Id\" serial primary key)", tableName) _, err := app.Db.Query(sanitizedTableQuery) if err != nil { - log.Println("Error creating table: " + tableName) + slog.Error("Error creating table: " + tableName) return err } - log.Println("Table created successfully: " + tableName) + slog.Info("Table created successfully: " + tableName) return nil } } @@ -65,17 +65,17 @@ func createColumn(app *app.App, tableName, columnName, columnType string) error 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) 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 } if columnExists { - log.Println("Column already exists: " + columnName + " in table: " + tableName) + slog.Info("Column already exists: " + columnName + " in table: " + tableName) return nil } else { postgresType, err := getPostgresType(columnType) 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 } @@ -84,11 +84,11 @@ func createColumn(app *app.App, tableName, columnName, columnType string) error _, err = app.Db.Query(query) 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 } - log.Println("Column created successfully:", columnName) + slog.Info("Column created successfully:", columnName) return nil } diff --git a/middleware/csrf.go b/middleware/csrf.go index 868c925..19a8219 100644 --- a/middleware/csrf.go +++ b/middleware/csrf.go @@ -2,7 +2,7 @@ package middleware import ( "GoWeb/security" - "log" + "log/slog" "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) { _, err := security.VerifyCsrfToken(r) if err != nil { - log.Println("Error verifying csrf token") + slog.Info("error verifying csrf token") http.Error(w, "Forbidden", http.StatusForbidden) return } diff --git a/models/session.go b/models/session.go index ffe8130..de644f5 100644 --- a/models/session.go +++ b/models/session.go @@ -4,7 +4,7 @@ import ( "GoWeb/app" "crypto/rand" "encoding/hex" - "log" + "log/slog" "net/http" "time" ) @@ -42,20 +42,19 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember b var existingAuthToken bool err := app.Db.QueryRow(selectAuthTokenIfExists, session.AuthToken).Scan(&existingAuthToken) if err != nil { - log.Println("Error checking for existing auth token") - log.Println(err) + slog.Error("error checking for existing auth token" + err.Error()) return Session{}, err } // If duplicate token found, recursively call function until unique token is generated 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) } err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.RememberMe, session.CreatedAt).Scan(&session.Id) if err != nil { - log.Println("Error inserting session into database") + slog.Error("error inserting session into database") 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) if err != nil { - log.Println("Error getting session by auth token") return Session{}, err } @@ -80,7 +78,7 @@ func generateAuthToken(app *app.App) string { b := make([]byte, 64) _, err := rand.Read(b) if err != nil { - log.Println("Error generating random bytes") + slog.Error("error generating random bytes for auth token") } 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 { _, err := app.Db.Exec(deleteSessionByAuthToken, authToken) if err != nil { - log.Println("Error deleting session from database") + slog.Error("error deleting session from database") return err } @@ -142,16 +140,14 @@ func ScheduledSessionCleanup(app *app.App) { // Delete sessions older than 30 days (remember me sessions) _, err := app.Db.Exec(deleteSessionsOlderThan30Days) if err != nil { - log.Println("Error deleting 30 day expired sessions from database") - log.Println(err) + slog.Error("error deleting 30 day expired sessions from database" + err.Error()) } // Delete sessions older than 6 hours _, err = app.Db.Exec(deleteSessionsOlderThan6Hours) if err != nil { - log.Println("Error deleting 6 hour expired sessions from database") - log.Println(err) + slog.Error("error deleting 6 hour expired sessions from database" + err.Error()) } - log.Println("Deleted expired sessions from database") + slog.Info("deleted expired sessions from database") } diff --git a/models/user.go b/models/user.go index d3739b5..4ac0009 100644 --- a/models/user.go +++ b/models/user.go @@ -2,9 +2,8 @@ package models import ( "GoWeb/app" - "log" + "log/slog" "net/http" - "strconv" "time" "golang.org/x/crypto/bcrypt" @@ -32,13 +31,11 @@ const ( func GetCurrentUser(app *app.App, r *http.Request) (User, error) { cookie, err := r.Cookie("session") if err != nil { - log.Println("Error getting session cookie") return User{}, err } session, err := GetSessionByAuthToken(app, cookie.Value) if err != nil { - log.Println("Error getting session by auth token") 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) if err != nil { - log.Println("Get user error (user not found) for user id:" + strconv.FormatInt(id, 10)) 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) if err != nil { - log.Println("Get user error (user not found) for user:" + username) 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) { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { - log.Println("Error hashing password when creating user") + slog.Error("error hashing password: " + err.Error()) 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) if err != nil { - log.Println("Error creating user row") + slog.Error("error creating user row: " + err.Error()) 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) if err != nil { - log.Println("Authentication error (user not found) for user:" + username) + slog.Info("user not found: " + username) return Session{}, err } err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) 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 } else { 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) { cookie, err := r.Cookie("session") if err != nil { - log.Println("Error getting cookie from request") return } err = DeleteSessionByAuthToken(app, w, cookie.Value) if err != nil { - log.Println("Error deleting session by AuthToken") return } } diff --git a/routes/get.go b/routes/get.go index e3049b1..0109773 100644 --- a/routes/get.go +++ b/routes/get.go @@ -4,7 +4,7 @@ import ( "GoWeb/app" "GoWeb/controllers" "io/fs" - "log" + "log/slog" "net/http" ) @@ -18,12 +18,12 @@ func Get(app *app.App) { // Serve static files staticFS, err := fs.Sub(app.Res, "static") if err != nil { - log.Println(err) + slog.Error(err.Error()) return } staticHandler := http.FileServer(http.FS(staticFS)) 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 http.HandleFunc("/", getController.ShowHome) diff --git a/security/csrf.go b/security/csrf.go index cd6db3b..6be63d9 100644 --- a/security/csrf.go +++ b/security/csrf.go @@ -3,7 +3,7 @@ package security import ( "crypto/rand" "encoding/hex" - "log" + "log/slog" "math" "net/http" ) @@ -13,8 +13,7 @@ func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) { buff := make([]byte, int(math.Ceil(float64(64)/2))) _, err := rand.Read(buff) if err != nil { - log.Println("Error creating random buffer for csrf token value") - log.Println(err) + slog.Error("Error creating random buffer for csrf token value" + err.Error()) return "", err } str := hex.EncodeToString(buff) @@ -38,8 +37,7 @@ func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) { func VerifyCsrfToken(r *http.Request) (bool, error) { cookie, err := r.Cookie("csrf_token") if err != nil { - log.Println("Error getting csrf_token cookie") - log.Println(err) + slog.Info("Unable to get csrf_token cookie" + err.Error()) return false, err } diff --git a/templating/templateHelper.go b/templating/templateHelper.go index ee00b37..dd8695f 100644 --- a/templating/templateHelper.go +++ b/templating/templateHelper.go @@ -3,7 +3,7 @@ package templating import ( "GoWeb/app" "html/template" - "log" + "log/slog" "net/http" ) @@ -13,35 +13,35 @@ func RenderTemplate(app *app.App, w http.ResponseWriter, contentPath string, dat templateContent, err := app.Res.ReadFile(templatePath) if err != nil { - log.Println(err) + slog.Error(err.Error()) http.Error(w, err.Error(), 500) return } t, err := template.New(templatePath).Parse(string(templateContent)) if err != nil { - log.Println(err) + slog.Error(err.Error()) http.Error(w, err.Error(), 500) return } content, err := app.Res.ReadFile(contentPath) if err != nil { - log.Println(err) + slog.Error(err.Error()) http.Error(w, err.Error(), 500) return } t, err = t.Parse(string(content)) if err != nil { - log.Println(err) + slog.Error(err.Error()) http.Error(w, err.Error(), 500) return } err = t.Execute(w, data) if err != nil { - log.Println(err) + slog.Error(err.Error()) http.Error(w, err.Error(), 500) return }