gengitkan/internal/middleware/auth.go

66 lines
1.5 KiB
Go
Raw Permalink Normal View History

2019-11-28 11:50:51 +01:00
package middleware
import (
"net/http"
"github.com/pborman/uuid"
2020-04-30 10:32:12 +02:00
"forge.cadoles.com/wpetit/gengitkan/internal/config"
2019-11-28 11:50:51 +01:00
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service"
"gitlab.com/wpetit/goweb/service/session"
"golang.org/x/oauth2"
)
const (
SessionOAuth2AccessToken = "accessToken"
SessionOAuth2State = "oauth2State"
)
func Authenticate(next http.Handler) http.Handler {
fn := func(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"))
}
accessToken, ok := sess.Get(SessionOAuth2AccessToken).(string)
if !ok || accessToken == "" {
state := uuid.New()
sess.Set(SessionOAuth2State, state)
if err := sess.Save(w, r); err != nil {
panic(errors.Wrap(err, "could not save session"))
}
giteaOAuth2Config := GiteaOAuth2Config(ctn)
url := giteaOAuth2Config.AuthCodeURL(state)
http.Redirect(w, r, url, http.StatusSeeOther)
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func GiteaOAuth2Config(ctn *service.Container) *oauth2.Config {
conf := config.Must(ctn)
return &oauth2.Config{
RedirectURL: conf.Gitea.RedirectURL,
ClientID: conf.Gitea.ClientID,
ClientSecret: conf.Gitea.ClientSecret,
Scopes: conf.Gitea.Scopes,
Endpoint: oauth2.Endpoint{
AuthURL: conf.Gitea.AuthURL,
TokenURL: conf.Gitea.TokenURL,
AuthStyle: oauth2.AuthStyleInParams,
},
}
}