Files
website/models/user.go
H3ALY e5bf12ad77 Feature: Full notification read view with conditional mark-as-read logic
- Added dedicated route and view for reading individual notifications (/account/notifications/read)
- Ensured notification is only marked as read if it hasn't already been
- Updated Notification model to use Subject and Body fields
- Fixed field references in templates (Title → Subject, Message → Body)
- Updated topbar dropdown to use correct field names and display logic
- Gracefully handle "notification not found" cases in template output
- Ensured consistent template parsing with layout and topbar inclusion
- Improved error logging for better diagnosis
2025-04-01 23:08:58 +01:00

92 lines
1.6 KiB
Go

package models
import (
"database/sql"
"log"
"time"
)
type User struct {
Id int
Username string
PasswordHash string
IsAdmin bool
}
type Notification struct {
ID int
UserId int
Subject string
Body string
IsRead bool
CreatedAt time.Time
}
type Message struct {
ID int
Sender string
Subject string
Message string
IsRead bool
CreatedAt time.Time
}
var db *sql.DB
func SetDB(database *sql.DB) {
db = database
}
func CreateUser(username, passwordHash string) error {
_, err := db.Exec("INSERT INTO users (username, password_hash) VALUES (?, ?)", username, passwordHash)
return err
}
func GetUserByUsername(username string) *User {
row := db.QueryRow("SELECT id, username, password_hash FROM users WHERE username = ?", username)
var user User
err := row.Scan(&user.Id, &user.Username, &user.PasswordHash)
if err != nil {
if err != sql.ErrNoRows {
log.Println("DB error:", err)
}
return nil
}
return &user
}
func GetUserByID(id int) *User {
row := db.QueryRow("SELECT id, username, password_hash, is_admin FROM users WHERE id = ?", id)
var user User
err := row.Scan(&user.Id, &user.Username, &user.PasswordHash, &user.IsAdmin)
if err != nil {
if err != sql.ErrNoRows {
log.Println("DB error:", err)
}
return nil
}
return &user
}
func LogLoginAttempt(username string, success bool) {
_, err := db.Exec("INSERT INTO auditlog (username, success, timestamp) VALUES (?, ?, ?)",
username, boolToInt(success), time.Now().Format(time.RFC3339))
if err != nil {
log.Println("❌ Failed to log login:", err)
}
}
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}