diff --git a/admin/accounthttp.go b/admin/accounthttp.go
index fc701e7..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,9 +16,12 @@ 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))
- mux.Handle("/", accountIndexHandler(app))
return mux
}
@@ -37,6 +41,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 +68,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 +129,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,36 +140,212 @@ 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)
})
}
+
+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 ad0d44e..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)
- session.Error = sql.NullString{}
- session.Message = sql.NullString{}
if session.Account != nil {
// user is already logged in
@@ -102,8 +100,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,8 +124,7 @@ func registerAccountHandler(app *model.AppState) http.Handler {
err := r.ParseForm()
if err != nil {
- session.Error = sql.NullString{ String: "Malformed data.", Valid: true }
- render()
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
@@ -144,7 +145,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 +154,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 +162,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,21 +176,30 @@ 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) }
// 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)
})
}
@@ -229,8 +239,7 @@ func loginHandler(app *model.AppState) http.Handler {
err := r.ParseForm()
if err != nil {
- session.Error = sql.NullString{ String: "Malformed data.", Valid: true }
- render()
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
@@ -253,12 +262,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 +276,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 +287,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,13 +300,15 @@ 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,
)
// 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)
})
}
@@ -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/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 0acfaf5..b1d083a 100644
--- a/admin/views/edit-account.html
+++ b/admin/views/edit-account.html
@@ -44,7 +44,7 @@
Added: {{.CreatedAt}}
{{end}} @@ -52,7 +52,10 @@You have no MFA devices.
{{end}} - +{{html .Session.Error.String}}
{{end}} -