| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | |
| 6 | "github.com/stevedylandev/andromeda/pkg/auth" |
| 7 | ) |
| 8 | |
| 9 | func (a *App) rootRedirect(w http.ResponseWriter, r *http.Request) { |
| 10 | http.Redirect(w, r, "/buckets", http.StatusSeeOther) |
| 11 | } |
| 12 | |
| 13 | func (a *App) loginGet(w http.ResponseWriter, r *http.Request) { |
| 14 | if a.Sessions.HasValid(r) { |
| 15 | http.Redirect(w, r, "/buckets", http.StatusSeeOther) |
| 16 | return |
| 17 | } |
| 18 | a.renderPage(w, "login.html", loginPageData{Error: r.URL.Query().Get("error")}) |
| 19 | } |
| 20 | |
| 21 | func (a *App) loginPost(w http.ResponseWriter, r *http.Request) { |
| 22 | if err := r.ParseForm(); err != nil { |
| 23 | http.Redirect(w, r, "/login?error=Bad+request", http.StatusSeeOther) |
| 24 | return |
| 25 | } |
| 26 | if !auth.VerifyPassword(r.FormValue("password"), a.Password) { |
| 27 | http.Redirect(w, r, "/login?error=Invalid+password", http.StatusSeeOther) |
| 28 | return |
| 29 | } |
| 30 | token, err := a.Sessions.Create() |
| 31 | if err != nil { |
| 32 | a.Log.Error("create session", "err", err) |
| 33 | http.Redirect(w, r, "/login?error=Server+error", http.StatusSeeOther) |
| 34 | return |
| 35 | } |
| 36 | a.Sessions.PruneExpired() |
| 37 | http.SetCookie(w, a.Sessions.SessionCookie(token)) |
| 38 | http.Redirect(w, r, "/buckets", http.StatusSeeOther) |
| 39 | } |
| 40 | |
| 41 | func (a *App) logout(w http.ResponseWriter, r *http.Request) { |
| 42 | if c, err := r.Cookie(a.Sessions.CookieName); err == nil && c.Value != "" { |
| 43 | a.Sessions.Delete(c.Value) |
| 44 | } |
| 45 | http.SetCookie(w, a.Sessions.ClearCookie()) |
| 46 | http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 47 | } |