108 lines
2.3 KiB
Go
108 lines
2.3 KiB
Go
package login
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"librapi/forms"
|
|
"librapi/services"
|
|
"librapi/templates"
|
|
)
|
|
|
|
const URL = "/login"
|
|
|
|
func Handler(a services.IAuthenticate) func(http.ResponseWriter, *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
getLogin(w, r, a)
|
|
case http.MethodPost:
|
|
postLogin(w, r, a)
|
|
default:
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
}
|
|
|
|
func postLogin(w http.ResponseWriter, r *http.Request, a services.IAuthenticate) {
|
|
if a.IsLogged(r) {
|
|
tmpl, err := templates.ExecuteLoginSuccessTmpl(w)
|
|
if err != nil {
|
|
log.Err(err).Msg("unable to generate login success template")
|
|
return
|
|
}
|
|
fmt.Fprint(w, tmpl)
|
|
return
|
|
}
|
|
|
|
lf := forms.LoginFormFromRequest(r)
|
|
if lf.HasErrors() {
|
|
tmpl, err := templates.ExecuteLoginFormTmpl(&lf, w)
|
|
if err != nil {
|
|
log.Err(err).Msg("unable to generate login form template")
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
fmt.Fprint(w, tmpl)
|
|
return
|
|
}
|
|
|
|
session, err := a.Authenticate(lf.Username.Value, lf.Password.Value)
|
|
if err != nil {
|
|
if errors.Is(err, services.ErrUnauthorized) {
|
|
log.Warn().Str("username", lf.Username.Value).Msg("bad credentials")
|
|
|
|
lf.Error = forms.ErrInvalidCredentials
|
|
|
|
tmpl, err := templates.ExecuteLoginFormTmpl(&lf, w)
|
|
if err != nil {
|
|
log.Err(err).Msg("unable to generate login form template")
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
fmt.Fprint(w, tmpl)
|
|
return
|
|
}
|
|
|
|
http.Error(w, "unexpected error occurred", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
cookie := session.GenerateCookie(a.IsSecure())
|
|
http.SetCookie(w, cookie)
|
|
|
|
tmpl, err := templates.ExecuteLoginSuccessTmpl(w)
|
|
if err != nil {
|
|
log.Err(err).Msg("unable to generate login success template")
|
|
return
|
|
}
|
|
|
|
fmt.Fprint(w, tmpl)
|
|
}
|
|
|
|
func getLogin(w http.ResponseWriter, r *http.Request, a services.IAuthenticate) {
|
|
if a.IsLogged(r) {
|
|
tmpl, err := templates.ExecuteLoginSuccessTmpl(w)
|
|
if err != nil {
|
|
log.Err(err).Msg("unable to generate login success template")
|
|
return
|
|
}
|
|
|
|
fmt.Fprint(w, tmpl)
|
|
return
|
|
}
|
|
|
|
tmpl, err := templates.ExecuteLoginFormTmpl(&forms.LoginForm{}, w)
|
|
if err != nil {
|
|
log.Err(err).Msg("unable to generate login form template")
|
|
return
|
|
}
|
|
|
|
fmt.Fprint(w, tmpl)
|
|
}
|