parcoursmob/handlers/api/oidc.go

51 lines
1.3 KiB
Go
Executable File

package api
import (
"context"
"net/http"
"github.com/rs/zerolog/log"
)
func (h APIHandler) OAuth2Callback(w http.ResponseWriter, r *http.Request) {
oauth2Token, err := h.idp.OAuth2Config.Exchange(context.Background(), r.URL.Query().Get("code"))
if err != nil {
log.Error().Err(err).Msg("Exchange error")
w.WriteHeader(http.StatusInternalServerError)
return
}
// Extract the ID Token from OAuth2 token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
log.Error().Msg("Cannot retrieve ID token")
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = h.idp.TokenVerifier.Verify(context.Background(), rawIDToken)
if err != nil {
log.Error().Err(err).Msg("Not able to verify token")
w.WriteHeader(http.StatusUnauthorized)
return
}
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
session.Values["idtoken"] = rawIDToken
redirect := "/app/"
if session.Values["redirect"] != nil && session.Values["redirect"] != "" {
redirect = session.Values["redirect"].(string)
delete(session.Values, "redirect")
}
if err = session.Save(r, w); err != nil {
log.Error().Err(err).Msg("Cannot save session")
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, redirect, http.StatusFound)
}