| 1 |
package app
|
| 2 |
|
| 3 |
import (
|
| 4 |
"net/http"
|
| 5 |
)
|
| 6 |
|
| 7 |
type pageData struct {
|
| 8 |
Title string
|
| 9 |
Email string
|
| 10 |
Error string
|
| 11 |
Notice string
|
| 12 |
CSRF string
|
| 13 |
Token string
|
| 14 |
User User
|
| 15 |
Sub Subscriber
|
| 16 |
Counts struct{ Subs, Users, Catalog, Boms int }
|
| 17 |
|
| 18 |
Catalog []CatalogEntry
|
| 19 |
Edit *CatalogEntry
|
| 20 |
Subs []SubscriberWithUsers
|
| 21 |
|
| 22 |
BOMs []BOMSummary
|
| 23 |
BOM *BOMDetail
|
| 24 |
BackURL string
|
| 25 |
}
|
| 26 |
|
| 27 |
func (a *App) render(w http.ResponseWriter, r *http.Request, status int, name string, data pageData) {
|
| 28 |
data.CSRF = csrfToken(r)
|
| 29 |
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
| 30 |
w.WriteHeader(status)
|
| 31 |
_ = tmpl.ExecuteTemplate(w, name, data)
|
| 32 |
}
|
| 33 |
|
| 34 |
func (a *App) handleLoginForm(w http.ResponseWriter, r *http.Request) {
|
| 35 |
a.render(w, r, http.StatusOK, "login", pageData{Title: "Sign in"})
|
| 36 |
}
|
| 37 |
|
| 38 |
func (a *App) handleLogin(w http.ResponseWriter, r *http.Request) {
|
| 39 |
email := r.PostFormValue("email")
|
| 40 |
password := r.PostFormValue("password")
|
| 41 |
|
| 42 |
u, err := a.authenticate(r.Context(), email, password)
|
| 43 |
if err != nil {
|
| 44 |
a.render(w, r, http.StatusUnauthorized, "login", pageData{
|
| 45 |
Title: "Sign in", Email: email, Error: "Invalid email or password.",
|
| 46 |
})
|
| 47 |
return
|
| 48 |
}
|
| 49 |
|
| 50 |
raw, err := a.createSession(r.Context(), u.ID)
|
| 51 |
if err != nil {
|
| 52 |
http.Error(w, "could not start session", http.StatusInternalServerError)
|
| 53 |
return
|
| 54 |
}
|
| 55 |
a.setSessionCookie(w, raw)
|
| 56 |
|
| 57 |
sub, _ := a.subscriber(r.Context(), u.SubscriberID)
|
| 58 |
dest := "/app"
|
| 59 |
if sub.IsInternal {
|
| 60 |
dest = "/admin"
|
| 61 |
}
|
| 62 |
http.Redirect(w, r, dest, http.StatusSeeOther)
|
| 63 |
}
|
| 64 |
|
| 65 |
func (a *App) handleLogout(w http.ResponseWriter, r *http.Request) {
|
| 66 |
if c, err := r.Cookie(cookieName); err == nil && c.Value != "" {
|
| 67 |
a.destroySession(r.Context(), c.Value)
|
| 68 |
}
|
| 69 |
a.clearSessionCookie(w)
|
| 70 |
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
| 71 |
}
|
| 72 |
|
| 73 |
func (a *App) handleApp(w http.ResponseWriter, r *http.Request) {
|
| 74 |
u, s, _ := current(r)
|
| 75 |
boms, err := a.listBOMs(r.Context(), &s.ID)
|
| 76 |
if err != nil {
|
| 77 |
http.Error(w, err.Error(), http.StatusInternalServerError)
|
| 78 |
return
|
| 79 |
}
|
| 80 |
a.render(w, r, http.StatusOK, "app", pageData{
|
| 81 |
Title: "Dashboard",
|
| 82 |
User: u,
|
| 83 |
Sub: s,
|
| 84 |
BOMs: boms,
|
| 85 |
Notice: r.URL.Query().Get("notice"),
|
| 86 |
Error: r.URL.Query().Get("err"),
|
| 87 |
})
|
| 88 |
}
|