package oauth import ( "context" "git.0x7f.app/WOJ/woj-server/internal/misc/config" "git.0x7f.app/WOJ/woj-server/internal/misc/log" "git.0x7f.app/WOJ/woj-server/internal/repo/cache" "git.0x7f.app/WOJ/woj-server/internal/service/user" "git.0x7f.app/WOJ/woj-server/internal/web/jwt" "github.com/coreos/go-oidc/v3/oidc" "github.com/gin-gonic/gin" "github.com/samber/do" "go.uber.org/zap" "golang.org/x/oauth2" "time" ) type Handler interface { LoginHandler() gin.HandlerFunc CallbackHandler() gin.HandlerFunc } const ( oauthStateCookieName = "oauth_state" oauthStateKey = "OAuthState:%s" oauthStateLiveness = 15 * time.Minute ) func RouteRegister(rg *gin.RouterGroup, i *do.Injector) { conf := do.MustInvoke[config.Service](i).GetConfig() if conf.WebServer.OAuth.Domain == "" { return } app := &handler{} app.log = do.MustInvoke[log.Service](i).GetLogger("oauth") app.jwt = do.MustInvoke[jwt.Service](i) app.user = do.MustInvoke[user.Service](i) app.cache = do.MustInvoke[cache.Service](i) var err error app.provider, err = oidc.NewProvider(context.Background(), conf.WebServer.OAuth.Domain) if err != nil { app.log.Error("failed to create oauth provider", zap.Error(err), zap.String("domain", conf.WebServer.OAuth.Domain)) return } app.verifier = app.provider.Verifier(&oidc.Config{ClientID: conf.WebServer.OAuth.ClientID}) app.conf = oauth2.Config{ ClientID: conf.WebServer.OAuth.ClientID, ClientSecret: conf.WebServer.OAuth.ClientSecret, RedirectURL: conf.WebServer.PublicBase + rg.BasePath() + "/callback", Endpoint: app.provider.Endpoint(), Scopes: []string{oidc.ScopeOpenID, "profile", "email", "roles"}, } rg.POST("/login", app.LoginHandler()) rg.GET("/callback", app.CallbackHandler()) } type handler struct { log *zap.Logger jwt jwt.Service user user.Service cache cache.Service provider *oidc.Provider conf oauth2.Config verifier *oidc.IDTokenVerifier }