75 lines
1.9 KiB
Go
75 lines
1.9 KiB
Go
package routing
|
|
|
|
import (
|
|
"encoding/json"
|
|
"lishwist/api"
|
|
sesh "lishwist/session"
|
|
"lishwist/templates"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
func (ctx *Context) Login(w http.ResponseWriter, r *http.Request) {
|
|
session, _ := ctx.store.Get(r, "lishwist_user")
|
|
|
|
props := api.NewLoginProps("", "")
|
|
|
|
flash, err := sesh.GetFirstFlash(w, r, session, "login_props")
|
|
if err != nil {
|
|
http.Error(w, "Something went wrong. Error code: Zuko", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
flashProps, ok := flash.(*api.LoginProps)
|
|
if ok {
|
|
props.Username.Value = flashProps.Username.Value
|
|
|
|
props.GeneralError = flashProps.GeneralError
|
|
props.Username.Error = flashProps.Username.Error
|
|
props.Password.Error = flashProps.Password.Error
|
|
}
|
|
|
|
flash, err = sesh.GetFirstFlash(w, r, session, "successful_registration")
|
|
if err != nil {
|
|
http.Error(w, "Something went wrong. Error code: Zuko", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
successfulReg, _ := flash.(bool)
|
|
if successfulReg {
|
|
props.SuccessfulRegistration = true
|
|
}
|
|
|
|
templates.Execute(w, "login.gotmpl", props)
|
|
}
|
|
|
|
func (ctx *Context) LoginPost(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, "Couldn't parse form", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
username := r.Form.Get("username")
|
|
password := r.Form.Get("password")
|
|
|
|
props := api.Login(username, password)
|
|
if props != nil {
|
|
ctx.RedirectWithFlash(w, r, "/", "login_props", &props)
|
|
_ = json.NewEncoder(w).Encode(props)
|
|
return
|
|
}
|
|
|
|
// NOTE: Overwriting any existing cookie or session here. So we don't care if there's an error
|
|
session, _ := ctx.store.Get(r, "lishwist_user")
|
|
session.ID = ""
|
|
session.Values["authorized"] = true
|
|
session.Values["username"] = username
|
|
if err := session.Save(r, w); err != nil {
|
|
log.Println("Couldn't save session:", err)
|
|
http.Error(w, "Something went wrong. Error code: Zuko", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, r.URL.Path, http.StatusSeeOther)
|
|
}
|