Skip to content

The only tool you need to know what is happening and how to fix it.

sso auth

dduxe98ca467973b
diff --git a/backend/app/config/config.go b/backend/app/config/config.go
index e2c43be7..1cf0836a 100644
--- a/backend/app/config/config.go
+++ b/backend/app/config/config.go
@@ -41,6 +41,12 @@ type Cfg struct {
APIOnly string
Ports string
TurnstileSecretKey string
+
+ GoogleClientID string
+ GoogleClientSecret string
+ GitHubClientID string
+ GitHubClientSecret string
+ OAuthSessionSecret string
}
var Config *Cfg
@@ -87,5 +93,11 @@ func LoadFromEnv() *Cfg {
APIOnly: os.Getenv("API_ONLY"),
Ports: os.Getenv("PORTS"),
TurnstileSecretKey: os.Getenv("TURNSTILE_SECRET_KEY"),
+
+ GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),
+ GoogleClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
+ GitHubClientID: os.Getenv("GITHUB_CLIENT_ID"),
+ GitHubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
+ OAuthSessionSecret: os.Getenv("OAUTH_SESSION_SECRET"),
}
}
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.go
index 2f89f5f4..d60b43e7 100644
--- a/backend/app/controllers/auth.controller.go
+++ b/backend/app/controllers/auth.controller.go
@@ -202,4 +202,42 @@ func (a authController) Register(c *gin.Context) {
})
}
+func (a authController) LoginBundle(c *gin.Context) {
+ tx := middleware.GetTx(c)
+
+ userId := middleware.GetUserId(c)
+ if userId == 0 {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+
+ user, err := repositories.UserRepository.FindById(tx, userId)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("LoginBundle: load user: %w", err))
+ return
+ }
+ if user == nil {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+
+ projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("LoginBundle: load projects: %w", err))
+ return
+ }
+
+ organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("LoginBundle: load orgs: %w", err))
+ return
+ }
+
+ c.JSON(http.StatusOK, &models.LoginResponse{
+ User: user.ToResponse(),
+ Projects: projects,
+ Organizations: organizations,
+ })
+}
+
var AuthController = authController{}
diff --git a/backend/app/controllers/oauth.controller.go b/backend/app/controllers/oauth.controller.go
new file mode 100644
index 00000000..77a05b1b
--- /dev/null
+++ b/backend/app/controllers/oauth.controller.go
@@ -0,0 +1,274 @@
+package controllers
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "github.com/tracewayapp/traceway/backend/app/cache"
+ "github.com/tracewayapp/traceway/backend/app/config"
+ "github.com/tracewayapp/traceway/backend/app/middleware"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+ "github.com/tracewayapp/traceway/backend/app/services"
+
+ "github.com/gin-gonic/gin"
+ "github.com/markbates/goth"
+ "github.com/markbates/goth/gothic"
+ traceway "go.tracewayapp.com"
+)
+
+type oauthController struct{}
+
+type oauthProvidersResponse struct {
+ Providers []string `json:"providers"`
+}
+
+type finishOAuthSetupRequest struct {
+ OrganizationName string `json:"organizationName" binding:"required"`
+ Timezone string `json:"timezone" binding:"required"`
+ ProjectName string `json:"projectName" binding:"required"`
+ Framework string `json:"framework" binding:"required"`
+}
+
+func (a oauthController) ListProviders(c *gin.Context) {
+ if services.OAuthService == nil {
+ c.JSON(http.StatusOK, oauthProvidersResponse{Providers: []string{}})
+ return
+ }
+ c.JSON(http.StatusOK, oauthProvidersResponse{Providers: services.OAuthService.EnabledProviders()})
+}
+
+func (a oauthController) Begin(c *gin.Context) {
+ provider := c.Param("provider")
+ if services.OAuthService == nil || !services.OAuthService.IsProviderEnabled(provider) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown OAuth provider"})
+ return
+ }
+
+ req := c.Request.WithContext(context.WithValue(c.Request.Context(), gothic.ProviderParamKey, provider))
+ gothic.BeginAuthHandler(c.Writer, req)
+}
+
+func (a oauthController) Callback(c *gin.Context) {
+ provider := c.Param("provider")
+ if services.OAuthService == nil || !services.OAuthService.IsProviderEnabled(provider) {
+ a.redirectError(c, "oauth_failed")
+ return
+ }
+
+ req := c.Request.WithContext(context.WithValue(c.Request.Context(), gothic.ProviderParamKey, provider))
+ gothUser, err := gothic.CompleteUserAuth(c.Writer, req)
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("OAuth complete failed (provider=%s): %w", provider, err))
+ a.redirectError(c, "oauth_failed")
+ return
+ }
+
+ if gothUser.Email == "" {
+ a.redirectError(c, "oauth_no_email")
+ return
+ }
+
+ user, err := a.findOrCreateUser(c, provider, gothUser)
+ if err != nil {
+ return
+ }
+
+ tx := middleware.GetTx(c)
+
+ memberships, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: load memberships: %w", err))
+ return
+ }
+ needsSetup := len(memberships) == 0
+
+ jwt, err := services.GenerateToken(user.Id, user.Email)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: generate JWT: %w", err))
+ return
+ }
+
+ target := fmt.Sprintf("%s/auth/callback#token=%s&needsSetup=%t",
+ strings.TrimRight(config.Config.AppBaseURL, "/"),
+ url.QueryEscape(jwt),
+ needsSetup,
+ )
+ c.Redirect(http.StatusSeeOther, target)
+}
+
+func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothUser goth.User) (*models.User, error) {
+ tracewayTx := middleware.GetTx(c)
+
+ user, err := repositories.UserRepository.FindByOAuth(tracewayTx, provider, gothUser.UserID)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: lookup by provider: %w", err))
+ return nil, err
+ }
+ if user != nil {
+ return user, nil
+ }
+
+ existing, err := repositories.UserRepository.FindByEmailIgnoreCase(tracewayTx, gothUser.Email)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: lookup by email: %w", err))
+ return nil, err
+ }
+
+ if existing != nil {
+ if err := repositories.UserRepository.LinkOAuth(tracewayTx, existing.Id, provider, gothUser.UserID, gothUser.AvatarURL); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: link provider: %w", err))
+ return nil, err
+ }
+ return existing, nil
+ }
+
+ if config.Config.CloudMode != "true" {
+ hasOrg, err := repositories.OrganizationRepository.HasOrganizations(tracewayTx)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: count orgs: %w", err))
+ return nil, err
+ }
+ if hasOrg {
+ a.redirectError(c, "invite_required")
+ return nil, errors.New("invite required")
+ }
+ }
+
+ name := gothUser.Name
+ if name == "" {
+ name = gothUser.NickName
+ }
+ if name == "" {
+ name = gothUser.Email
+ }
+
+ created, err := repositories.UserRepository.CreateOAuth(tracewayTx, gothUser.Email, name, provider, gothUser.UserID, gothUser.AvatarURL)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: create user: %w", err))
+ return nil, err
+ }
+ return created, nil
+}
+
+func (a oauthController) FinishSetup(c *gin.Context) {
+ var request finishOAuthSetupRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ if !validFrameworks[request.Framework] {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, hono, cloudflare, opentelemetry, symfony, flutter"})
+ return
+ }
+
+ userId := middleware.GetUserId(c)
+ if userId == 0 {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+
+ tx := middleware.GetTx(c)
+
+ user, err := repositories.UserRepository.FindById(tx, userId)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load user: %w", err))
+ return
+ }
+ if user == nil {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+
+ memberships, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load memberships: %w", err))
+ return
+ }
+ if len(memberships) > 0 {
+ c.JSON(http.StatusConflict, gin.H{"error": "Setup already complete"})
+ return
+ }
+
+ if config.Config.CloudMode != "true" {
+ hasOrg, err := repositories.OrganizationRepository.HasOrganizations(tx)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: count orgs: %w", err))
+ return
+ }
+ if hasOrg {
+ c.JSON(http.StatusConflict, gin.H{"error": "An organization already exists. Please ask an admin to invite you."})
+ return
+ }
+ }
+
+ org, err := repositories.OrganizationRepository.Create(tx, request.OrganizationName, request.Timezone)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: create org: %w", err))
+ return
+ }
+
+ if _, err := repositories.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner"); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: add user to org: %w", err))
+ return
+ }
+
+ for _, hook := range PostRegistrationHooks {
+ if err := hook(tx, org, user); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: post-registration hook: %w", err))
+ return
+ }
+ }
+
+ project, err := repositories.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: create project: %w", err))
+ return
+ }
+
+ cache.ProjectCache.AddProject(&models.Project{
+ Id: project.Id,
+ Name: project.Name,
+ Token: project.Token,
+ Framework: project.Framework,
+ OrganizationId: project.OrganizationId,
+ })
+
+ token, err := services.GenerateToken(user.Id, user.Email)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: regenerate token: %w", err))
+ return
+ }
+
+ projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load projects: %w", err))
+ return
+ }
+
+ organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load orgs: %w", err))
+ return
+ }
+
+ c.JSON(http.StatusCreated, &models.RegisterResponse{
+ Token: token,
+ User: user.ToResponse(),
+ Project: *project.ToProjectWithBackendUrl(),
+ Projects: projects,
+ Organizations: organizations,
+ })
+}
+
+func (a oauthController) redirectError(c *gin.Context, code string) {
+ target := fmt.Sprintf("%s/login?error=%s", strings.TrimRight(config.Config.AppBaseURL, "/"), url.QueryEscape(code))
+ c.Redirect(http.StatusSeeOther, target)
+}
+
+var OAuthController = oauthController{}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 74ae03c2..47d61b6c 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -108,6 +108,13 @@ func RegisterControllers(router *gin.RouterGroup) {
// Auth
router.POST("/login", middleware.Transactional, AuthController.Login)
router.POST("/register", middleware.Transactional, AuthController.Register)
+ router.GET("/me/login-bundle", middleware.UseAppAuth, middleware.Transactional, AuthController.LoginBundle)
+
+ // OAuth (Google, GitHub via markbates/goth)
+ router.GET("/auth/providers", OAuthController.ListProviders)
+ router.GET("/auth/start/:provider", OAuthController.Begin)
+ router.GET("/auth/callback/:provider", middleware.Transactional, OAuthController.Callback)
+ router.POST("/auth/finish-setup", middleware.UseAppAuth, middleware.Transactional, OAuthController.FinishSetup)
if config.Config.CloudMode != "true" {
router.GET("/has-organizations", middleware.Transactional, AuthController.HasOrganizations)
diff --git a/backend/app/migrations/pg/0030_add_oauth_provider_to_users.up.sql b/backend/app/migrations/pg/0030_add_oauth_provider_to_users.up.sql
new file mode 100644
index 00000000..67011082
--- /dev/null
+++ b/backend/app/migrations/pg/0030_add_oauth_provider_to_users.up.sql
@@ -0,0 +1 @@
+ALTER TABLE users ADD COLUMN oauth_provider TEXT
diff --git a/backend/app/migrations/pg/0031_add_oauth_user_id_to_users.up.sql b/backend/app/migrations/pg/0031_add_oauth_user_id_to_users.up.sql
new file mode 100644
index 00000000..088a6cb0
--- /dev/null
+++ b/backend/app/migrations/pg/0031_add_oauth_user_id_to_users.up.sql
@@ -0,0 +1 @@
+ALTER TABLE users ADD COLUMN oauth_user_id TEXT
diff --git a/backend/app/migrations/pg/0032_add_avatar_url_to_users.up.sql b/backend/app/migrations/pg/0032_add_avatar_url_to_users.up.sql
new file mode 100644
index 00000000..586d5b49
--- /dev/null
+++ b/backend/app/migrations/pg/0032_add_avatar_url_to_users.up.sql
@@ -0,0 +1 @@
+ALTER TABLE users ADD COLUMN avatar_url TEXT
diff --git a/backend/app/migrations/pg/0033_create_users_oauth_index.up.sql b/backend/app/migrations/pg/0033_create_users_oauth_index.up.sql
new file mode 100644
index 00000000..cd222f4c
--- /dev/null
+++ b/backend/app/migrations/pg/0033_create_users_oauth_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX IF NOT EXISTS idx_users_oauth ON users(oauth_provider, oauth_user_id) WHERE oauth_provider IS NOT NULL
diff --git a/backend/app/migrations/sqlite/0005_add_oauth_provider_to_users.up.sql b/backend/app/migrations/sqlite/0005_add_oauth_provider_to_users.up.sql
new file mode 100644
index 00000000..67011082
--- /dev/null
+++ b/backend/app/migrations/sqlite/0005_add_oauth_provider_to_users.up.sql
@@ -0,0 +1 @@
+ALTER TABLE users ADD COLUMN oauth_provider TEXT
diff --git a/backend/app/migrations/sqlite/0006_add_oauth_user_id_to_users.up.sql b/backend/app/migrations/sqlite/0006_add_oauth_user_id_to_users.up.sql
new file mode 100644
index 00000000..088a6cb0
--- /dev/null
+++ b/backend/app/migrations/sqlite/0006_add_oauth_user_id_to_users.up.sql
@@ -0,0 +1 @@
+ALTER TABLE users ADD COLUMN oauth_user_id TEXT
diff --git a/backend/app/migrations/sqlite/0007_add_avatar_url_to_users.up.sql b/backend/app/migrations/sqlite/0007_add_avatar_url_to_users.up.sql
new file mode 100644
index 00000000..586d5b49
--- /dev/null
+++ b/backend/app/migrations/sqlite/0007_add_avatar_url_to_users.up.sql
@@ -0,0 +1 @@
+ALTER TABLE users ADD COLUMN avatar_url TEXT
diff --git a/backend/app/migrations/sqlite/0008_create_users_oauth_index.up.sql b/backend/app/migrations/sqlite/0008_create_users_oauth_index.up.sql
new file mode 100644
index 00000000..cd222f4c
--- /dev/null
+++ b/backend/app/migrations/sqlite/0008_create_users_oauth_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX IF NOT EXISTS idx_users_oauth ON users(oauth_provider, oauth_user_id) WHERE oauth_provider IS NOT NULL
diff --git a/backend/app/models/user.model.go b/backend/app/models/user.model.go
index cd27783f..3f9003b5 100644
--- a/backend/app/models/user.model.go
+++ b/backend/app/models/user.model.go
@@ -13,6 +13,9 @@ type User struct {
PasswordResetToken *string `json:"-"`
PasswordResetExpiresAt *time.Time `json:"-"`
PasswordResetRequestedAt *time.Time `json:"-"`
+ OauthProvider *string `json:"-"`
+ OauthUserId *string `json:"-"`
+ AvatarUrl *string `json:"avatarUrl,omitempty"`
}
type UserResponse struct {
diff --git a/backend/app/repositories/user.repository.go b/backend/app/repositories/user.repository.go
index 54348dba..e9d67079 100644
--- a/backend/app/repositories/user.repository.go
+++ b/backend/app/repositories/user.repository.go
@@ -12,10 +12,20 @@ import (
type userRepository struct{}
+const userColumns = "id, email, name, password, created_at, oauth_provider, oauth_user_id, avatar_url"
+
func (r *userRepository) FindByEmail(tx *sql.Tx, email string) (*models.User, error) {
return lit.SelectSingleNamed[models.User](
tx,
- "SELECT id, email, name, password, created_at FROM users WHERE email = :email",
+ "SELECT "+userColumns+" FROM users WHERE email = :email",
+ lit.P{"email": email},
+ )
+}
+
+func (r *userRepository) FindByEmailIgnoreCase(tx *sql.Tx, email string) (*models.User, error) {
+ return lit.SelectSingleNamed[models.User](
+ tx,
+ "SELECT "+userColumns+" FROM users WHERE LOWER(email) = LOWER(:email)",
lit.P{"email": email},
)
}
@@ -23,11 +33,19 @@ func (r *userRepository) FindByEmail(tx *sql.Tx, email string) (*models.User, er
func (r *userRepository) FindById(tx *sql.Tx, id int) (*models.User, error) {
return lit.SelectSingleNamed[models.User](
tx,
- "SELECT id, email, name, password, created_at FROM users WHERE id = :id",
+ "SELECT "+userColumns+" FROM users WHERE id = :id",
lit.P{"id": id},
)
}
+func (r *userRepository) FindByOAuth(tx *sql.Tx, provider string, providerUserId string) (*models.User, error) {
+ return lit.SelectSingleNamed[models.User](
+ tx,
+ "SELECT "+userColumns+" FROM users WHERE oauth_provider = :provider AND oauth_user_id = :uid",
+ lit.P{"provider": provider, "uid": providerUserId},
+ )
+}
+
func (r *userRepository) Create(tx *sql.Tx, email string, name string, hashedPassword string) (*models.User, error) {
user := &models.User{
Email: email,
@@ -45,6 +63,54 @@ func (r *userRepository) Create(tx *sql.Tx, email string, name string, hashedPas
return user, nil
}
+func (r *userRepository) CreateOAuth(tx *sql.Tx, email, name, provider, providerUserId, avatarUrl string) (*models.User, error) {
+ var avatar *string
+ if avatarUrl != "" {
+ avatar = &avatarUrl
+ }
+ user := &models.User{
+ Email: email,
+ Name: name,
+ Password: "",
+ CreatedAt: time.Now().UTC(),
+ OauthProvider: &provider,
+ OauthUserId: &providerUserId,
+ AvatarUrl: avatar,
+ }
+
+ id, err := lit.Insert(tx, user)
+ if err != nil {
+ return nil, err
+ }
+ user.Id = id
+
+ return user, nil
+}
+
+func (r *userRepository) LinkOAuth(tx *sql.Tx, userId int, provider, providerUserId, avatarUrl string) error {
+ q, a, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE users SET oauth_provider = :provider, oauth_user_id = :uid, avatar_url = COALESCE(:avatar, avatar_url) WHERE id = :id",
+ lit.P{
+ "provider": provider,
+ "uid": providerUserId,
+ "avatar": nullIfEmpty(avatarUrl),
+ "id": userId,
+ },
+ )
+ if err != nil {
+ return err
+ }
+ return lit.UpdateNative(tx, q, a...)
+}
+
+func nullIfEmpty(s string) any {
+ if s == "" {
+ return nil
+ }
+ return s
+}
+
func (r *userRepository) EmailExists(tx *sql.Tx, email string) (bool, error) {
user, err := r.FindByEmail(tx, email)
if err != nil {
@@ -79,7 +145,7 @@ func (r *userRepository) ClearPasswordResetToken(tx *sql.Tx, userId int) error {
func (r *userRepository) FindByPasswordResetToken(tx *sql.Tx, token string) (*models.User, error) {
return lit.SelectSingleNamed[models.User](
tx,
- "SELECT id, email, name, password, created_at, password_reset_token, password_reset_expires_at, password_reset_requested_at FROM users WHERE password_reset_token = :token",
+ "SELECT "+userColumns+", password_reset_token, password_reset_expires_at, password_reset_requested_at FROM users WHERE password_reset_token = :token",
lit.P{"token": token},
)
}
diff --git a/backend/app/services/oauth.service.go b/backend/app/services/oauth.service.go
new file mode 100644
index 00000000..03fa0768
--- /dev/null
+++ b/backend/app/services/oauth.service.go
@@ -0,0 +1,95 @@
+package services
+
+import (
+ "net/http"
+ "strings"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+
+ "github.com/gorilla/sessions"
+ "github.com/markbates/goth"
+ "github.com/markbates/goth/gothic"
+ "github.com/markbates/goth/providers/github"
+ "github.com/markbates/goth/providers/google"
+)
+
+type oauthService struct {
+ googleEnabled bool
+ githubEnabled bool
+}
+
+var OAuthService *oauthService
+
+func InitOAuth() {
+ cfg := config.Config
+
+ svc := &oauthService{
+ googleEnabled: cfg.GoogleClientID != "" && cfg.GoogleClientSecret != "",
+ githubEnabled: cfg.GitHubClientID != "" && cfg.GitHubClientSecret != "",
+ }
+ OAuthService = svc
+
+ if !svc.googleEnabled && !svc.githubEnabled {
+ return
+ }
+
+ secret := cfg.OAuthSessionSecret
+ if secret == "" {
+ // fall back to JWT secret so cookies are still signed if the operator
+ // forgot to set a dedicated session secret. Both are server-only.
+ secret = cfg.JWTSecret
+ }
+
+ store := sessions.NewCookieStore([]byte(secret))
+ store.Options.Path = "/"
+ store.Options.HttpOnly = true
+ store.Options.MaxAge = 600
+ store.Options.Secure = strings.HasPrefix(cfg.AppBaseURL, "https://")
+ store.Options.SameSite = http.SameSiteLaxMode
+ gothic.Store = store
+
+ providers := []goth.Provider{}
+ base := strings.TrimRight(cfg.AppBaseURL, "/")
+ if svc.googleEnabled {
+ providers = append(providers, google.New(
+ cfg.GoogleClientID,
+ cfg.GoogleClientSecret,
+ base+"/api/auth/callback/google",
+ "email", "profile",
+ ))
+ }
+ if svc.githubEnabled {
+ providers = append(providers, github.New(
+ cfg.GitHubClientID,
+ cfg.GitHubClientSecret,
+ base+"/api/auth/callback/github",
+ "user:email",
+ ))
+ }
+ goth.UseProviders(providers...)
+}
+
+func (s *oauthService) IsEnabled() bool {
+ return s.googleEnabled || s.githubEnabled
+}
+
+func (s *oauthService) IsProviderEnabled(name string) bool {
+ switch name {
+ case "google":
+ return s.googleEnabled
+ case "github":
+ return s.githubEnabled
+ }
+ return false
+}
+
+func (s *oauthService) EnabledProviders() []string {
+ out := []string{}
+ if s.googleEnabled {
+ out = append(out, "google")
+ }
+ if s.githubEnabled {
+ out = append(out, "github")
+ }
+ return out
+}
diff --git a/backend/app/services/password.service.go b/backend/app/services/password.service.go
index 6adac7ab..01ecacfc 100644
--- a/backend/app/services/password.service.go
+++ b/backend/app/services/password.service.go
@@ -15,6 +15,9 @@ func HashPassword(password string) (string, error) {
}
func CheckPassword(password, hash string) bool {
+ if hash == "" {
+ return false
+ }
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index 04c2a9ae..5d94b0aa 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -112,6 +112,7 @@ func Run(opts ...Option) {
services.InitEmail()
services.InitTurnstile()
+ services.InitOAuth()
for _, hook := range PostStartupHooks {
hook(ctx)
diff --git a/backend/go.mod b/backend/go.mod
index 2e48d738..d485aa88 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -9,7 +9,9 @@ require (
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0
github.com/coreos/go-systemd/v22 v22.6.0
github.com/golang-jwt/jwt/v5 v5.3.0
+ github.com/gorilla/sessions v1.4.0
github.com/lib/pq v1.10.9
+ github.com/markbates/goth v1.82.0
github.com/tracewayapp/lit/v2 v2.0.2
go.tracewayapp.com v1.0.2
go.tracewayapp.com/tracewaygin v1.0.2
@@ -17,9 +19,14 @@ require (
)
require (
+ cloud.google.com/go/compute/metadata v0.8.0 // indirect
+ github.com/go-chi/chi/v5 v5.2.2 // indirect
+ github.com/gorilla/mux v1.7.4 // indirect
+ github.com/gorilla/securecookie v1.1.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
+ golang.org/x/oauth2 v0.30.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirect
google.golang.org/grpc v1.75.1 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index ebf6cfa6..85992cf0 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -1,3 +1,5 @@
+cloud.google.com/go/compute/metadata v0.8.0 h1:HxMRIbao8w17ZX6wBnjhcDkW6lTFpgcaobyVfZWqRLA=
+cloud.google.com/go/compute/metadata v0.8.0/go.mod h1:sYOGTp851OV9bOFJ9CH7elVvyzopvWQFNNghtDQ/Biw=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/ClickHouse/ch-go v0.69.0 h1:nO0OJkpxOlN/eaXFj0KzjTz5p7vwP1/y3GN4qc5z/iM=
@@ -91,6 +93,8 @@ github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
+github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618=
+github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-faster/city v1.0.1 h1:4WAxSZ3V2Ws4QRDrscLEDcibJY8uf41H6AhXDrNDcGw=
github.com/go-faster/city v1.0.1/go.mod h1:jKcUJId49qdW3L1qKHH/3wPeUstCVpVSXTM6vO3VcTw=
github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg=
@@ -128,9 +132,17 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
+github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
+github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
+github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
+github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
+github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
+github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
@@ -157,6 +169,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
+github.com/markbates/goth v1.82.0 h1:8j/c34AjBSTNzO7zTsOyP5IYCQCMBTRBHAbBt/PI0bQ=
+github.com/markbates/goth v1.82.0/go.mod h1:/DRlcq0pyqkKToyZjsL2KgiA1zbF1HIjE7u2uC79rUk=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
@@ -271,6 +285,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
+golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
+golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
diff --git a/frontend/src/lib/components/oauth-buttons.svelte b/frontend/src/lib/components/oauth-buttons.svelte
new file mode 100644
index 00000000..aa85ddfa
--- /dev/null
+++ b/frontend/src/lib/components/oauth-buttons.svelte
@@ -0,0 +1,62 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button";
+ import { onMount } from 'svelte';
+
+ let providers = $state<string[]>([]);
+ let loaded = $state(false);
+
+ onMount(async () => {
+ try {
+ const response = await fetch('/api/auth/providers');
+ if (response.ok) {
+ const data = await response.json();
+ providers = data.providers || [];
+ }
+ } catch {
+ providers = [];
+ } finally {
+ loaded = true;
+ }
+ });
+
+ function start(provider: string) {
+ window.location.href = `/api/auth/start/${provider}`;
+ }
+
+ const labels: Record<string, string> = {
+ google: 'Continue with Google',
+ github: 'Continue with GitHub',
+ };
+</script>
+
+{#if loaded && providers.length > 0}
+ <div class="flex flex-col gap-2">
+ {#each providers as provider}
+ <Button
+ type="button"
+ variant="outline"
+ class="w-full"
+ onclick={() => start(provider)}
+ >
+ {#if provider === 'google'}
+ <svg class="size-4" viewBox="0 0 24 24" aria-hidden="true">
+ <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
+ <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
+ <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
+ <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
+ </svg>
+ {:else if provider === 'github'}
+ <svg class="size-4" viewBox="0 0 24 24" aria-hidden="true" fill="currentColor">
+ <path d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56v-2.16c-3.2.7-3.87-1.37-3.87-1.37-.52-1.32-1.27-1.67-1.27-1.67-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.69 1.24 3.34.95.1-.74.4-1.24.72-1.53-2.55-.29-5.24-1.27-5.24-5.66 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.46.11-3.05 0 0 .96-.31 3.15 1.17.91-.25 1.89-.38 2.86-.39.97 0 1.95.13 2.86.39 2.18-1.48 3.14-1.17 3.14-1.17.62 1.59.23 2.76.11 3.05.74.8 1.18 1.82 1.18 3.07 0 4.4-2.69 5.36-5.25 5.65.41.36.78 1.07.78 2.15v3.18c0 .31.21.67.8.56C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z" />
+ </svg>
+ {/if}
+ {labels[provider] ?? `Continue with ${provider}`}
+ </Button>
+ {/each}
+ <div class="flex items-center gap-3 my-2">
+ <div class="flex-1 border-t"></div>
+ <p class="text-xs text-muted-foreground">or</p>
+ <div class="flex-1 border-t"></div>
+ </div>
+ </div>
+{/if}
diff --git a/frontend/src/routes/auth/callback/+page.svelte b/frontend/src/routes/auth/callback/+page.svelte
new file mode 100644
index 00000000..ad35770b
--- /dev/null
+++ b/frontend/src/routes/auth/callback/+page.svelte
@@ -0,0 +1,62 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { onMount } from 'svelte';
+ import { authState } from '$lib/state/auth.svelte';
+ import { projectsState } from '$lib/state/projects.svelte';
+ import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
+ import { CircleAlert } from "@lucide/svelte";
+ import { LoadingCircle } from '$lib/components/ui/loading-circle';
+
+ let error = $state('');
+
+ onMount(async () => {
+ const fragment = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : '';
+ const params = new URLSearchParams(fragment);
+ const token = params.get('token');
+ const needsSetup = params.get('needsSetup') === 'true';
+
+ history.replaceState(null, '', window.location.pathname);
+
+ if (!token) {
+ error = 'Missing authentication token.';
+ setTimeout(() => goto('/login?error=oauth_failed'), 1500);
+ return;
+ }
+
+ authState.setToken(token);
+
+ if (needsSetup) {
+ goto('/finish-setup');
+ return;
+ }
+
+ try {
+ const response = await fetch('/api/me/login-bundle', {
+ headers: { 'Authorization': `Bearer ${token}` }
+ });
+ if (!response.ok) {
+ throw new Error('Failed to load account');
+ }
+ const data = await response.json();
+ authState.setOrganizations(data.organizations || []);
+ projectsState.setProjects(data.projects || []);
+ goto('/');
+ } catch {
+ authState.logout();
+ error = 'Failed to load your account. Please try logging in again.';
+ setTimeout(() => goto('/login?error=oauth_failed'), 1500);
+ }
+ });
+</script>
+
+<div class="flex h-screen w-full items-center justify-center px-4">
+ {#if error}
+ <Alert variant="destructive" class="max-w-md bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Error</AlertTitle>
+ <AlertDescription class="text-red-700">{error}</AlertDescription>
+ </Alert>
+ {:else}
+ <LoadingCircle size="xlg" />
+ {/if}
+</div>
diff --git a/frontend/src/routes/auth/callback/+page.ts b/frontend/src/routes/auth/callback/+page.ts
new file mode 100644
index 00000000..a3d15781
--- /dev/null
+++ b/frontend/src/routes/auth/callback/+page.ts
@@ -0,0 +1 @@
+export const ssr = false;
diff --git a/frontend/src/routes/finish-setup/+page.svelte b/frontend/src/routes/finish-setup/+page.svelte
new file mode 100644
index 00000000..f19751ec
--- /dev/null
+++ b/frontend/src/routes/finish-setup/+page.svelte
@@ -0,0 +1,131 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { onMount } from 'svelte';
+ import { Button } from "$lib/components/ui/button";
+ import { Input } from "$lib/components/ui/input";
+ import { Label } from "$lib/components/ui/label";
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";
+ import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
+ import * as Select from "$lib/components/ui/select";
+ import { CircleAlert, Check } from "@lucide/svelte";
+ import { authState } from '$lib/state/auth.svelte';
+ import { projectsState, type Framework } from '$lib/state/projects.svelte';
+ import { themeState } from '$lib/state/theme.svelte';
+ import FrameworkCombobox from '$lib/components/framework-combobox.svelte';
+
+ const DEFAULT_FRAMEWORK: Framework = 'gin';
+
+ let organizationName = $state('');
+ let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);
+ let projectName = $state('');
+ let framework = $state<Framework>(DEFAULT_FRAMEWORK);
+ let error = $state('');
+ let loading = $state(false);
+
+ const timezones = Intl.supportedValuesOf('timeZone');
+
+ onMount(() => {
+ if (!authState.token) {
+ goto('/login');
+ }
+ });
+
+ async function handleSubmit() {
+ loading = true;
+ error = '';
+ try {
+ const response = await fetch('/api/auth/finish-setup', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${authState.token}`,
+ },
+ body: JSON.stringify({ organizationName, timezone, projectName, framework })
+ });
+
+ if (!response.ok) {
+ const data = await response.json().catch(() => ({}));
+ throw new Error(data.error || 'Setup failed');
+ }
+
+ const data = await response.json();
+ authState.setToken(data.token);
+ authState.setOrganizations(data.organizations || []);
+ projectsState.setProjects(data.projects);
+ goto('/');
+ } catch (e) {
+ error = e instanceof Error ? e.message : 'Setup failed';
+ } finally {
+ loading = false;
+ }
+ }
+</script>
+
+<div class="flex min-h-screen w-full items-center justify-center px-4 py-8">
+ <Card class="w-[400px]">
+ <CardHeader>
+ <CardTitle class="text-2xl">
+ <div class="flex flex-row items-center justify-center gap-2">
+ {#if themeState.isDark}
+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />
+ {:else}
+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />
+ {/if}
+ </div>
+ </CardTitle>
+ <CardDescription class="text-center">
+ Finish setting up your account
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {#if error}
+ <Alert variant="destructive" class="mb-4 bg-red-50 border-red-200">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Error</AlertTitle>
+ <AlertDescription class="text-red-700">{error}</AlertDescription>
+ </Alert>
+ {/if}
+ <form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="grid w-full items-center gap-4">
+ <div class="flex flex-col space-y-1.5">
+ <Label for="organizationName">Organization Name</Label>
+ <Input id="organizationName" type="text" bind:value={organizationName} placeholder="Your company or team" required />
+ </div>
+ <div class="flex flex-col space-y-1.5">
+ <Label for="timezone">Timezone</Label>
+ <Select.Root type="single" bind:value={timezone}>
+ <Select.Trigger class="w-full">
+ <span>{timezone}</span>
+ </Select.Trigger>
+ <Select.Content class="max-h-60">
+ {#each timezones as tz}
+ <Select.Item value={tz}>
+ {#snippet children({ selected })}
+ <span>{tz}</span>
+ {#if selected}
+ <Check class="absolute end-2 size-4" />
+ {/if}
+ {/snippet}
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
+ <div class="flex flex-col space-y-1.5">
+ <Label for="projectName">Project Name</Label>
+ <Input id="projectName" type="text" bind:value={projectName} placeholder="My App" required />
+ </div>
+ <div class="flex flex-col space-y-1.5">
+ <Label for="framework">Framework</Label>
+ <FrameworkCombobox bind:value={framework} />
+ </div>
+ <Button type="submit" disabled={loading} class="w-full mt-2">
+ {#if loading}
+ Finishing setup...
+ {:else}
+ Finish setup
+ {/if}
+ </Button>
+ </form>
+ </CardContent>
+ </Card>
+</div>
diff --git a/frontend/src/routes/finish-setup/+page.ts b/frontend/src/routes/finish-setup/+page.ts
new file mode 100644
index 00000000..a3d15781
--- /dev/null
+++ b/frontend/src/routes/finish-setup/+page.ts
@@ -0,0 +1 @@
+export const ssr = false;
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte
index cee1e9fa..5d59600f 100644
--- a/frontend/src/routes/login/+page.svelte
+++ b/frontend/src/routes/login/+page.svelte
@@ -11,9 +11,17 @@
import { projectsState } from '$lib/state/projects.svelte';
import { themeState } from '$lib/state/theme.svelte';
import { toast } from 'svelte-sonner';
+ import OauthButtons from '$lib/components/oauth-buttons.svelte';
+
+ const ERROR_MESSAGES: Record<string, string> = {
+ oauth_failed: 'Sign-in failed. Please try again.',
+ oauth_no_email: "We couldn't read an email address from that account. Please make sure it has a verified email and try again.",
+ invite_required: 'This server is invite-only. Ask an admin to invite you.',
+ };
let email = $state(page.url.searchParams.get('email') ?? '');
let password = $state(page.url.searchParams.get('password') ?? '');
+ const initialError = page.url.searchParams.get('error');
if (page.url.searchParams.has('email') || page.url.searchParams.has('password')) {
const cleanUrl = new URL(window.location.href);
@@ -22,9 +30,15 @@
window.history.replaceState({}, '', cleanUrl.pathname + cleanUrl.search);
}
- let error = $state('');
+ let error = $state(initialError ? (ERROR_MESSAGES[initialError] ?? 'Sign-in failed. Please try again.') : '');
let loading = $state(false);
+ if (initialError) {
+ const cleanUrl = new URL(window.location.href);
+ cleanUrl.searchParams.delete('error');
+ window.history.replaceState({}, '', cleanUrl.pathname + cleanUrl.search);
+ }
+
// Get returnTo parameter for redirecting after login
const returnTo = $derived(page.url.searchParams.get('returnTo'));
@@ -109,6 +123,7 @@
</AlertDescription>
</Alert>
{/if}
+ <OauthButtons />
<form onsubmit={(e) => { e.preventDefault(); handleLogin(); }} class="grid w-full items-center gap-4">
<div class="flex flex-col space-y-1.5">
<Label for="email">Email</Label>
diff --git a/frontend/src/routes/register/+page.svelte b/frontend/src/routes/register/+page.svelte
index bc7e1b58..1ffc9532 100644
--- a/frontend/src/routes/register/+page.svelte
+++ b/frontend/src/routes/register/+page.svelte
@@ -14,6 +14,7 @@
import { toast } from 'svelte-sonner';
import FrameworkCombobox from '$lib/components/framework-combobox.svelte';
import TurnstileWidget from '$lib/components/turnstile-widget.svelte';
+ import OauthButtons from '$lib/components/oauth-buttons.svelte';
const DEFAULT_FRAMEWORK: Framework = 'gin';
@@ -145,6 +146,7 @@
</AlertDescription>
</Alert>
{/if}
+ <OauthButtons />
<form onsubmit={(e) => { e.preventDefault(); handleRegister(); }} class="grid w-full items-center gap-4">
<div class="flex flex-col space-y-1.5">
<Label for="email">Email</Label>