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

@ -9,13 +9,13 @@ import (
"arimelody-web/admin/templates"
"arimelody-web/controller"
"arimelody-web/log"
"arimelody-web/model"
"arimelody-web/model/app"
"golang.org/x/crypto/bcrypt"
)
func accountHandler(app *model.AppState) http.Handler {
func accountHandler(app *app.AppState) http.Handler {
mux := http.NewServeMux()
mux.Handle("/account/totp-setup", totpSetupHandler(app))
@ -28,7 +28,7 @@ func accountHandler(app *model.AppState) http.Handler {
return mux
}
func accountIndexHandler(app *model.AppState) http.Handler {
func accountIndexHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -76,7 +76,7 @@ func accountIndexHandler(app *model.AppState) http.Handler {
})
}
func changePasswordHandler(app *model.AppState) http.Handler {
func changePasswordHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.NotFound(w, r)
@ -107,8 +107,7 @@ func changePasswordHandler(app *model.AppState) http.Handler {
return
}
session.Account.Password = string(hashedPassword)
err = controller.UpdateAccount(app.DB, session.Account)
err = app.AccountService.ChangePassword(session.Account.ID, string(hashedPassword))
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to update account password: %v\n", err)
controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.")
@ -116,7 +115,7 @@ func changePasswordHandler(app *model.AppState) http.Handler {
return
}
app.Log.Info(log.TYPE_ACCOUNT, "\"%s\" changed password by user request. (%s)", session.Account.Username, controller.ResolveIP(app, r))
app.Log.Info(model.LOG_ACCOUNT, "\"%s\" changed password by user request. (%s)", session.Account.Username, controller.ResolveIP(app, r))
controller.SetSessionError(app.DB, session, "")
controller.SetSessionMessage(app.DB, session, "Password updated successfully.")
@ -124,7 +123,7 @@ func changePasswordHandler(app *model.AppState) http.Handler {
})
}
func deleteAccountHandler(app *model.AppState) http.Handler {
func deleteAccountHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.NotFound(w, r)
@ -146,13 +145,13 @@ func deleteAccountHandler(app *model.AppState) http.Handler {
// check password
if err := bcrypt.CompareHashAndPassword([]byte(session.Account.Password), []byte(r.Form.Get("password"))); err != nil {
app.Log.Warn(log.TYPE_ACCOUNT, "Account \"%s\" attempted account deletion with incorrect password. (%s)", session.Account.Username, controller.ResolveIP(app, r))
app.Log.Warn(model.LOG_ACCOUNT, "Account \"%s\" attempted account deletion with incorrect password. (%s)", session.Account.Username, controller.ResolveIP(app, r))
controller.SetSessionError(app.DB, session, "Incorrect password.")
http.Redirect(w, r, "/admin/account", http.StatusFound)
return
}
err = controller.DeleteAccount(app.DB, session.Account.ID)
err = app.AccountService.Delete(session.Account.ID)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to delete account: %v\n", err)
controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.")
@ -160,7 +159,7 @@ func deleteAccountHandler(app *model.AppState) http.Handler {
return
}
app.Log.Info(log.TYPE_ACCOUNT, "Account \"%s\" deleted by user request. (%s)", session.Account.Username, controller.ResolveIP(app, r))
app.Log.Info(model.LOG_ACCOUNT, "Account \"%s\" deleted by user request. (%s)", session.Account.Username, controller.ResolveIP(app, r))
controller.SetSessionAccount(app.DB, session, nil)
controller.SetSessionError(app.DB, session, "")
@ -176,7 +175,7 @@ type totpConfirmData struct {
QRBase64Image string
}
func totpSetupHandler(app *model.AppState) http.Handler {
func totpSetupHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
session := r.Context().Value("session").(*model.Session)
@ -247,7 +246,7 @@ func totpSetupHandler(app *model.AppState) http.Handler {
})
}
func totpConfirmHandler(app *model.AppState) http.Handler {
func totpConfirmHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.NotFound(w, r)
@ -311,7 +310,7 @@ func totpConfirmHandler(app *model.AppState) http.Handler {
return
}
app.Log.Info(log.TYPE_ACCOUNT, "\"%s\" created TOTP method \"%s\".", session.Account.Username, totp.Name)
app.Log.Info(model.LOG_ACCOUNT, "\"%s\" created TOTP method \"%s\".", session.Account.Username, totp.Name)
controller.SetSessionError(app.DB, session, "")
controller.SetSessionMessage(app.DB, session, fmt.Sprintf("TOTP method \"%s\" created successfully.", totp.Name))
@ -319,7 +318,7 @@ func totpConfirmHandler(app *model.AppState) http.Handler {
})
}
func totpDeleteHandler(app *model.AppState) http.Handler {
func totpDeleteHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.NotFound(w, r)
@ -359,7 +358,7 @@ func totpDeleteHandler(app *model.AppState) http.Handler {
return
}
app.Log.Info(log.TYPE_ACCOUNT, "\"%s\" deleted TOTP method \"%s\".", session.Account.Username, totp.Name)
app.Log.Info(model.LOG_ACCOUNT, "\"%s\" deleted TOTP method \"%s\".", session.Account.Username, totp.Name)
controller.SetSessionError(app.DB, session, "")
controller.SetSessionMessage(app.DB, session, fmt.Sprintf("TOTP method \"%s\" deleted successfully.", totp.Name))

View file

@ -8,9 +8,10 @@ import (
"arimelody-web/admin/templates"
"arimelody-web/controller"
"arimelody-web/model"
"arimelody-web/model/app"
)
func serveArtists(app *model.AppState) http.Handler {
func serveArtists(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -45,7 +46,7 @@ func serveArtists(app *model.AppState) http.Handler {
})
}
func serveArtist(app *model.AppState, artistID string) http.Handler {
func serveArtist(app *app.AppState, artistID string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)

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
}

View file

@ -2,15 +2,15 @@ package admin
import (
"arimelody-web/admin/templates"
"arimelody-web/log"
"arimelody-web/model"
"arimelody-web/model/app"
"fmt"
"net/http"
"os"
"strings"
)
func logsHandler(app *model.AppState) http.Handler {
func logsHandler(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.NotFound(w, r)
@ -19,16 +19,16 @@ func logsHandler(app *model.AppState) http.Handler {
session := r.Context().Value("session").(*model.Session)
levelFilter := []log.LogLevel{}
levelFilter := []model.LogLevel{}
typeFilter := []string{}
query := r.URL.Query().Get("q")
for key, value := range r.URL.Query() {
if strings.HasPrefix(key, "level-") && value[0] == "on" {
m := map[string]log.LogLevel{
"info": log.LEVEL_INFO,
"warn": log.LEVEL_WARN,
m := map[string]model.LogLevel{
"info": model.LEVEL_INFO,
"warn": model.LEVEL_WARN,
}
level, ok := m[strings.TrimPrefix(key, "level-")]
if ok {
@ -52,7 +52,7 @@ func logsHandler(app *model.AppState) http.Handler {
type LogsResponse struct {
adminPageData
Logs []*log.Log
Logs []*model.Log
}
err = templates.LogsTemplate.Execute(w, LogsResponse{

View file

@ -9,9 +9,10 @@ import (
"arimelody-web/admin/templates"
"arimelody-web/controller"
"arimelody-web/model"
"arimelody-web/model/app"
)
func serveReleases(app *model.AppState) http.Handler {
func serveReleases(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -55,7 +56,7 @@ func serveReleases(app *model.AppState) http.Handler {
})
}
func serveRelease(app *model.AppState, releaseID string, action string) http.Handler {
func serveRelease(app *app.AppState, releaseID string, action string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -127,7 +128,7 @@ func serveEditCredits(release *model.Release) http.Handler {
})
}
func serveAddCredit(app *model.AppState, release *model.Release) http.Handler {
func serveAddCredit(app *app.AppState, release *model.Release) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
artists, err := controller.GetArtistsNotOnRelease(app.DB, release.ID)
if err != nil {
@ -153,7 +154,7 @@ func serveAddCredit(app *model.AppState, release *model.Release) http.Handler {
})
}
func serveNewCredit(app *model.AppState) http.Handler {
func serveNewCredit(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
split := strings.Split(r.URL.Path, "/")
artistID := split[len(split) - 1]
@ -204,7 +205,7 @@ func serveEditTracks(release *model.Release) http.Handler {
})
}
func serveAddTrack(app *model.AppState, release *model.Release) http.Handler {
func serveAddTrack(app *app.AppState, release *model.Release) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tracks, err := controller.GetTracksNotOnRelease(app.DB, release.ID)
if err != nil {
@ -230,7 +231,7 @@ func serveAddTrack(app *model.AppState, release *model.Release) http.Handler {
})
}
func serveNewTrack(app *model.AppState) http.Handler {
func serveNewTrack(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
split := strings.Split(r.URL.Path, "/")
trackID := split[len(split) - 1]

View file

@ -1,7 +1,7 @@
package templates
import (
"arimelody-web/log"
"arimelody-web/model"
_ "embed"
"fmt"
"html/template"
@ -163,11 +163,11 @@ var NewTrackTemplate = template.Must(template.Must(BaseTemplate.Clone()).Parse(c
func parseLevel(level log.LogLevel) string {
func parseLevel(level model.LogLevel) string {
switch level {
case log.LEVEL_INFO:
case model.LEVEL_INFO:
return "INFO"
case log.LEVEL_WARN:
case model.LEVEL_WARN:
return "WARN"
}
return fmt.Sprintf("%d?", level)

View file

@ -8,9 +8,10 @@ import (
"arimelody-web/admin/templates"
"arimelody-web/controller"
"arimelody-web/model"
"arimelody-web/model/app"
)
func serveTracks(app *model.AppState) http.Handler {
func serveTracks(app *app.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
@ -45,7 +46,7 @@ func serveTracks(app *model.AppState) http.Handler {
})
}
func serveTrack(app *model.AppState, trackID string) http.Handler {
func serveTrack(app *app.AppState, trackID string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)