package main import ( "fmt" "log" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" "gorm.io/driver/sqlite" "gorm.io/gorm" "oidc-oauth2-server/config" "oidc-oauth2-server/handlers" "oidc-oauth2-server/models" "oidc-oauth2-server/services" ) func main() { // 初始化配置 if err := config.Init(); err != nil { log.Fatalf("Failed to initialize config: %v", err) } // 初始化数据库连接 db, err := gorm.Open(sqlite.Open(config.GlobalConfig.Database.Path), &gorm.Config{}) if err != nil { log.Fatalf("Failed to connect to database: %v", err) } // 运行数据库迁移 if err := models.AutoMigrate(db); err != nil { log.Fatalf("Failed to run database migrations: %v", err) } // 初始化服务 authService := services.NewAuthService(db) oauthService := services.NewOAuthService(db, []byte(config.GlobalConfig.JWT.SigningKey)) // 设置 Gin 路由 r := gin.Default() // 设置模板目录 r.LoadHTMLGlob("templates/*") // 设置 session 中间件 store := cookie.NewStore([]byte("secret")) r.Use(sessions.Sessions("oidc_session", store)) // 健康检查 r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{ "status": "ok", }) }) // 创建处理器 authHandler := handlers.NewAuthHandler(authService) oidcHandler := handlers.NewOIDCHandler(config.GlobalConfig.OAuth.IssuerURL, oauthService, authService) // 认证路由 r.GET("/login", authHandler.ShowLogin) r.POST("/login", authHandler.HandleLogin) // OIDC 端点 r.GET("/.well-known/openid-configuration", oidcHandler.OpenIDConfiguration) r.GET("/authorize", oidcHandler.Authorize) r.POST("/token", oidcHandler.Token) r.GET("/userinfo", oidcHandler.Userinfo) r.GET("/jwks", oidcHandler.JWKS) // 启动服务器 addr := fmt.Sprintf("%s:%d", config.GlobalConfig.Server.Host, config.GlobalConfig.Server.Port) log.Printf("Starting server on %s", addr) if err := r.Run(addr); err != nil { log.Fatalf("Failed to start server: %v", err) } }