Clean up error handling, migrate to log/slog, add todo for flash message system in post controller
This commit is contained in:
parent
ee4c9f9199
commit
ed712a5344
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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")
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user