98 lines
2.5 KiB
Go
98 lines
2.5 KiB
Go
package routing
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
lishwist "lishwist/core"
|
|
"lishwist/http/props"
|
|
"lishwist/http/response"
|
|
"lishwist/http/session"
|
|
|
|
"github.com/Teajey/hmc"
|
|
"github.com/Teajey/rsvp"
|
|
)
|
|
|
|
type LoginPage struct {
|
|
hmc.Namespace
|
|
Form hmc.Form[props.Login]
|
|
}
|
|
|
|
func Login(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
|
|
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 := LoginPage{
|
|
Namespace: hmc.NS(),
|
|
Form: hmc.Form[props.Login]{Method: "POST", Elements: login},
|
|
}
|
|
return rsvp.Body{TemplateName: "login.gotmpl", Data: body}
|
|
}
|
|
|
|
func LoginPost(session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
|
|
err := r.ParseForm()
|
|
if err != nil {
|
|
return response.Error("Failed to parse form").StatusBadRequest()
|
|
}
|
|
|
|
username := r.Form.Get("username")
|
|
password := r.Form.Get("password")
|
|
referrer := r.URL.Query().Get("referrer")
|
|
|
|
login := props.NewLogin(username, password)
|
|
|
|
resp := rsvp.Data(login).StatusSeeOther(referrer)
|
|
|
|
valid := login.Validate()
|
|
login.Password.Value = ""
|
|
if !valid {
|
|
session.FlashSet(&login)
|
|
log.Printf("Invalid login submission: %#v\n", login)
|
|
resp.Data = LoginPage{
|
|
Namespace: hmc.NS(),
|
|
Form: hmc.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)
|
|
default:
|
|
login.GeneralError = "Something went wrong."
|
|
session.FlashSet(&login)
|
|
log.Printf("Login error: %s\n", err)
|
|
}
|
|
|
|
resp.Data = LoginPage{
|
|
Namespace: hmc.NS(),
|
|
Form: hmc.Form[props.Login]{Method: "POST", Elements: login},
|
|
}
|
|
return resp
|
|
}
|
|
|
|
session.SetID("")
|
|
session.SetValue("sessionKey", appSession.Key)
|
|
|
|
return rsvp.Data("Login successful!").StatusSeeOther(referrer)
|
|
}
|