package handlers import ( "net/http" "git.haelnorr.com/h/golib/hws" "github.com/pkg/errors" "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(server *hws.Server, cfg *config.Config, st *store.Store, discordAPI *discord.APIClient) http.Handler { return http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { // Track login redirect attempts attempts, exceeded, track := st.TrackRedirect(r, "/login", 5) if exceeded { // Build detailed error for logging 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"), ) // Clear the tracking entry st.ClearRedirectTrack(r, "/login") // Show error page throwError( server, 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(server, w, r, "Failed to generate state token", err) return } oauth.SetStateCookie(w, uak, cfg.HWSAuth.SSL) link, err := discord.GetOAuthLink(cfg.Discord, state, cfg.HWSAuth.TrustedHost) if err != nil { throwInternalServiceError(server, w, r, "An error occurred trying to generate the login link", err) return } // SUCCESS POINT: OAuth link generated, redirecting to Discord // Clear redirect tracking - user successfully initiated OAuth st.ClearRedirectTrack(r, "/login") http.Redirect(w, r, link, http.StatusSeeOther) }, ) }