81 lines
2.0 KiB
Go
81 lines
2.0 KiB
Go
package routing
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
lishwist "lishwist/core"
|
|
"lishwist/http/api"
|
|
"lishwist/http/response"
|
|
|
|
"github.com/Teajey/rsvp"
|
|
)
|
|
|
|
func Login(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
|
|
props := api.NewLoginProps("", "")
|
|
|
|
flash := s.FlashGet()
|
|
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
|
|
|
|
props.SuccessfulRegistration = flashProps.SuccessfulRegistration
|
|
props.SuccessfulSetPassword = flashProps.SuccessfulSetPassword
|
|
}
|
|
|
|
return rsvp.Response{TemplateName: "login.gotmpl", Body: props}
|
|
}
|
|
|
|
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")
|
|
}
|
|
|
|
props := api.NewLoginProps(username, password)
|
|
|
|
resp := rsvp.SeeOther(r.URL.Path, props)
|
|
|
|
valid := props.Validate()
|
|
props.Password.Value = ""
|
|
if !valid {
|
|
session.FlashSet(&props)
|
|
log.Printf("Invalid props: %#v\n", props)
|
|
return resp
|
|
}
|
|
|
|
appSession, err := lishwist.Login(username, password, time.Hour*24)
|
|
if err != nil {
|
|
var targ lishwist.ErrorInvalidCredentials
|
|
switch {
|
|
case errors.As(err, &targ):
|
|
props.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(&props)
|
|
log.Printf("Invalid credentials: %s: %#v\n", err, props)
|
|
return resp
|
|
default:
|
|
props.GeneralError = "Something went wrong."
|
|
session.FlashSet(&props)
|
|
log.Printf("Login error: %s\n", err)
|
|
return resp
|
|
}
|
|
}
|
|
|
|
session.SetID("")
|
|
session.SetValue("sessionKey", appSession.Key)
|
|
|
|
return rsvp.SeeOther(r.URL.Path, "Login successful!")
|
|
}
|