goweb-oidc/internal/route/login.go

54 lines
1.3 KiB
Go
Raw Normal View History

2020-05-20 10:43:12 +02:00
package route
import (
"encoding/json"
"net/http"
oidc "forge.cadoles.com/wpetit/goweb-oidc"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveHomePage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
idToken, err := oidc.IDToken(w, r)
if err != nil {
panic(errors.Wrap(err, "could not retrieve idToken"))
}
jsonIDToken, err := json.MarshalIndent(idToken, "", " ")
if err != nil {
panic(errors.Wrap(err, "could not encode idToken"))
}
data := extendTemplateData(w, r, template.Data{
"IDToken": idToken,
"JSONIDToken": string(jsonIDToken),
})
if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
idToken, err := oidc.IDToken(w, r)
if err != nil {
logger.Error(ctx, "could not retrieve idToken", logger.E(err))
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
logger.Info(ctx, "user logged in", logger.F("sub", idToken.Subject))
http.Redirect(w, r, "/", http.StatusSeeOther)
}