Files
mailgoserver/internal/webui/mailbox_apppasswords.go
T

71 lines
2.3 KiB
Go
Raw Normal View History

2026-08-12 21:14:19 +01:00
package webui
import (
"net/http"
"strings"
"mailgoserver/internal/db"
)
// appPasswordsList shows a mailbox's existing app-password labels (never the secrets
// themselves — those are shown once, at creation) plus a form to add a new one.
func (a *App) appPasswordsList(w http.ResponseWriter, r *http.Request) {
mailbox, ok := a.mailboxWithAccess(w, r)
if !ok {
return
}
passwords, err := a.DB.ListAppPasswordsForMailbox(mailbox.ID)
if err != nil {
setFlash(w, "error", "Error loading app passwords")
}
a.render(w, r, "mailbox_apppasswords.html", M{"active": "mailboxes", "mailbox": mailbox, "passwords": passwords})
}
// addAppPassword generates a random secret (the only credential IMAP/SMTP clients ever
// use for this mailbox — never the portal password), shows it once via flash, and
// stores only its bcrypt hash.
func (a *App) addAppPassword(w http.ResponseWriter, r *http.Request) {
mailbox, ok := a.mailboxWithAccess(w, r)
if !ok {
return
}
label := strings.TrimSpace(r.FormValue("label"))
if label == "" {
label = "App password"
}
minLen := a.Cfg.Section("Mailstore").Key("app_password_min_length").MustInt(25)
secret := db.GenerateAppPassword(minLen)
hash, err := db.HashPassword(secret)
if err != nil {
setFlash(w, "error", "Error creating app password")
http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/apppasswords", http.StatusFound)
return
}
if _, err := a.DB.CreateAppPassword(mailbox.ID, label, hash); err != nil {
setFlash(w, "error", "Error creating app password")
http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/apppasswords", http.StatusFound)
return
}
setFlash(w, "success", "App password created — copy it now, it will not be shown again: "+secret)
http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/apppasswords", http.StatusFound)
}
func (a *App) revokeAppPassword(w http.ResponseWriter, r *http.Request) {
mailbox, ok := a.mailboxWithAccess(w, r)
if !ok {
return
}
pwID := int64(atoi(r.PathValue("pw_id")))
if err := a.DB.RemoveAppPassword(pwID, mailbox.ID); err != nil {
setFlash(w, "error", "Error revoking app password")
} else {
setFlash(w, "success", "App password revoked")
}
http.Redirect(w, r, Prefix+"/mailboxes/"+idStr(r)+"/apppasswords", http.StatusFound)
}
func idStr(r *http.Request) string {
return r.PathValue("id")
}