gengitkan/internal/route/oauth2.go

47 lines
1.1 KiB
Go
Raw Permalink Normal View History

2019-11-28 11:50:51 +01:00
package route
import (
"net/http"
2020-04-30 10:32:12 +02:00
"forge.cadoles.com/wpetit/gengitkan/internal/middleware"
2019-11-28 11:50:51 +01:00
"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)
}