This commit is contained in:
2026-01-27 19:14:12 +11:00
parent e47619abd4
commit b25906b115
15 changed files with 138 additions and 314 deletions

View File

@@ -1,11 +1,13 @@
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"
@@ -13,16 +15,34 @@ import (
"git.haelnorr.com/h/oslstats/pkg/oauth"
)
func Login(server *hws.Server, cfg *config.Config, st *store.Store, discordAPI *discord.APIClient) http.Handler {
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) {
// TODO: check DB is connected
// check discord API is working
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 either fail, notify the client that login is unavailable right now
// otherwise proceed redirect to GET method
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
}
// if either fail and method is GET, show service not available page
cookies.SetPageFrom(w, r, cfg.HWSAuth.TrustedHost)
attempts, exceeded, track := st.TrackRedirect(r, "/login", 5)
@@ -39,7 +59,7 @@ func Login(server *hws.Server, cfg *config.Config, st *store.Store, discordAPI *
st.ClearRedirectTrack(r, "/login")
throwError(
server,
s,
w,
r,
http.StatusBadRequest,
@@ -52,14 +72,14 @@ func Login(server *hws.Server, cfg *config.Config, st *store.Store, discordAPI *
state, uak, err := oauth.GenerateState(cfg.OAuth, "login")
if err != nil {
throwInternalServiceError(server, w, r, "Failed to generate state token", err)
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(server, w, r, "An error occurred trying to generate the login link", err)
throwInternalServiceError(s, w, r, "An error occurred trying to generate the login link", err)
return
}
st.ClearRedirectTrack(r, "/login")