/* Copyright CAcert Inc. SPDX-License-Identifier: Apache-2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package handlers import ( "encoding/base64" "fmt" "log/slog" "net/http" "github.com/gorilla/sessions" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/oauth2" "code.cacert.org/cacert/oidc-demo-app/internal/services" ) const ( oauth2RedirectStateLength = 8 sessionName = "resource_app" ) func Authenticate(logger *slog.Logger, oauth2Config *oauth2.Config) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session, err := GetSession(r) if err != nil { logger.ErrorContext(r.Context(), "failed to get session", "error", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } if _, ok := session.Values[services.SessionIDToken]; ok { next.ServeHTTP(w, r) return } session.Values[services.SessionRedirectTarget] = r.URL.String() if err = session.Save(r, w); err != nil { logger.ErrorContext(r.Context(), "failed to save session", "error", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } state, err := services.GenerateKey(oauth2RedirectStateLength) if err != nil { logger.ErrorContext( r.Context(), "failed to generate state for starting OIDC flow", "error", err, ) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } authURL := oauth2Config.AuthCodeURL(base64.URLEncoding.EncodeToString(state)) w.Header().Set("Location", authURL) w.WriteHeader(http.StatusFound) }) } } func GetSession(r *http.Request) (*sessions.Session, error) { session, err := services.GetSessionStore().Get(r, sessionName) if err != nil { return nil, fmt.Errorf("could not get session") } return session, nil } type I18NHandler interface { GetBundle() *i18n.Bundle GetCatalog() *services.MessageCatalog } func GetLocalizer(h I18NHandler, r *http.Request) *i18n.Localizer { accept := r.Header.Get("Accept-Language") localizer := i18n.NewLocalizer(h.GetBundle(), accept) return localizer } func BaseTemplateData(h I18NHandler, localizer *i18n.Localizer) map[string]interface{} { msg := h.GetCatalog().LookupMessage data := map[string]interface{}{ "WelcomeNavLabel": msg("IndexNavLabel", nil, localizer), "ProtectedNavLabel": msg("ProtectedNavLabel", nil, localizer), } return data }