package handlers import ( stderrors "errors" "net/http" "git.haelnorr.com/h/golib/cookies" "git.haelnorr.com/h/golib/hws" "github.com/pkg/errors" "git.haelnorr.com/h/oslstats/internal/config" "git.haelnorr.com/h/oslstats/internal/db" "git.haelnorr.com/h/oslstats/internal/discord" "git.haelnorr.com/h/oslstats/internal/notify" "git.haelnorr.com/h/oslstats/internal/respond" "git.haelnorr.com/h/oslstats/internal/store" "git.haelnorr.com/h/oslstats/internal/throw" "git.haelnorr.com/h/oslstats/pkg/oauth" ) func Login( s *hws.Server, conn *db.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 { notify.ServiceUnavailable(s, w, r, "Login currently unavailable", err) respond.OK(w) return } respond.HXRedirect(w, "/login") return } if err != nil { throw.ServiceUnavailable(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 = track.Error(attempts) st.ClearRedirectTrack(r, "/login") throw.BadRequest(s, w, r, "Too many redirects. Please clear your browser cookies and try again", err) return } state, uak, err := oauth.GenerateState(cfg.OAuth, "login") if err != nil { throw.InternalServiceError(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 { throw.InternalServiceError(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) }, ) }