Files
oslstats/internal/handlers/login.go
2026-01-27 19:14:12 +11:00

91 lines
2.2 KiB
Go

package handlers
import (
stderrors "errors"
"net/http"
"git.haelnorr.com/h/golib/cookies"
"git.haelnorr.com/h/golib/hws"
"github.com/pkg/errors"
"github.com/uptrace/bun"
"git.haelnorr.com/h/oslstats/internal/config"
"git.haelnorr.com/h/oslstats/internal/discord"
"git.haelnorr.com/h/oslstats/internal/store"
"git.haelnorr.com/h/oslstats/pkg/oauth"
)
func Login(
s *hws.Server,
conn *bun.DB,
cfg *config.Config,
st *store.Store,
discordAPI *discord.APIClient,
) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
errDB := conn.Ping()
_, errDisc := discordAPI.Ping()
err := stderrors.Join(errors.Wrap(errDB, "conn.Ping"), errors.Wrap(errDisc, "discordAPI.Ping"))
err = errors.Wrap(err, "login error")
if r.Method == "POST" {
if err != nil {
notifyServiceUnavailable(s, r, "Login currently unavailable", err)
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("HX-Redirect", "/login")
return
}
if err != nil {
throwServiceUnavailable(s, w, r, "Login currently unavailable", err)
return
}
cookies.SetPageFrom(w, r, cfg.HWSAuth.TrustedHost)
attempts, exceeded, track := st.TrackRedirect(r, "/login", 5)
if exceeded {
err := errors.Errorf(
"login redirect loop detected after %d attempts | ip=%s ua=%s path=%s first_seen=%s",
attempts,
track.IP,
track.UserAgent,
track.Path,
track.FirstSeen.Format("2006-01-02T15:04:05Z07:00"),
)
st.ClearRedirectTrack(r, "/login")
throwError(
s,
w,
r,
http.StatusBadRequest,
"Login failed: Too many redirect attempts. Please clear your browser cookies and try again.",
err,
"warn",
)
return
}
state, uak, err := oauth.GenerateState(cfg.OAuth, "login")
if err != nil {
throwInternalServiceError(s, w, r, "Failed to generate state token", err)
return
}
oauth.SetStateCookie(w, uak, cfg.HWSAuth.SSL)
link, err := discordAPI.GetOAuthLink(state)
if err != nil {
throwInternalServiceError(s, w, r, "An error occurred trying to generate the login link", err)
return
}
st.ClearRedirectTrack(r, "/login")
http.Redirect(w, r, link, http.StatusSeeOther)
},
)
}