package routing import ( "errors" "fmt" "log" "net/http" "time" lishwist "lishwist/core" "lishwist/http/props" "lishwist/http/props/htmlx" "lishwist/http/response" "lishwist/http/session" "github.com/Teajey/rsvp" ) func Login(s *session.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[*props.Login]{Method: "POST", Elements: login} return rsvp.Response{TemplateName: "login.gotmpl", Body: body} } func LoginPost(session *session.Session, h http.Header, r *http.Request) rsvp.Response { 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") referrer := r.URL.Query().Get("referrer") if referrer != "" { return LoginWithCreds(username, password, session, referrer) } else { return LoginWithCreds(username, password, session, r.URL.Path) } } func LoginWithCreds(username, password string, session *session.Session, referrer string) rsvp.Response { login := props.NewLogin(username, password) resp := rsvp.SeeOther(referrer, login) valid := login.Validate() login.Password.Value = "" if !valid { session.FlashSet(&login) log.Printf("Invalid login submission: %#v\n", login) resp.Body = htmlx.Form[*props.Login]{Method: "POST", Elements: 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[*props.Login]{Method: "POST", Elements: login} return resp default: login.GeneralError = "Something went wrong." session.FlashSet(&login) log.Printf("Login error: %s\n", err) resp.Body = htmlx.Form[*props.Login]{Method: "POST", Elements: login} return resp } } session.SetID("") session.SetValue("sessionKey", appSession.Key) return rsvp.SeeOther(referrer, "Login successful!") } func LoginReferrer(s *session.Session, h http.Header, r *http.Request) rsvp.Response { return rsvp.Found(fmt.Sprintf("/login?referrer=%s", r.URL.Path), nil) }