lishwist/http/routing/login.go

88 lines
2.5 KiB
Go

package routing
import (
"errors"
"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")
return LoginWithCreds(username, password, session, h, r)
}
func LoginWithCreds(username, password string, session *session.Session, h http.Header, r *http.Request) rsvp.Response {
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[*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(r.URL.Path, "Login successful!")
}