From e457e979ff042ca8871ae21404f1c3e5c384e08c Mon Sep 17 00:00:00 2001 From: ari melody Date: Thu, 23 Jan 2025 09:39:40 +0000 Subject: [PATCH 1/2] tidying some things up session message handling is pretty annoying; should look into a better method of doing this --- admin/accounthttp.go | 50 +++++++++++---- admin/http.go | 51 ++++++++------- admin/views/edit-account.html | 5 +- controller/account.go | 6 +- controller/session.go | 6 +- main.go | 83 ++++++++++++++++++------- schema_migration/000-init.sql | 20 +++--- schema_migration/001-pre-versioning.sql | 22 +++---- 8 files changed, 161 insertions(+), 82 deletions(-) diff --git a/admin/accounthttp.go b/admin/accounthttp.go index fc701e7..fc4fed1 100644 --- a/admin/accounthttp.go +++ b/admin/accounthttp.go @@ -17,7 +17,6 @@ func accountHandler(app *model.AppState) http.Handler { mux.Handle("/password", changePasswordHandler(app)) mux.Handle("/delete", deleteAccountHandler(app)) - mux.Handle("/", accountIndexHandler(app)) return mux } @@ -37,6 +36,13 @@ func accountIndexHandler(app *model.AppState) http.Handler { TOTPs []model.TOTP } + sessionMessage := session.Message + sessionError := session.Error + controller.SetSessionMessage(app.DB, session, "") + controller.SetSessionError(app.DB, session, "") + session.Message = sessionMessage + session.Error = sessionError + err = pages["account"].Execute(w, accountResponse{ Session: session, TOTPs: totps, @@ -57,18 +63,39 @@ func changePasswordHandler(app *model.AppState) http.Handler { session := r.Context().Value("session").(*model.Session) + controller.SetSessionMessage(app.DB, session, "") + controller.SetSessionError(app.DB, session, "") + r.ParseForm() currentPassword := r.Form.Get("current-password") if err := bcrypt.CompareHashAndPassword([]byte(session.Account.Password), []byte(currentPassword)); err != nil { - controller.SetSessionMessage(app.DB, session, "Incorrect password.") + controller.SetSessionError(app.DB, session, "Incorrect password.") http.Redirect(w, r, "/admin/account", http.StatusFound) return } newPassword := r.Form.Get("new-password") - controller.SetSessionMessage(app.DB, session, fmt.Sprintf("Updating password to %s", newPassword)) + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) + if err != nil { + fmt.Fprintf(os.Stderr, "WARN: Failed to generate password hash: %v\n", err) + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") + http.Redirect(w, r, "/admin/account", http.StatusFound) + return + } + + session.Account.Password = string(hashedPassword) + err = controller.UpdateAccount(app.DB, session.Account) + 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.") + http.Redirect(w, r, "/admin/account", http.StatusFound) + return + } + + controller.SetSessionError(app.DB, session, "") + controller.SetSessionMessage(app.DB, session, "Password updated successfully.") http.Redirect(w, r, "/admin/account", http.StatusFound) }) } @@ -97,10 +124,10 @@ func deleteAccountHandler(app *model.AppState) http.Handler { if err := bcrypt.CompareHashAndPassword([]byte(session.Account.Password), []byte(r.Form.Get("password"))); err != nil { fmt.Printf( "[%s] WARN: Account \"%s\" attempted account deletion with incorrect password.\n", - time.Now().Format("2006-02-01 15:04:05"), + time.Now().Format(time.UnixDate), session.Account.Username, ) - controller.SetSessionMessage(app.DB, session, "Incorrect password.") + controller.SetSessionError(app.DB, session, "Incorrect password.") http.Redirect(w, r, "/admin/account", http.StatusFound) return } @@ -108,35 +135,36 @@ func deleteAccountHandler(app *model.AppState) http.Handler { totpMethod, err := controller.CheckTOTPForAccount(app.DB, session.Account.ID, r.Form.Get("totp")) if err != nil { fmt.Fprintf(os.Stderr, "Failed to fetch account: %v\n", err) - controller.SetSessionMessage(app.DB, session, "Something went wrong. Please try again.") + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") http.Redirect(w, r, "/admin/account", http.StatusFound) return } if totpMethod == nil { fmt.Printf( "[%s] WARN: Account \"%s\" attempted account deletion with incorrect TOTP.\n", - time.Now().Format("2006-02-01 15:04:05"), + time.Now().Format(time.UnixDate), session.Account.Username, ) - controller.SetSessionMessage(app.DB, session, "Incorrect TOTP.") + controller.SetSessionError(app.DB, session, "Incorrect TOTP.") http.Redirect(w, r, "/admin/account", http.StatusFound) } err = controller.DeleteAccount(app.DB, session.Account.ID) if err != nil { fmt.Fprintf(os.Stderr, "Failed to delete account: %v\n", err) - controller.SetSessionMessage(app.DB, session, "Something went wrong. Please try again.") + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") http.Redirect(w, r, "/admin/account", http.StatusFound) return } fmt.Printf( "[%s] INFO: Account \"%s\" deleted by user request.\n", - time.Now().Format("2006-02-01 15:04:05"), + time.Now().Format(time.UnixDate), session.Account.Username, ) - session.Account = nil + controller.SetSessionAccount(app.DB, session, nil) + controller.SetSessionError(app.DB, session, "") controller.SetSessionMessage(app.DB, session, "Account deleted successfully.") http.Redirect(w, r, "/admin/login", http.StatusFound) }) diff --git a/admin/http.go b/admin/http.go index ad0d44e..5fcce01 100644 --- a/admin/http.go +++ b/admin/http.go @@ -93,8 +93,8 @@ func AdminIndexHandler(app *model.AppState) http.Handler { func registerAccountHandler(app *model.AppState) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session := r.Context().Value("session").(*model.Session) - session.Error = sql.NullString{} - session.Message = sql.NullString{} + controller.SetSessionError(app.DB, session, "") + controller.SetSessionMessage(app.DB, session, "") if session.Account != nil { // user is already logged in @@ -102,8 +102,12 @@ func registerAccountHandler(app *model.AppState) http.Handler { return } + type registerData struct { + Session *model.Session + } + render := func() { - err := pages["register"].Execute(w, session) + err := pages["register"].Execute(w, registerData{ Session: session }) if err != nil { fmt.Printf("WARN: Error rendering create account page: %s\n", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) @@ -122,7 +126,7 @@ func registerAccountHandler(app *model.AppState) http.Handler { err := r.ParseForm() if err != nil { - session.Error = sql.NullString{ String: "Malformed data.", Valid: true } + controller.SetSessionError(app.DB, session, "Malformed data.") render() return } @@ -144,7 +148,7 @@ func registerAccountHandler(app *model.AppState) http.Handler { invite, err := controller.GetInvite(app.DB, credentials.Invite) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to retrieve invite: %v\n", err) - session.Error = sql.NullString{ String: "Something went wrong. Please try again.", Valid: true } + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") render() return } @@ -153,7 +157,7 @@ func registerAccountHandler(app *model.AppState) http.Handler { err := controller.DeleteInvite(app.DB, invite.Code) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to delete expired invite: %v\n", err) } } - session.Error = sql.NullString{ String: "Invalid invite code.", Valid: true } + controller.SetSessionError(app.DB, session, "Invalid invite code.") render() return } @@ -161,7 +165,7 @@ func registerAccountHandler(app *model.AppState) http.Handler { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(credentials.Password), bcrypt.DefaultCost) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to generate password hash: %v\n", err) - session.Error = sql.NullString{ String: "Something went wrong. Please try again.", Valid: true } + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") render() return } @@ -175,16 +179,23 @@ func registerAccountHandler(app *model.AppState) http.Handler { err = controller.CreateAccount(app.DB, &account) if err != nil { if strings.HasPrefix(err.Error(), "pq: duplicate key") { - session.Error = sql.NullString{ String: "An account with that username already exists.", Valid: true } + controller.SetSessionError(app.DB, session, "An account with that username already exists.") render() return } fmt.Fprintf(os.Stderr, "WARN: Failed to create account: %v\n", err) - session.Error = sql.NullString{ String: "Something went wrong. Please try again.", Valid: true } + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") render() return } + fmt.Printf( + "[%s]: Account registered: %s (%s)\n", + time.Now().Format(time.UnixDate), + account.Username, + account.ID, + ) + err = controller.DeleteInvite(app.DB, invite.Code) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to delete expired invite: %v\n", err) } @@ -229,7 +240,7 @@ func loginHandler(app *model.AppState) http.Handler { err := r.ParseForm() if err != nil { - session.Error = sql.NullString{ String: "Malformed data.", Valid: true } + controller.SetSessionError(app.DB, session, "Malformed data.") render() return } @@ -253,12 +264,12 @@ func loginHandler(app *model.AppState) http.Handler { account, err := controller.GetAccountByUsername(app.DB, credentials.Username) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to fetch account for login: %v\n", err) - session.Error = sql.NullString{ String: "Invalid username or password.", Valid: true } + controller.SetSessionError(app.DB, session, "Invalid username or password.") render() return } if account == nil { - session.Error = sql.NullString{ String: "Invalid username or password.", Valid: true } + controller.SetSessionError(app.DB, session, "Invalid username or password.") render() return } @@ -267,10 +278,10 @@ func loginHandler(app *model.AppState) http.Handler { if err != nil { fmt.Printf( "[%s] INFO: Account \"%s\" attempted login with incorrect password.\n", - time.Now().Format("2006-02-01 15:04:05"), + time.Now().Format(time.UnixDate), account.Username, ) - session.Error = sql.NullString{ String: "Invalid username or password.", Valid: true } + controller.SetSessionError(app.DB, session, "Invalid username or password.") render() return } @@ -278,12 +289,12 @@ func loginHandler(app *model.AppState) http.Handler { totpMethod, err := controller.CheckTOTPForAccount(app.DB, account.ID, credentials.TOTP) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to fetch TOTPs: %v\n", err) - session.Error = sql.NullString{ String: "Something went wrong. Please try again.", Valid: true } + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") render() return } if totpMethod == nil { - session.Error = sql.NullString{ String: "Invalid TOTP.", Valid: true } + controller.SetSessionError(app.DB, session, "Invalid TOTP.") render() return } @@ -291,7 +302,7 @@ func loginHandler(app *model.AppState) http.Handler { // TODO: log login activity to user fmt.Printf( "[%s] INFO: Account \"%s\" logged in with method \"%s\"\n", - time.Now().Format("2006-02-01 15:04:05"), + time.Now().Format(time.UnixDate), account.Username, totpMethod.Name, ) @@ -379,11 +390,7 @@ func enforceSession(app *model.AppState, next http.Handler) http.Handler { // fetch existing session session, err = controller.GetSession(app.DB, sessionCookie.Value) - if err != nil { - if strings.Contains(err.Error(), "no rows") { - http.Error(w, "Invalid session. Please try clearing your cookies and refresh.", http.StatusBadRequest) - return - } + if err != nil && !strings.Contains(err.Error(), "no rows") { fmt.Fprintf(os.Stderr, "WARN: Failed to retrieve session: %v\n", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return diff --git a/admin/views/edit-account.html b/admin/views/edit-account.html index 0acfaf5..18a6dca 100644 --- a/admin/views/edit-account.html +++ b/admin/views/edit-account.html @@ -52,7 +52,10 @@

You have no MFA devices.

{{end}} - +
+ + Add TOTP Device +
diff --git a/controller/account.go b/controller/account.go index 8272bad..0cf3364 100644 --- a/controller/account.go +++ b/controller/account.go @@ -108,7 +108,7 @@ func CreateAccount(db *sqlx.DB, account *model.Account) error { func UpdateAccount(db *sqlx.DB, account *model.Account) error { _, err := db.Exec( "UPDATE account " + - "SET username=$2, password=$3, email=$4, avatar_url=$5) " + + "SET username=$2,password=$3,email=$4,avatar_url=$5 " + "WHERE id=$1", account.ID, account.Username, @@ -120,7 +120,7 @@ func UpdateAccount(db *sqlx.DB, account *model.Account) error { return err } -func DeleteAccount(db *sqlx.DB, username string) error { - _, err := db.Exec("DELETE FROM account WHERE username=$1", username) +func DeleteAccount(db *sqlx.DB, accountID string) error { + _, err := db.Exec("DELETE FROM account WHERE id=$1", accountID) return err } diff --git a/controller/session.go b/controller/session.go index 2a2a19e..c9c4cbb 100644 --- a/controller/session.go +++ b/controller/session.go @@ -63,6 +63,7 @@ func SetSessionAccount(db *sqlx.DB, session *model.Session, account *model.Accou func SetSessionMessage(db *sqlx.DB, session *model.Session, message string) error { var err error if message == "" { + if !session.Message.Valid { return nil } session.Message = sql.NullString{ } _, err = db.Exec("UPDATE session SET message=NULL WHERE token=$1", session.Token) } else { @@ -75,10 +76,11 @@ func SetSessionMessage(db *sqlx.DB, session *model.Session, message string) erro func SetSessionError(db *sqlx.DB, session *model.Session, message string) error { var err error if message == "" { - session.Message = sql.NullString{ } + if !session.Error.Valid { return nil } + session.Error = sql.NullString{ } _, err = db.Exec("UPDATE session SET error=NULL WHERE token=$1", session.Token) } else { - session.Message = sql.NullString{ String: message, Valid: true } + session.Error = sql.NullString{ String: message, Valid: true } _, err = db.Exec("UPDATE session SET error=$2 WHERE token=$1", session.Token, message) } return err diff --git a/main.go b/main.go index 9c5b38a..251d9a9 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "log" + "math" "math/rand" "net/http" "os" @@ -22,6 +23,7 @@ import ( "github.com/jmoiron/sqlx" _ "github.com/lib/pq" + "golang.org/x/crypto/bcrypt" ) // used for database migrations @@ -91,12 +93,12 @@ func main() { account, err := controller.GetAccountByUsername(app.DB, username) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch account \"%s\": %v\n", username, err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch account \"%s\": %v\n", username, err) os.Exit(1) } if account == nil { - fmt.Fprintf(os.Stderr, "Account \"%s\" does not exist.\n", username) + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" does not exist.\n", username) os.Exit(1) } @@ -109,10 +111,10 @@ func main() { err = controller.CreateTOTP(app.DB, &totp) if err != nil { if strings.HasPrefix(err.Error(), "pq: duplicate key") { - fmt.Fprintf(os.Stderr, "Account \"%s\" already has a TOTP method named \"%s\"!\n", account.Username, totp.Name) + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" already has a TOTP method named \"%s\"!\n", account.Username, totp.Name) os.Exit(1) } - fmt.Fprintf(os.Stderr, "Failed to create TOTP method: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to create TOTP method: %v\n", err) os.Exit(1) } @@ -130,18 +132,18 @@ func main() { account, err := controller.GetAccountByUsername(app.DB, username) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch account \"%s\": %v\n", username, err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch account \"%s\": %v\n", username, err) os.Exit(1) } if account == nil { - fmt.Fprintf(os.Stderr, "Account \"%s\" does not exist.\n", username) + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" does not exist.\n", username) os.Exit(1) } err = controller.DeleteTOTP(app.DB, account.ID, totpName) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to create TOTP method: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to create TOTP method: %v\n", err) os.Exit(1) } @@ -157,18 +159,18 @@ func main() { account, err := controller.GetAccountByUsername(app.DB, username) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch account \"%s\": %v\n", username, err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch account \"%s\": %v\n", username, err) os.Exit(1) } if account == nil { - fmt.Fprintf(os.Stderr, "Account \"%s\" does not exist.\n", username) + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" does not exist.\n", username) os.Exit(1) } totps, err := controller.GetTOTPsForAccount(app.DB, account.ID) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to create TOTP methods: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to create TOTP methods: %v\n", err) os.Exit(1) } @@ -190,23 +192,23 @@ func main() { account, err := controller.GetAccountByUsername(app.DB, username) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch account \"%s\": %v\n", username, err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch account \"%s\": %v\n", username, err) os.Exit(1) } if account == nil { - fmt.Fprintf(os.Stderr, "Account \"%s\" does not exist.\n", username) + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" does not exist.\n", username) os.Exit(1) } totp, err := controller.GetTOTP(app.DB, account.ID, totpName) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch TOTP method \"%s\": %v\n", totpName, err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch TOTP method \"%s\": %v\n", totpName, err) os.Exit(1) } if totp == nil { - fmt.Fprintf(os.Stderr, "TOTP method \"%s\" does not exist for account \"%s\"\n", totpName, username) + fmt.Fprintf(os.Stderr, "FATAL: TOTP method \"%s\" does not exist for account \"%s\"\n", totpName, username) os.Exit(1) } @@ -218,18 +220,22 @@ func main() { fmt.Printf("Creating invite...\n") invite, err := controller.CreateInvite(app.DB, 16, time.Hour * 24) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to create invite code: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to create invite code: %v\n", err) os.Exit(1) } - fmt.Printf("Here you go! This code expires in 24 hours: %s\n", invite.Code) + fmt.Printf( + "Here you go! This code expires in %d hours: %s\n", + int(math.Ceil(invite.ExpiresAt.Sub(invite.CreatedAt).Hours())), + invite.Code, + ) return case "purgeInvites": fmt.Printf("Deleting all invites...\n") err := controller.DeleteAllInvites(app.DB) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to delete invites: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to delete invites: %v\n", err) os.Exit(1) } @@ -239,7 +245,7 @@ func main() { case "listAccounts": accounts, err := controller.GetAllAccounts(app.DB) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch accounts: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch accounts: %v\n", err) os.Exit(1) } @@ -259,6 +265,39 @@ func main() { } return + case "changePassword": + if len(os.Args) < 4 { + fmt.Fprintf(os.Stderr, "FATAL: `username` and `password` must be specified for changePassword\n") + os.Exit(1) + } + + username := os.Args[2] + password := os.Args[3] + account, err := controller.GetAccountByUsername(app.DB, username) + if err != nil { + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch account \"%s\": %v\n", username, err) + os.Exit(1) + } + if account == nil { + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" does not exist.\n", username) + os.Exit(1) + } + + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + fmt.Fprintf(os.Stderr, "FATAL: Failed to update password: %v\n", err) + os.Exit(1) + } + account.Password = string(hashedPassword) + err = controller.UpdateAccount(app.DB, account) + if err != nil { + fmt.Fprintf(os.Stderr, "FATAL: Failed to delete account: %v\n", err) + os.Exit(1) + } + + fmt.Printf("Account \"%s\" deleted successfully.\n", account.Username) + return + case "deleteAccount": if len(os.Args) < 3 { fmt.Fprintf(os.Stderr, "FATAL: `username` must be specified for deleteAccount\n") @@ -269,12 +308,12 @@ func main() { account, err := controller.GetAccountByUsername(app.DB, username) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fetch account \"%s\": %v\n", username, err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to fetch account \"%s\": %v\n", username, err) os.Exit(1) } if account == nil { - fmt.Fprintf(os.Stderr, "Account \"%s\" does not exist.\n", username) + fmt.Fprintf(os.Stderr, "FATAL: Account \"%s\" does not exist.\n", username) os.Exit(1) } @@ -285,9 +324,9 @@ func main() { return } - err = controller.DeleteAccount(app.DB, username) + err = controller.DeleteAccount(app.DB, account.ID) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to delete account: %v\n", err) + fmt.Fprintf(os.Stderr, "FATAL: Failed to delete account: %v\n", err) os.Exit(1) } diff --git a/schema_migration/000-init.sql b/schema_migration/000-init.sql index 48b8fbe..ff5c1af 100644 --- a/schema_migration/000-init.sql +++ b/schema_migration/000-init.sql @@ -4,19 +4,19 @@ -- Accounts CREATE TABLE arimelody.account ( - id uuid DEFAULT gen_random_uuid(), - username text NOT NULL UNIQUE, - password text NOT NULL, - email text, - avatar_url text, + id UUID DEFAULT gen_random_uuid(), + username TEXT NOT NULL UNIQUE, + password TEXT NOT NULL, + email TEXT, + avatar_url TEXT, created_at TIMESTAMP DEFAULT current_timestamp ); ALTER TABLE arimelody.account ADD CONSTRAINT account_pk PRIMARY KEY (id); -- Privilege CREATE TABLE arimelody.privilege ( - account uuid NOT NULL, - privilege text NOT NULL + account UUID NOT NULL, + privilege TEXT NOT NULL ); ALTER TABLE arimelody.privilege ADD CONSTRAINT privilege_pk PRIMARY KEY (account, privilege); @@ -33,12 +33,12 @@ CREATE TABLE arimelody.session ( token TEXT, user_agent TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT current_timestamp, - expires_at TIMESTAMP DEFAULT NULL + expires_at TIMESTAMP DEFAULT NULL, account UUID, message TEXT, - error TEXT, + error TEXT ); -ALTER TABLE arimelody.session ADD CONSTRAINT session_pk PRIMARY KEY (session); +ALTER TABLE arimelody.session ADD CONSTRAINT session_pk PRIMARY KEY (token); -- TOTPs CREATE TABLE arimelody.totp ( diff --git a/schema_migration/001-pre-versioning.sql b/schema_migration/001-pre-versioning.sql index 76fb1b8..cd0c061 100644 --- a/schema_migration/001-pre-versioning.sql +++ b/schema_migration/001-pre-versioning.sql @@ -2,21 +2,21 @@ -- New items -- --- Acounts +-- Accounts CREATE TABLE arimelody.account ( - id uuid DEFAULT gen_random_uuid(), - username text NOT NULL UNIQUE, - password text NOT NULL, - email text, - avatar_url text, + id UUID DEFAULT gen_random_uuid(), + username TEXT NOT NULL UNIQUE, + password TEXT NOT NULL, + email TEXT, + avatar_url TEXT, created_at TIMESTAMP DEFAULT current_timestamp ); ALTER TABLE arimelody.account ADD CONSTRAINT account_pk PRIMARY KEY (id); -- Privilege CREATE TABLE arimelody.privilege ( - account uuid NOT NULL, - privilege text NOT NULL + account UUID NOT NULL, + privilege TEXT NOT NULL ); ALTER TABLE arimelody.privilege ADD CONSTRAINT privilege_pk PRIMARY KEY (account, privilege); @@ -33,12 +33,12 @@ CREATE TABLE arimelody.session ( token TEXT, user_agent TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT current_timestamp, - expires_at TIMESTAMP DEFAULT NULL + expires_at TIMESTAMP DEFAULT NULL, account UUID, message TEXT, - error TEXT, + error TEXT ); -ALTER TABLE arimelody.session ADD CONSTRAINT session_pk PRIMARY KEY (session); +ALTER TABLE arimelody.session ADD CONSTRAINT session_pk PRIMARY KEY (token); -- TOTPs CREATE TABLE arimelody.totp ( From 50cbce92fcde5ada0eae1e0fa8b2072737ffdc5d Mon Sep 17 00:00:00 2001 From: ari melody Date: Thu, 23 Jan 2025 12:09:33 +0000 Subject: [PATCH 2/2] TOTP methods can now be created on the frontend! --- admin/accounthttp.go | 180 ++++++++++++++++++++++++++++++++++ admin/http.go | 12 +-- admin/static/admin.css | 29 +++++- admin/static/edit-account.css | 4 - admin/templates.go | 10 ++ admin/views/edit-account.html | 2 +- admin/views/login.html | 20 +--- admin/views/register.html | 18 +--- admin/views/totp-confirm.html | 34 +++++++ admin/views/totp-setup.html | 20 ++++ controller/totp.go | 22 +++-- 11 files changed, 295 insertions(+), 56 deletions(-) create mode 100644 admin/views/totp-confirm.html create mode 100644 admin/views/totp-setup.html diff --git a/admin/accounthttp.go b/admin/accounthttp.go index fc4fed1..b5deca2 100644 --- a/admin/accounthttp.go +++ b/admin/accounthttp.go @@ -3,6 +3,7 @@ package admin import ( "fmt" "net/http" + "net/url" "os" "time" @@ -15,6 +16,10 @@ import ( func accountHandler(app *model.AppState) http.Handler { mux := http.NewServeMux() + mux.Handle("/totp-setup", totpSetupHandler(app)) + mux.Handle("/totp-confirm", totpConfirmHandler(app)) + mux.Handle("/totp-delete/", http.StripPrefix("/totp-delete", totpDeleteHandler(app))) + mux.Handle("/password", changePasswordHandler(app)) mux.Handle("/delete", deleteAccountHandler(app)) @@ -169,3 +174,178 @@ func deleteAccountHandler(app *model.AppState) http.Handler { http.Redirect(w, r, "/admin/login", http.StatusFound) }) } + +func totpSetupHandler(app *model.AppState) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + type totpSetupData struct { + Session *model.Session + } + + session := r.Context().Value("session").(*model.Session) + + err := pages["totp-setup"].Execute(w, totpSetupData{ Session: session }) + if err != nil { + fmt.Printf("WARN: Failed to render TOTP setup page: %s\n", err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + return + } + + if r.Method != http.MethodPost { + http.NotFound(w, r) + return + } + + type totpSetupData struct { + Session *model.Session + TOTP *model.TOTP + NameEscaped string + } + + err := r.ParseForm() + if err != nil { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + + name := r.FormValue("totp-name") + if len(name) == 0 { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + + session := r.Context().Value("session").(*model.Session) + + secret := controller.GenerateTOTPSecret(controller.TOTP_SECRET_LENGTH) + totp := model.TOTP { + AccountID: session.Account.ID, + Name: name, + Secret: string(secret), + } + err = controller.CreateTOTP(app.DB, &totp) + if err != nil { + fmt.Printf("WARN: Failed to create TOTP method: %s\n", err) + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") + err := pages["totp-setup"].Execute(w, totpSetupData{ Session: session }) + if err != nil { + fmt.Printf("WARN: Failed to render TOTP setup page: %s\n", err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + return + } + + err = pages["totp-confirm"].Execute(w, totpSetupData{ + Session: session, + TOTP: &totp, + NameEscaped: url.PathEscape(totp.Name), + }) + if err != nil { + fmt.Printf("WARN: Failed to render TOTP confirm page: %s\n", err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + }) +} + +func totpConfirmHandler(app *model.AppState) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.NotFound(w, r) + return + } + + type totpConfirmData struct { + Session *model.Session + TOTP *model.TOTP + } + + session := r.Context().Value("session").(*model.Session) + + err := r.ParseForm() + if err != nil { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + name := r.FormValue("totp-name") + if len(name) == 0 { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + code := r.FormValue("totp") + if len(code) != controller.TOTP_CODE_LENGTH { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + + totp, err := controller.GetTOTP(app.DB, session.Account.ID, name) + if err != nil { + fmt.Printf("WARN: Failed to fetch TOTP method: %s\n", err) + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") + http.Redirect(w, r, "/admin/account", http.StatusFound) + return + } + if totp == nil { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + + confirmCode := controller.GenerateTOTP(totp.Secret, 0) + if code != confirmCode { + confirmCodeOffset := controller.GenerateTOTP(totp.Secret, 1) + if code != confirmCodeOffset { + controller.SetSessionError(app.DB, session, "Incorrect TOTP code. Please try again.") + err = pages["totp-confirm"].Execute(w, totpConfirmData{ + Session: session, + TOTP: totp, + }) + return + } + } + + controller.SetSessionError(app.DB, session, "") + controller.SetSessionMessage(app.DB, session, fmt.Sprintf("TOTP method \"%s\" created successfully.", totp.Name)) + http.Redirect(w, r, "/admin/account", http.StatusFound) + }) +} + +func totpDeleteHandler(app *model.AppState) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.NotFound(w, r) + return + } + + name := r.URL.Path + fmt.Printf("%s\n", name); + if len(name) == 0 { + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + return + } + + session := r.Context().Value("session").(*model.Session) + + totp, err := controller.GetTOTP(app.DB, session.Account.ID, name) + if err != nil { + fmt.Printf("WARN: Failed to fetch TOTP method: %s\n", err) + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") + http.Redirect(w, r, "/admin/account", http.StatusFound) + return + } + if totp == nil { + http.NotFound(w, r) + return + } + + err = controller.DeleteTOTP(app.DB, session.Account.ID, totp.Name) + if err != nil { + fmt.Printf("WARN: Failed to delete TOTP method: %s\n", err) + controller.SetSessionError(app.DB, session, "Something went wrong. Please try again.") + http.Redirect(w, r, "/admin/account", http.StatusFound) + return + } + + controller.SetSessionError(app.DB, session, "") + controller.SetSessionMessage(app.DB, session, fmt.Sprintf("TOTP method \"%s\" deleted successfully.", totp.Name)) + http.Redirect(w, r, "/admin/account", http.StatusFound) + }) +} diff --git a/admin/http.go b/admin/http.go index 5fcce01..7dd5207 100644 --- a/admin/http.go +++ b/admin/http.go @@ -93,8 +93,6 @@ func AdminIndexHandler(app *model.AppState) http.Handler { func registerAccountHandler(app *model.AppState) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session := r.Context().Value("session").(*model.Session) - controller.SetSessionError(app.DB, session, "") - controller.SetSessionMessage(app.DB, session, "") if session.Account != nil { // user is already logged in @@ -126,8 +124,7 @@ func registerAccountHandler(app *model.AppState) http.Handler { err := r.ParseForm() if err != nil { - controller.SetSessionError(app.DB, session, "Malformed data.") - render() + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } @@ -201,6 +198,8 @@ func registerAccountHandler(app *model.AppState) http.Handler { // registration success! controller.SetSessionAccount(app.DB, session, &account) + controller.SetSessionMessage(app.DB, session, "") + controller.SetSessionError(app.DB, session, "") http.Redirect(w, r, "/admin", http.StatusFound) }) } @@ -240,8 +239,7 @@ func loginHandler(app *model.AppState) http.Handler { err := r.ParseForm() if err != nil { - controller.SetSessionError(app.DB, session, "Malformed data.") - render() + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } @@ -309,6 +307,8 @@ func loginHandler(app *model.AppState) http.Handler { // login success! controller.SetSessionAccount(app.DB, session, account) + controller.SetSessionMessage(app.DB, session, "") + controller.SetSessionError(app.DB, session, "") http.Redirect(w, r, "/admin", http.StatusFound) }) } diff --git a/admin/static/admin.css b/admin/static/admin.css index 45d67a4..cbb827e 100644 --- a/admin/static/admin.css +++ b/admin/static/admin.css @@ -146,7 +146,7 @@ a img.icon { -a.delete { +a.delete:not(.button) { color: #d22828; } @@ -197,3 +197,30 @@ button:active, .button:active { opacity: .5; cursor: not-allowed !important; } + + + +form { + width: 100%; + display: block; +} +label { + width: 100%; + margin: 1rem 0 .5rem 0; + display: block; + color: #10101080; +} +input { + margin: .5rem 0; + padding: .3rem .5rem; + display: block; + border-radius: 4px; + border: 1px solid #808080; + font-size: inherit; + font-family: inherit; + color: inherit; +} +input[disabled] { + opacity: .5; + cursor: not-allowed; +} diff --git a/admin/static/edit-account.css b/admin/static/edit-account.css index 52fb756..37351b2 100644 --- a/admin/static/edit-account.css +++ b/admin/static/edit-account.css @@ -4,10 +4,6 @@ div.card { margin-bottom: 2rem; } -form button { - margin-top: 1rem; -} - label { width: 100%; margin: 1rem 0 .5rem 0; diff --git a/admin/templates.go b/admin/templates.go index 1021832..3bae106 100644 --- a/admin/templates.go +++ b/admin/templates.go @@ -33,6 +33,16 @@ var pages = map[string]*template.Template{ filepath.Join("views", "prideflag.html"), filepath.Join("admin", "views", "edit-account.html"), )), + "totp-setup": template.Must(template.ParseFiles( + filepath.Join("admin", "views", "layout.html"), + filepath.Join("views", "prideflag.html"), + filepath.Join("admin", "views", "totp-setup.html"), + )), + "totp-confirm": template.Must(template.ParseFiles( + filepath.Join("admin", "views", "layout.html"), + filepath.Join("views", "prideflag.html"), + filepath.Join("admin", "views", "totp-confirm.html"), + )), "release": template.Must(template.ParseFiles( filepath.Join("admin", "views", "layout.html"), diff --git a/admin/views/edit-account.html b/admin/views/edit-account.html index 18a6dca..b1d083a 100644 --- a/admin/views/edit-account.html +++ b/admin/views/edit-account.html @@ -44,7 +44,7 @@

Added: {{.CreatedAt}}

- Delete + Delete
{{end}} diff --git a/admin/views/login.html b/admin/views/login.html index e8581e8..b77af83 100644 --- a/admin/views/login.html +++ b/admin/views/login.html @@ -11,7 +11,7 @@ a.discord { color: #5865F2; } -form { +form#login { width: 100%; display: flex; flex-direction: column; @@ -26,26 +26,8 @@ form button { margin-top: 1rem; } -label { - width: 100%; - margin: 1rem 0 .5rem 0; - display: block; - color: #10101080; -} input { width: 100%; - margin: .5rem 0; - padding: .3rem .5rem; - display: block; - border-radius: 4px; - border: 1px solid #808080; - font-size: inherit; - font-family: inherit; - color: inherit; -} -input[disabled] { - opacity: .5; - cursor: not-allowed; } {{end}} diff --git a/admin/views/register.html b/admin/views/register.html index 8899fd9..94170c9 100644 --- a/admin/views/register.html +++ b/admin/views/register.html @@ -11,7 +11,7 @@ a.discord { color: #5865F2; } -form { +form#register { width: 100%; display: flex; flex-direction: column; @@ -26,22 +26,8 @@ form button { margin-top: 1rem; } -label { - width: 100%; - margin: 1rem 0 .5rem 0; - display: block; - color: #10101080; -} input { width: 100%; - margin: .5rem 0; - padding: .3rem .5rem; - display: block; - border-radius: 4px; - border: 1px solid #808080; - font-size: inherit; - font-family: inherit; - color: inherit; } {{end}} @@ -52,7 +38,7 @@ input {

{{html .Session.Error.String}}

{{end}} -
+
diff --git a/admin/views/totp-confirm.html b/admin/views/totp-confirm.html new file mode 100644 index 0000000..af6b6e1 --- /dev/null +++ b/admin/views/totp-confirm.html @@ -0,0 +1,34 @@ +{{define "head"}} +TOTP Confirmation - ari melody 💫 + + + +{{end}} + +{{define "content"}} +
+ {{if .Session.Error.Valid}} +

{{html .Session.Error.String}}

+ {{end}} + + +

Your TOTP secret: {{.TOTP.Secret}}

+ + + +

+ Please store this into your two-factor authentication app or + password manager, then enter your code below: +

+ + + + + + +
+{{end}} diff --git a/admin/views/totp-setup.html b/admin/views/totp-setup.html new file mode 100644 index 0000000..62b9daf --- /dev/null +++ b/admin/views/totp-setup.html @@ -0,0 +1,20 @@ +{{define "head"}} +TOTP Setup - ari melody 💫 + + +{{end}} + +{{define "content"}} +
+ {{if .Session.Error.Valid}} +

{{html .Session.Error.String}}

+ {{end}} + +
+ + + + +
+
+{{end}} diff --git a/controller/totp.go b/controller/totp.go index 83a5b1c..02f1c4b 100644 --- a/controller/totp.go +++ b/controller/totp.go @@ -17,9 +17,9 @@ import ( "github.com/jmoiron/sqlx" ) -const TOTP_SECRET_LENGTH = 64 -const TIME_STEP int64 = 30 -const CODE_LENGTH = 6 +const TOTP_SECRET_LENGTH = 32 +const TOTP_TIME_STEP int64 = 30 +const TOTP_CODE_LENGTH = 6 func GenerateTOTP(secret string, timeStepOffset int) string { decodedSecret, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret) @@ -27,7 +27,7 @@ func GenerateTOTP(secret string, timeStepOffset int) string { fmt.Fprintf(os.Stderr, "WARN: Invalid Base32 secret\n") } - counter := time.Now().Unix() / TIME_STEP - int64(timeStepOffset) + counter := time.Now().Unix() / TOTP_TIME_STEP - int64(timeStepOffset) counterBytes := make([]byte, 8) binary.BigEndian.PutUint64(counterBytes, uint64(counter)) @@ -37,9 +37,9 @@ func GenerateTOTP(secret string, timeStepOffset int) string { offset := hash[len(hash) - 1] & 0x0f binaryCode := int32(binary.BigEndian.Uint32(hash[offset : offset + 4]) & 0x7FFFFFFF) - code := binaryCode % int32(math.Pow10(CODE_LENGTH)) + code := binaryCode % int32(math.Pow10(TOTP_CODE_LENGTH)) - return fmt.Sprintf(fmt.Sprintf("%%0%dd", CODE_LENGTH), code) + return fmt.Sprintf(fmt.Sprintf("%%0%dd", TOTP_CODE_LENGTH), code) } func GenerateTOTPSecret(length int) string { @@ -65,8 +65,8 @@ func GenerateTOTPURI(username string, secret string) string { query.Set("secret", secret) query.Set("issuer", "arimelody.me") query.Set("algorithm", "SHA1") - query.Set("digits", fmt.Sprintf("%d", CODE_LENGTH)) - query.Set("period", fmt.Sprintf("%d", TIME_STEP)) + query.Set("digits", fmt.Sprintf("%d", TOTP_CODE_LENGTH)) + query.Set("period", fmt.Sprintf("%d", TOTP_TIME_STEP)) url.RawQuery = query.Encode() return url.String() @@ -98,7 +98,11 @@ func CheckTOTPForAccount(db *sqlx.DB, accountID string, totp string) (*model.TOT for _, method := range totps { check := GenerateTOTP(method.Secret, 0) if check == totp { - // return the whole TOTP method as it may be useful for logging + return &method, nil + } + // try again with offset- maybe user input the code late? + check = GenerateTOTP(method.Secret, 1) + if check == totp { return &method, nil } }