You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

160 lines
4.2 KiB
Go

/*
Copyright 2020-2023 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 (
"fmt"
"html/template"
"net/http"
"net/url"
"github.com/lestrrat-go/jwx/jwk"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
"code.cacert.org/cacert/oidc-demo-app/ui"
"code.cacert.org/cacert/oidc-demo-app/internal/services"
)
type IndexHandler struct {
bundle *i18n.Bundle
indexTemplate *template.Template
logger *log.Logger
keySet jwk.Set
logoutURL string
messageCatalog *services.MessageCatalog
publicURL string
}
func (h *IndexHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet {
http.Error(writer, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
if request.URL.Path != "/" {
http.NotFound(writer, request)
return
}
accept := request.Header.Get("Accept-Language")
localizer := i18n.NewLocalizer(h.bundle, accept)
writer.WriteHeader(http.StatusOK)
session, err := services.GetSessionStore().Get(request, sessionName)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
logoutURL, err := url.Parse(h.logoutURL)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
var (
accessToken string
refreshToken string
idToken string
ok bool
)
if accessToken, ok = session.Values[sessionKeyAccessToken].(string); ok {
h.logger.WithField("access_token", accessToken).Info("found access token in session")
}
if refreshToken, ok = session.Values[refreshToken].(string); ok {
h.logger.WithField("refresh_token", refreshToken).Info("found refresh token in session")
}
if idToken, ok = session.Values[sessionKeyIDToken].(string); ok {
logoutURL.RawQuery = url.Values{
"id_token_hint": []string{idToken},
"post_logout_redirect_uri": []string{fmt.Sprintf("%s/after-logout", h.publicURL)},
}.Encode()
} else {
return
}
oidcToken, err := ParseIDToken(idToken, h.keySet)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
expires := oidcToken.Expiration()
h.logger.WithField("expires", expires).Info("id token expires at")
writer.Header().Add("Content-Type", "text/html")
msgLookup := h.messageCatalog.LookupMessage
err = h.indexTemplate.Lookup("base").Execute(writer, map[string]interface{}{
"Title": msgLookup("IndexTitle", nil, localizer),
"Greeting": msgLookup("IndexGreeting", map[string]interface{}{
"User": oidcToken.Name(),
}, localizer),
"IntroductionText": msgLookup("IndexIntroductionText", nil, localizer),
"LogoutLabel": msgLookup("LogoutLabel", nil, localizer),
"LogoutURL": logoutURL.String(),
"AuthenticatedAs": msgLookup("AuthenticatedAs", map[string]interface{}{
"Name": oidcToken.Name(),
"Email": oidcToken.Email(),
}, localizer),
})
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
return
}
}
func NewIndexHandler(
logger *log.Logger,
bundle *i18n.Bundle,
catalog *services.MessageCatalog,
oidcInfo *services.OIDCInformation,
publicURL string,
) (*IndexHandler, error) {
indexTemplate, err := template.ParseFS(
ui.Templates,
"templates/base.gohtml", "templates/index.gohtml")
if err != nil {
return nil, fmt.Errorf("could not parse templates: %w", err)
}
return &IndexHandler{
logger: logger,
bundle: bundle,
indexTemplate: indexTemplate,
keySet: oidcInfo.KeySet,
logoutURL: oidcInfo.OIDCConfiguration.EndSessionEndpoint,
messageCatalog: catalog,
publicURL: publicURL,
}, nil
}