HEAVY: migrate accounts and logs to service/repo architecture

This commit is contained in:
ari melody 2026-07-31 02:43:45 +01:00
parent 5c255fb34b
commit 49e14b5bc5
Signed by: ari
GPG key ID: CF99829C92678188
37 changed files with 1019 additions and 687 deletions

View file

@ -2,7 +2,6 @@ package admin
import (
"context"
"database/sql"
"fmt"
"net/http"
"os"
@ -11,8 +10,8 @@ import (
"arimelody-web/admin/templates"
"arimelody-web/controller"
"arimelody-web/log"
"arimelody-web/model"
"arimelody-web/model/app"
"arimelody-web/view"
"golang.org/x/crypto/bcrypt"
@ -23,7 +22,7 @@ type adminPageData struct {
Session *model.Session
}
func Handler(app *model.AppState) http.Handler {
func Handler(app *app.AppState) http.Handler {
mux := http.NewServeMux()
mux.Handle("/qr-test", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -75,7 +74,7 @@ func Handler(app *model.AppState) http.Handler {
return enforceSession(app, mux)
}
func AdminIndexHandler(app *model.AppState) http.Handler {
func AdminIndexHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
@ -150,7 +149,7 @@ func AdminIndexHandler(app *model.AppState) http.Handler {
})
}
func registerAccountHandler(app *model.AppState) http.Handler {
func registerAccountHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -223,13 +222,13 @@ func registerAccountHandler(app *model.AppState) http.Handler {
return
}
account := model.Account{
Username: credentials.Username,
Password: string(hashedPassword),
Email: sql.NullString{ String: credentials.Email, Valid: true },
AvatarURL: sql.NullString{ String: "/img/default-avatar.png", Valid: true },
}
err = controller.CreateAccount(app.DB, &account)
defaultAvatar := "/img/default-avatar.png"
accountID, err := app.AccountService.Create(
credentials.Username,
string(hashedPassword),
&credentials.Email,
&defaultAvatar,
)
if err != nil {
if strings.HasPrefix(err.Error(), "pq: duplicate key") {
controller.SetSessionError(app.DB, session, "An account with that username already exists.")
@ -242,22 +241,36 @@ func registerAccountHandler(app *model.AppState) http.Handler {
return
}
app.Log.Info(log.TYPE_ACCOUNT, "Account \"%s\" (%s) created using invite \"%s\". (%s)", account.Username, account.ID, invite.Code, controller.ResolveIP(app, r))
app.Log.Info(
model.LOG_ACCOUNT,
"Account \"%s\" (%s) created using invite \"%s\". (%s)",
credentials.Username,
accountID,
invite.Code,
controller.ResolveIP(app, r),
)
err = controller.DeleteInvite(app.DB, invite.Code)
if err != nil {
app.Log.Warn(log.TYPE_ACCOUNT, "Failed to delete expired invite \"%s\": %v", invite.Code, err)
app.Log.Warn(model.LOG_ACCOUNT, "Failed to delete expired invite \"%s\": %v", invite.Code, err)
}
// registration success!
controller.SetSessionAccount(app.DB, session, &account)
if account, err := app.AccountService.GetByID(accountID); err != nil || account == nil {
controller.SetSessionError(
app.DB, session,
"Account created, but something went wrong logging you in. Please try logging in manually.",
)
} else {
controller.SetSessionAccount(app.DB, session, account)
}
controller.SetSessionMessage(app.DB, session, "")
controller.SetSessionError(app.DB, session, "")
http.Redirect(w, r, "/admin", http.StatusFound)
})
}
func loginHandler(app *model.AppState) http.Handler {
func loginHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodPost {
http.NotFound(w, r)
@ -299,7 +312,7 @@ func loginHandler(app *model.AppState) http.Handler {
username := r.FormValue("username")
password := r.FormValue("password")
account, err := controller.GetAccountByUsername(app.DB, username)
account, err := app.AccountService.GetByUsername(username)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to fetch account for login: %v\n", err)
controller.SetSessionError(app.DB, session, "Invalid username or password.")
@ -319,7 +332,7 @@ func loginHandler(app *model.AppState) http.Handler {
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password))
if err != nil {
app.Log.Warn(log.TYPE_ACCOUNT, "\"%s\" attempted login with incorrect password. (%s)", account.Username, controller.ResolveIP(app, r))
app.Log.Warn(model.LOG_ACCOUNT, "\"%s\" attempted login with incorrect password. (%s)", account.Username, controller.ResolveIP(app, r))
if locked := handleFailedLogin(app, account, r); locked {
controller.SetSessionError(app.DB, session, "Too many failed attempts. This account is now locked.")
} else {
@ -353,8 +366,8 @@ func loginHandler(app *model.AppState) http.Handler {
// login success!
// TODO: log login activity to user
app.Log.Info(log.TYPE_ACCOUNT, "\"%s\" logged in. (%s)", account.Username, controller.ResolveIP(app, r))
app.Log.Warn(log.TYPE_ACCOUNT, "\"%s\" does not have any TOTP methods assigned.", account.Username)
app.Log.Info(model.LOG_ACCOUNT, "\"%s\" logged in. (%s)", account.Username, controller.ResolveIP(app, r))
app.Log.Warn(model.LOG_ACCOUNT, "\"%s\" does not have any TOTP methods assigned.", account.Username)
err = controller.SetSessionAccount(app.DB, session, account)
if err != nil {
@ -369,7 +382,7 @@ func loginHandler(app *model.AppState) http.Handler {
})
}
func loginTOTPHandler(app *model.AppState) http.Handler {
func loginTOTPHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -407,7 +420,7 @@ func loginTOTPHandler(app *model.AppState) http.Handler {
totpCode := r.FormValue("totp")
if len(totpCode) != controller.TOTP_CODE_LENGTH {
app.Log.Warn(log.TYPE_ACCOUNT, "\"%s\" failed login (Invalid TOTP). (%s)", session.AttemptAccount.Username, controller.ResolveIP(app, r))
app.Log.Warn(model.LOG_ACCOUNT, "\"%s\" failed login (Invalid TOTP). (%s)", session.AttemptAccount.Username, controller.ResolveIP(app, r))
controller.SetSessionError(app.DB, session, "Invalid TOTP.")
render()
return
@ -421,7 +434,7 @@ func loginTOTPHandler(app *model.AppState) http.Handler {
return
}
if totpMethod == nil {
app.Log.Warn(log.TYPE_ACCOUNT, "\"%s\" failed login (Incorrect TOTP). (%s)", session.AttemptAccount.Username, controller.ResolveIP(app, r))
app.Log.Warn(model.LOG_ACCOUNT, "\"%s\" failed login (Incorrect TOTP). (%s)", session.AttemptAccount.Username, controller.ResolveIP(app, r))
if locked := handleFailedLogin(app, session.AttemptAccount, r); locked {
controller.SetSessionError(app.DB, session, "Too many failed attempts. This account is now locked.")
controller.SetSessionAttemptAccount(app.DB, session, nil)
@ -433,7 +446,7 @@ func loginTOTPHandler(app *model.AppState) http.Handler {
return
}
app.Log.Info(log.TYPE_ACCOUNT, "\"%s\" logged in with TOTP method \"%s\". (%s)", session.AttemptAccount.Username, totpMethod.Name, controller.ResolveIP(app, r))
app.Log.Info(model.LOG_ACCOUNT, "\"%s\" logged in with TOTP method \"%s\". (%s)", session.AttemptAccount.Username, totpMethod.Name, controller.ResolveIP(app, r))
err = controller.SetSessionAccount(app.DB, session, session.AttemptAccount)
if err != nil {
@ -452,7 +465,7 @@ func loginTOTPHandler(app *model.AppState) http.Handler {
})
}
func logoutHandler(app *model.AppState) http.Handler {
func logoutHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.NotFound(w, r)
@ -514,7 +527,7 @@ func staticHandler() http.Handler {
}
*/
func enforceSession(app *model.AppState, next http.Handler) http.Handler {
func enforceSession(app *app.AppState, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := controller.GetSessionFromRequest(app, r)
if err != nil {
@ -547,8 +560,45 @@ func enforceSession(app *model.AppState, next http.Handler) http.Handler {
})
}
func handleFailedLogin(app *model.AppState, account *model.Account, r *http.Request) bool {
locked, err := controller.IncrementAccountFails(app.DB, account.ID)
// Helper for handling login failures. Increments the account auth failure
// count and logs warnings. If failure count exceeds MAX_LOGIN_FAIL_ATTEMPTS,
// the account will be locked.
func handleFailedLogin(app *app.AppState, account *model.Account, r *http.Request) bool {
failAttempts, err := app.AccountService.IncrementFails(account.ID)
if failAttempts >= model.MAX_LOGIN_FAIL_ATTEMPTS {
err = app.AccountService.Lock(account.ID)
if err != nil {
fmt.Fprintf(
os.Stderr,
"WARN: Failed to lock account \"%s\": %v\n",
account.Username,
err,
)
app.Log.Warn(
model.LOG_ACCOUNT,
"Failed to lock account \"%s\"",
account.Username,
)
}
fmt.Fprintf(
os.Stderr,
"Account \"%s\" was locked: %d failed login attempts (IP: %s)",
account.Username,
model.MAX_LOGIN_FAIL_ATTEMPTS,
controller.ResolveIP(app, r),
)
app.Log.Warn(
model.LOG_ACCOUNT,
"Account \"%s\" was locked: %d failed login attempts (IP: %s)",
account.Username,
model.MAX_LOGIN_FAIL_ATTEMPTS,
controller.ResolveIP(app, r),
)
return true
}
if err != nil {
fmt.Fprintf(
os.Stderr,
@ -557,19 +607,11 @@ func handleFailedLogin(app *model.AppState, account *model.Account, r *http.Requ
err,
)
app.Log.Warn(
log.TYPE_ACCOUNT,
model.LOG_ACCOUNT,
"Failed to increment login failures for \"%s\"",
account.Username,
)
}
if locked {
app.Log.Warn(
log.TYPE_ACCOUNT,
"Account \"%s\" was locked: %d failed login attempts (IP: %s)",
account.Username,
model.MAX_LOGIN_FAIL_ATTEMPTS,
controller.ResolveIP(app, r),
)
}
return locked
return false
}