polycule-connect/polyculeconnect/controller/auth/authredirect.go
Melora Hugues a0849388a7
Some checks failed
/ docker-build-only (push) Failing after 37s
/ go-test (push) Failing after 1m28s
Add login workflow until callback (#48)
2024-10-06 22:11:58 +02:00

63 lines
2 KiB
Go

package auth
import (
"net/http"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/helpers"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/storage"
"github.com/google/uuid"
"github.com/zitadel/oidc/v3/pkg/client/rp"
"go.uber.org/zap"
)
const AuthRedirectRoute = "/perform_auth"
type AuthRedirectController struct {
l *zap.SugaredLogger
st *storage.Storage
}
func NewAuthRedirectController(l *zap.SugaredLogger, storage *storage.Storage) *AuthRedirectController {
return &AuthRedirectController{
l: l,
st: storage,
}
}
func (c *AuthRedirectController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestIDStr := r.URL.Query().Get("request_id")
if requestIDStr == "" {
helpers.HandleResponse(w, r, http.StatusBadRequest, []byte("no request ID in request"), c.l)
return
}
requestID, err := uuid.Parse(requestIDStr)
if err != nil {
c.l.Errorf("Invalid UUID format for request ID: %s", err)
helpers.HandleResponse(w, r, http.StatusBadRequest, []byte("invalid request id"), c.l)
return
}
req, err := c.st.LocalStorage.AuthRequestStorage().GetAuthRequestByID(r.Context(), requestID)
if err != nil {
c.l.Errorf("Failed to get auth request from DB: %s", err)
helpers.HandleResponse(w, r, http.StatusBadRequest, []byte("unknown request id"), c.l)
return
}
backend, err := c.st.LocalStorage.BackendStorage().GetBackendByID(r.Context(), req.BackendID)
if err != nil {
c.l.Errorf("Failed to get backend from DB: %s", err)
helpers.HandleResponse(w, r, http.StatusInternalServerError, []byte("failed to perform auth"), c.l)
return
}
provider, err := rp.NewRelyingPartyOIDC(r.Context(), backend.Config.Issuer, backend.Config.ClientID, backend.Config.ClientSecret, backend.Config.RedirectURI, req.Scopes)
if err != nil {
c.l.Errorf("Failed to init relying party: %s", err)
helpers.HandleResponse(w, r, http.StatusInternalServerError, []byte("failed to perform auth"), c.l)
return
}
rp.AuthURLHandler(func() string { return requestIDStr }, provider).ServeHTTP(w, r)
}