2022-08-11 15:26:55 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
2024-11-11 18:50:17 +00:00
|
|
|
|
|
|
|
"github.com/rs/zerolog/log"
|
2022-08-11 15:26:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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 {
|
2024-11-11 18:50:17 +00:00
|
|
|
log.Error().Err(err).Msg("Exchange error")
|
2022-08-11 15:26:55 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract the ID Token from OAuth2 token.
|
|
|
|
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
|
|
|
if !ok {
|
2024-11-11 18:50:17 +00:00
|
|
|
log.Error().Msg("Cannot retrieve ID token")
|
2022-08-11 15:26:55 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = h.idp.TokenVerifier.Verify(context.Background(), rawIDToken)
|
|
|
|
if err != nil {
|
2024-11-11 18:50:17 +00:00
|
|
|
log.Error().Err(err).Msg("Not able to verify token")
|
2022-08-11 15:26:55 +00:00
|
|
|
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")
|
|
|
|
}
|
|
|
|
|
2022-10-30 19:11:36 +00:00
|
|
|
if err = session.Save(r, w); err != nil {
|
2024-11-11 18:50:17 +00:00
|
|
|
log.Error().Err(err).Msg("Cannot save session")
|
2022-10-30 19:11:36 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-08-11 15:26:55 +00:00
|
|
|
http.Redirect(w, r, redirect, http.StatusFound)
|
|
|
|
}
|