package routing import ( "errors" "log" "net/http" "time" lishwist "lishwist/core" "lishwist/http/props" "lishwist/http/props/htmlx" "lishwist/http/response" "github.com/Teajey/rsvp" ) func Login(s *response.Session, h http.Header, r *http.Request) rsvp.Response { login := props.NewLogin("", "") flash := s.FlashGet() flashProps, ok := flash.(*props.Login) if ok { login.Username.Value = flashProps.Username.Value login.GeneralError = flashProps.GeneralError login.Username.Error = flashProps.Username.Error login.Password.Error = flashProps.Password.Error login.SuccessfulRegistration = flashProps.SuccessfulRegistration login.SuccessfulSetPassword = flashProps.SuccessfulSetPassword } body := htmlx.Form{Method: "POST", Content: login} return rsvp.Response{TemplateName: "login.gotmpl", Body: body} } func LoginPost(session *response.Session, h http.Header, r *http.Request) rsvp.Response { username, password, ok := r.BasicAuth() if !ok { err := r.ParseForm() if err != nil { return response.Error(http.StatusBadRequest, "Failed to parse form") } username = r.Form.Get("username") password = r.Form.Get("password") } login := props.NewLogin(username, password) resp := rsvp.SeeOther(r.URL.Path, login) valid := login.Validate() login.Password.Value = "" if !valid { session.FlashSet(&login) log.Printf("Invalid login submission: %#v\n", login) resp.Body = htmlx.Form{Method: "POST", Content: login} return resp } appSession, err := lishwist.Login(username, password, time.Hour*24) if err != nil { var targ lishwist.ErrorInvalidCredentials switch { case errors.As(err, &targ): login.GeneralError = "Username or password invalid. If you're having trouble accessing your account, you may want to consider asking the System Admin (Thomas) to reset your password" session.FlashSet(&login) log.Printf("Invalid credentials: %s: %#v\n", err, login) resp.Body = htmlx.Form{Method: "POST", Content: login} return resp default: login.GeneralError = "Something went wrong." session.FlashSet(&login) log.Printf("Login error: %s\n", err) resp.Body = htmlx.Form{Method: "POST", Content: login} return resp } } session.SetID("") session.SetValue("sessionKey", appSession.Key) return rsvp.SeeOther(r.URL.Path, "Login successful!") }