ContainerImage.SpamasaurusRex/pkg/spamasaurusrex/main.go

102 lines
2.3 KiB
Go
Raw Normal View History

2024-02-19 00:35:04 +00:00
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
_ "github.com/breml/rootcerts"
2024-03-09 06:56:47 +00:00
"github.com/davecgh/go-spew/spew"
2024-03-10 04:48:44 +00:00
"github.com/gorilla/mux"
2024-03-09 06:56:47 +00:00
2024-03-10 04:48:44 +00:00
"golang.org/x/oauth2"
"golang.org/x/oauth2/microsoft"
2024-02-19 00:35:04 +00:00
)
2024-03-10 04:48:44 +00:00
var config = oauth2.Config{
ClientID: "dccb4b93-3f75-4775-a94a-da39216d7daf",
ClientSecret: "tiL8Q~qahoaZUck4ZG4sc5w.V_I.1c60bwkW6aYJ",
Endpoint: microsoft.AzureADEndpoint("ceeae22e-f163-4ac9-b7c2-45972d3aed4f"),
2024-03-10 05:22:41 +00:00
RedirectURL: "https://alias.spamasaurus.com/callback",
2024-03-10 04:48:44 +00:00
Scopes: []string{"User.Read"},
}
2024-03-10 04:48:44 +00:00
func rootHandler(w http.ResponseWriter, r *http.Request) {
url := config.AuthCodeURL("state", oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusFound)
}
2024-03-01 06:15:06 +00:00
2024-03-10 04:48:44 +00:00
func callbackHandler(w http.ResponseWriter, r *http.Request) {
// Handle the callback after successful authentication
code := r.URL.Query().Get("code")
token, err := config.Exchange(r.Context(), code)
if err != nil {
2024-03-10 05:37:17 +00:00
w.Write([]byte(spew.Sdump(err)))
2024-03-10 04:48:44 +00:00
http.Error(w, "Error exchanging code for token", http.StatusInternalServerError)
return
}
2024-03-10 04:48:44 +00:00
// Use the token to make MS Graph queries
// Example: Fetch user profile information
// ...
w.Write([]byte(spew.Sdump(token)))
fmt.Fprintln(w, "Authentication successful!")
2024-02-19 00:35:04 +00:00
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func readinessHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func main() {
r := mux.NewRouter()
2024-03-10 04:48:44 +00:00
r.HandleFunc("/", rootHandler)
2024-02-19 00:35:04 +00:00
r.HandleFunc("/health", healthHandler)
2024-03-10 04:48:44 +00:00
r.HandleFunc("/callback", callbackHandler)
2024-02-19 00:35:04 +00:00
r.HandleFunc("/readiness", readinessHandler)
srv := &http.Server{
Handler: r,
Addr: ":8080",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
// Start Server
go func() {
log.Println("Starting Server")
if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
// Graceful Shutdown
waitForShutdown(srv)
}
func waitForShutdown(srv *http.Server) {
interruptChan := make(chan os.Signal, 1)
signal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
// Block until we receive our signal.
<-interruptChan
// create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
srv.Shutdown(ctx)
log.Println("Shutting down")
os.Exit(0)
}