package route import ( "net/http" "forge.cadoles.com/wpetit/gengitkan/internal/middleware" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/middleware/container" "gitlab.com/wpetit/goweb/service/session" "golang.org/x/oauth2" ) func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) { ctn := container.Must(r.Context()) sess, err := session.Must(ctn).Get(w, r) if err != nil { panic(errors.Wrap(err, "could not retrieve session")) } expectedState := sess.Get(middleware.SessionOAuth2State) state := r.FormValue("state") if state != expectedState { http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } giteaOAuth2Config := middleware.GiteaOAuth2Config(ctn) code := r.FormValue("code") token, err := giteaOAuth2Config.Exchange(oauth2.NoContext, code) if err != nil { panic(errors.Wrap(err, "could not exchange oauth2 token")) } sess.Set(middleware.SessionOAuth2AccessToken, token.AccessToken) sess.Set(middleware.SessionOAuth2State, "") if err := sess.Save(w, r); err != nil { panic(errors.Wrap(err, "could not save session")) } http.Redirect(w, r, "/", http.StatusSeeOther) }