Skip to content

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

feat: generic OIDC SSO and password-login disable flag (#152)

The Kinky Coder7a84f1a3f41b
diff --git a/backend/app/config/config.go b/backend/app/config/config.go
index 2661e1ae..fa15cbba 100644
--- a/backend/app/config/config.go
+++ b/backend/app/config/config.go
@@ -52,6 +52,21 @@ type Cfg struct {
GitHubClientID string
GitHubClientSecret string
OAuthSessionSecret string
+
+ OIDCClientID string
+ OIDCClientSecret string
+ OIDCDiscoveryURL string
+ OIDCDisplayName string
+ OIDCAutoCreateUsers string
+ OIDCOrgClaim string
+ OIDCExtraScopes string
+ OIDCRoleClaim string
+ OIDCRoleMap string
+ OIDCAuthURL string
+ OIDCTokenURL string
+ OIDCUserInfoURL string
+
+ DisablePasswordLogin string
}
var Config *Cfg
@@ -109,5 +124,20 @@ func LoadFromEnv() *Cfg {
GitHubClientID: os.Getenv("GITHUB_CLIENT_ID"),
GitHubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
OAuthSessionSecret: os.Getenv("OAUTH_SESSION_SECRET"),
+
+ OIDCClientID: os.Getenv("OIDC_CLIENT_ID"),
+ OIDCClientSecret: os.Getenv("OIDC_CLIENT_SECRET"),
+ OIDCDiscoveryURL: os.Getenv("OIDC_DISCOVERY_URL"),
+ OIDCDisplayName: os.Getenv("OIDC_DISPLAY_NAME"),
+ OIDCAutoCreateUsers: os.Getenv("OIDC_AUTO_CREATE_USERS"),
+ OIDCOrgClaim: os.Getenv("OIDC_ORG_CLAIM"),
+ OIDCExtraScopes: os.Getenv("OIDC_EXTRA_SCOPES"),
+ OIDCRoleClaim: os.Getenv("OIDC_ROLE_CLAIM"),
+ OIDCRoleMap: os.Getenv("OIDC_ROLE_MAP"),
+ OIDCAuthURL: os.Getenv("OIDC_AUTH_URL"),
+ OIDCTokenURL: os.Getenv("OIDC_TOKEN_URL"),
+ OIDCUserInfoURL: os.Getenv("OIDC_USER_INFO_URL"),
+
+ DisablePasswordLogin: os.Getenv("DISABLE_PASSWORD_LOGIN"),
}
}
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.go
index 9a9a0a00..6785af31 100644
--- a/backend/app/controllers/auth.controller.go
+++ b/backend/app/controllers/auth.controller.go
@@ -31,6 +31,11 @@ func (a authController) HasOrganizations(c *gin.Context) {
}
func (a authController) Login(c *gin.Context) {
+ if config.Config.DisablePasswordLogin == "true" {
+ c.JSON(http.StatusForbidden, gin.H{"error": "Password login is disabled. Please use SSO to sign in."})
+ return
+ }
+
var request models.LoginRequest
if err := c.ShouldBindJSON(&request); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
@@ -81,6 +86,11 @@ func (a authController) Login(c *gin.Context) {
}
func (a authController) Register(c *gin.Context) {
+ if config.Config.DisablePasswordLogin == "true" {
+ c.JSON(http.StatusForbidden, gin.H{"error": "Password login is disabled. Please use SSO to sign in."})
+ return
+ }
+
var request models.RegisterRequest
if err := c.ShouldBindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
diff --git a/backend/app/controllers/oauth.controller.go b/backend/app/controllers/oauth.controller.go
index 4b466c87..09fdebf4 100644
--- a/backend/app/controllers/oauth.controller.go
+++ b/backend/app/controllers/oauth.controller.go
@@ -2,6 +2,7 @@ package controllers
import (
"context"
+ "database/sql"
"errors"
"fmt"
"net/http"
@@ -24,7 +25,9 @@ import (
type oauthController struct{}
type oauthProvidersResponse struct {
- Providers []string `json:"providers"`
+ Providers []string `json:"providers"`
+ ProviderLabels map[string]string `json:"providerLabels"`
+ PasswordLoginEnabled bool `json:"passwordLoginEnabled"`
}
type finishOAuthSetupRequest struct {
@@ -35,11 +38,20 @@ type finishOAuthSetupRequest struct {
}
func (a oauthController) ListProviders(c *gin.Context) {
+ passwordEnabled := config.Config.DisablePasswordLogin != "true"
if services.OAuthService == nil {
- c.JSON(http.StatusOK, oauthProvidersResponse{Providers: []string{}})
+ c.JSON(http.StatusOK, oauthProvidersResponse{Providers: []string{}, ProviderLabels: map[string]string{}, PasswordLoginEnabled: passwordEnabled})
return
}
- c.JSON(http.StatusOK, oauthProvidersResponse{Providers: services.OAuthService.EnabledProviders()})
+ labels := map[string]string{}
+ if name := services.OAuthService.OIDCDisplayName(); name != "" {
+ labels["oidc"] = name
+ }
+ c.JSON(http.StatusOK, oauthProvidersResponse{
+ Providers: services.OAuthService.EnabledProviders(),
+ ProviderLabels: labels,
+ PasswordLoginEnabled: passwordEnabled,
+ })
}
func (a oauthController) Begin(c *gin.Context) {
@@ -49,7 +61,7 @@ func (a oauthController) Begin(c *gin.Context) {
return
}
- req := c.Request.WithContext(context.WithValue(c.Request.Context(), gothic.ProviderParamKey, provider))
+ req := c.Request.WithContext(context.WithValue(c.Request.Context(), gothic.ProviderParamKey, externalToGothProvider(provider)))
gothic.BeginAuthHandler(c.Writer, req)
}
@@ -60,7 +72,7 @@ func (a oauthController) Callback(c *gin.Context) {
return
}
- req := c.Request.WithContext(context.WithValue(c.Request.Context(), gothic.ProviderParamKey, provider))
+ req := c.Request.WithContext(context.WithValue(c.Request.Context(), gothic.ProviderParamKey, externalToGothProvider(provider)))
gothUser, err := gothic.CompleteUserAuth(c.Writer, req)
if err != nil {
traceway.CaptureException(fmt.Errorf("OAuth complete failed (provider=%s): %w", provider, err))
@@ -80,6 +92,11 @@ func (a oauthController) Callback(c *gin.Context) {
tx := middleware.GetTx(c)
+ var mappedRole string
+ if provider == "oidc" && services.OAuthService.OIDCRoleClaimEnabled() {
+ mappedRole = services.OAuthService.ResolveRole(gothUser.RawData)
+ }
+
memberships, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: load memberships: %w", err))
@@ -87,6 +104,35 @@ func (a oauthController) Callback(c *gin.Context) {
}
needsSetup := len(memberships) == 0
+ if needsSetup && config.Config.CloudMode != "true" && provider == "oidc" && services.OAuthService.OIDCAutoCreateEnabled() {
+ org, err := a.resolveOIDCOrg(tx, gothUser.RawData)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: resolve org for auto-join: %w", err))
+ return
+ }
+ if org != nil {
+ role := "user"
+ if mappedRole != "" {
+ role = mappedRole
+ }
+ if _, err := repositories.OrganizationRepository.AddUser(tx, org.Id, user.Id, role); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: auto-join org: %w", err))
+ return
+ }
+ needsSetup = false
+ }
+ } else if mappedRole != "" && !needsSetup {
+ for _, m := range memberships {
+ if m.Role == "owner" {
+ continue
+ }
+ if err := repositories.OrganizationRepository.UpdateUserRole(tx, m.Id, user.Id, mappedRole); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: sync mapped role: %w", err))
+ return
+ }
+ }
+ }
+
jwt, err := services.GenerateToken(user.Id, user.Email)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: generate JWT: %w", err))
@@ -127,7 +173,8 @@ func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothU
return existing, nil
}
- if config.Config.CloudMode != "true" {
+ oidcAutoCreate := provider == "oidc" && services.OAuthService.OIDCAutoCreateEnabled()
+ if config.Config.CloudMode != "true" && !oidcAutoCreate {
hasOrg, err := repositories.OrganizationRepository.HasOrganizations(tracewayTx)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: count orgs: %w", err))
@@ -152,6 +199,7 @@ func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothU
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: create user: %w", err))
return nil, err
}
+
return created, nil
}
@@ -271,4 +319,28 @@ func (a oauthController) redirectError(c *gin.Context, code string) {
c.Redirect(http.StatusSeeOther, target)
}
+func (a oauthController) resolveOIDCOrg(tx *sql.Tx, rawData map[string]interface{}) (*models.Organization, error) {
+ if claim := services.OAuthService.OIDCOrgClaim(); claim != "" {
+ if val, ok := rawData[claim]; ok {
+ if orgName, ok := val.(string); ok && orgName != "" {
+ org, err := repositories.OrganizationRepository.FindByName(tx, orgName)
+ if err != nil {
+ return nil, err
+ }
+ if org != nil {
+ return org, nil
+ }
+ }
+ }
+ }
+ return repositories.OrganizationRepository.FindFirst(tx)
+}
+
+func externalToGothProvider(provider string) string {
+ if provider == "oidc" {
+ return "openid-connect"
+ }
+ return provider
+}
+
var OAuthController = oauthController{}
diff --git a/backend/app/repositories/organization.repository.go b/backend/app/repositories/organization.repository.go
index 3a711b2b..c239eb67 100644
--- a/backend/app/repositories/organization.repository.go
+++ b/backend/app/repositories/organization.repository.go
@@ -44,6 +44,21 @@ func (r *organizationRepository) HasOrganizations(tx *sql.Tx) (bool, error) {
return result.Count > 0, nil
}
+func (r *organizationRepository) FindFirst(tx *sql.Tx) (*models.Organization, error) {
+ return lit.SelectSingle[models.Organization](
+ tx,
+ "SELECT id, name, timezone, created_at FROM organizations ORDER BY created_at ASC LIMIT 1",
+ )
+}
+
+func (r *organizationRepository) FindByName(tx *sql.Tx, name string) (*models.Organization, error) {
+ return lit.SelectSingleNamed[models.Organization](
+ tx,
+ "SELECT id, name, timezone, created_at FROM organizations WHERE name = :name LIMIT 1",
+ lit.P{"name": name},
+ )
+}
+
func (r *organizationRepository) FindById(tx *sql.Tx, id int) (*models.Organization, error) {
return lit.SelectSingleNamed[models.Organization](
tx,
diff --git a/backend/app/services/oauth.service.go b/backend/app/services/oauth.service.go
index 03fa0768..502cea78 100644
--- a/backend/app/services/oauth.service.go
+++ b/backend/app/services/oauth.service.go
@@ -1,21 +1,32 @@
package services
import (
+ "encoding/json"
+ "fmt"
+ "net"
"net/http"
"strings"
"github.com/tracewayapp/traceway/backend/app/config"
+ traceway "go.tracewayapp.com"
"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"
+ "github.com/markbates/goth/providers/openidConnect"
)
type oauthService struct {
- googleEnabled bool
- githubEnabled bool
+ googleEnabled bool
+ githubEnabled bool
+ oidcEnabled bool
+ oidcDisplayName string
+ oidcAutoCreate bool
+ oidcOrgClaim string
+ oidcRoleClaim string
+ oidcRoleMap map[string]string
}
var OAuthService *oauthService
@@ -23,29 +34,44 @@ var OAuthService *oauthService
func InitOAuth() {
cfg := config.Config
+ hasManualEndpoints := cfg.OIDCAuthURL != "" && cfg.OIDCTokenURL != "" && cfg.OIDCUserInfoURL != ""
+ oidcCredentialsSet := cfg.OIDCClientID != "" && cfg.OIDCClientSecret != ""
+
svc := &oauthService{
- googleEnabled: cfg.GoogleClientID != "" && cfg.GoogleClientSecret != "",
- githubEnabled: cfg.GitHubClientID != "" && cfg.GitHubClientSecret != "",
+ googleEnabled: cfg.GoogleClientID != "" && cfg.GoogleClientSecret != "",
+ githubEnabled: cfg.GitHubClientID != "" && cfg.GitHubClientSecret != "",
+ oidcEnabled: oidcCredentialsSet && (cfg.OIDCDiscoveryURL != "" || hasManualEndpoints),
+ oidcDisplayName: cfg.OIDCDisplayName,
+ oidcAutoCreate: cfg.OIDCAutoCreateUsers == "true",
+ oidcOrgClaim: cfg.OIDCOrgClaim,
+ oidcRoleClaim: cfg.OIDCRoleClaim,
}
OAuthService = svc
- if !svc.googleEnabled && !svc.githubEnabled {
+ if cfg.OIDCRoleClaim != "" && cfg.OIDCRoleMap != "" {
+ if err := json.Unmarshal([]byte(cfg.OIDCRoleMap), &svc.oidcRoleMap); err != nil {
+ traceway.CaptureException(fmt.Errorf("OIDC_ROLE_MAP is not valid JSON, role mapping disabled: %w", err))
+ }
+ }
+
+ if !svc.googleEnabled && !svc.githubEnabled && !svc.oidcEnabled {
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
+ store := sessions.NewFilesystemStore("", []byte(secret))
+ store.MaxLength(0)
+ store.Options = &sessions.Options{
+ Path: "/",
+ HttpOnly: true,
+ MaxAge: 600,
+ Secure: strings.HasPrefix(cfg.AppBaseURL, "https://"),
+ SameSite: http.SameSiteLaxMode,
+ }
gothic.Store = store
providers := []goth.Provider{}
@@ -66,11 +92,82 @@ func InitOAuth() {
"user:email",
))
}
+ if svc.oidcEnabled {
+ scopes := []string{"openid", "email", "profile"}
+ for _, s := range strings.Split(cfg.OIDCExtraScopes, ",") {
+ if s = strings.TrimSpace(s); s != "" {
+ scopes = append(scopes, s)
+ }
+ }
+
+ discoveryURL := cfg.OIDCDiscoveryURL
+ if discoveryURL == "" && hasManualEndpoints {
+ srv, addr := newSyntheticDiscoveryServer(cfg.OIDCAuthURL, cfg.OIDCTokenURL, cfg.OIDCUserInfoURL)
+ if srv != nil {
+ defer srv.Close()
+ discoveryURL = addr
+ }
+ }
+
+ if discoveryURL == "" {
+ svc.oidcEnabled = false
+ } else {
+ oidcProvider, err := openidConnect.New(
+ cfg.OIDCClientID,
+ cfg.OIDCClientSecret,
+ base+"/api/auth/callback/oidc",
+ discoveryURL,
+ scopes...,
+ )
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("OIDC provider init failed (discovery URL may be unreachable): %w", err))
+ svc.oidcEnabled = false
+ } else {
+ providers = append(providers, oidcProvider)
+ }
+ }
+ }
goth.UseProviders(providers...)
}
+func newSyntheticDiscoveryServer(authURL, tokenURL, userInfoURL string) (*http.Server, string) {
+ issuer := extractURLOrigin(authURL)
+ doc, _ := json.Marshal(map[string]string{
+ "issuer": issuer,
+ "authorization_endpoint": authURL,
+ "token_endpoint": tokenURL,
+ "userinfo_endpoint": userInfoURL,
+ })
+
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("OIDC manual-endpoint: failed to start discovery server: %w", err))
+ return nil, ""
+ }
+
+ srv := &http.Server{
+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Write(doc)
+ }),
+ }
+ go srv.Serve(ln)
+
+ return srv, "http://" + ln.Addr().String()
+}
+
+func extractURLOrigin(rawURL string) string {
+ if i := strings.Index(rawURL, "://"); i != -1 {
+ rest := rawURL[i+3:]
+ if j := strings.Index(rest, "/"); j != -1 {
+ return rawURL[:i+3+j]
+ }
+ }
+ return rawURL
+}
+
func (s *oauthService) IsEnabled() bool {
- return s.googleEnabled || s.githubEnabled
+ return s.googleEnabled || s.githubEnabled || s.oidcEnabled
}
func (s *oauthService) IsProviderEnabled(name string) bool {
@@ -79,6 +176,8 @@ func (s *oauthService) IsProviderEnabled(name string) bool {
return s.googleEnabled
case "github":
return s.githubEnabled
+ case "oidc":
+ return s.oidcEnabled
}
return false
}
@@ -91,5 +190,72 @@ func (s *oauthService) EnabledProviders() []string {
if s.githubEnabled {
out = append(out, "github")
}
+ if s.oidcEnabled {
+ out = append(out, "oidc")
+ }
return out
}
+
+func (s *oauthService) OIDCAutoCreateEnabled() bool {
+ return s.oidcAutoCreate
+}
+
+func (s *oauthService) OIDCDisplayName() string {
+ return s.oidcDisplayName
+}
+
+func (s *oauthService) OIDCOrgClaim() string {
+ return s.oidcOrgClaim
+}
+
+func (s *oauthService) OIDCRoleClaimEnabled() bool {
+ return s.oidcRoleClaim != "" && len(s.oidcRoleMap) > 0
+}
+
+func (s *oauthService) ResolveRole(rawData map[string]interface{}) string {
+ value := resolveClaimPath(rawData, s.oidcRoleClaim)
+ claimValues := normalizeClaimToStrings(value)
+
+ rolePriority := map[string]int{"admin": 3, "user": 2, "readonly": 1}
+ bestPriority := 0
+ bestRole := ""
+
+ for _, cv := range claimValues {
+ if role, ok := s.oidcRoleMap[cv]; ok {
+ if p := rolePriority[role]; p > bestPriority {
+ bestPriority = p
+ bestRole = role
+ }
+ }
+ }
+ return bestRole
+}
+
+func resolveClaimPath(data map[string]interface{}, path string) interface{} {
+ parts := strings.Split(path, ".")
+ var current interface{} = data
+ for _, part := range parts {
+ m, ok := current.(map[string]interface{})
+ if !ok {
+ return nil
+ }
+ current = m[part]
+ }
+ return current
+}
+
+func normalizeClaimToStrings(v interface{}) []string {
+ switch val := v.(type) {
+ case string:
+ return []string{val}
+ case []interface{}:
+ out := make([]string, 0, len(val))
+ for _, item := range val {
+ if s, ok := item.(string); ok {
+ out = append(out, s)
+ }
+ }
+ return out
+ }
+ return nil
+}
diff --git a/backend/app/services/oauth_service_test.go b/backend/app/services/oauth_service_test.go
new file mode 100644
index 00000000..c71d2600
--- /dev/null
+++ b/backend/app/services/oauth_service_test.go
@@ -0,0 +1,237 @@
+package services
+
+import "testing"
+
+func TestResolveClaimPath(t *testing.T) {
+ tests := []struct {
+ name string
+ data map[string]interface{}
+ path string
+ want interface{}
+ }{
+ {
+ name: "flat key",
+ data: map[string]interface{}{"role": "admin"},
+ path: "role",
+ want: "admin",
+ },
+ {
+ name: "nested dot notation",
+ data: map[string]interface{}{
+ "realm_access": map[string]interface{}{
+ "roles": []interface{}{"traceway-admin", "offline_access"},
+ },
+ },
+ path: "realm_access.roles",
+ want: []interface{}{"traceway-admin", "offline_access"},
+ },
+ {
+ name: "missing intermediate key",
+ data: map[string]interface{}{"a": map[string]interface{}{}},
+ path: "a.b.c",
+ want: nil,
+ },
+ {
+ name: "non-map intermediate",
+ data: map[string]interface{}{"a": "string"},
+ path: "a.b",
+ want: nil,
+ },
+ {
+ name: "missing top-level key",
+ data: map[string]interface{}{},
+ path: "groups",
+ want: nil,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := resolveClaimPath(tt.data, tt.path)
+ if !deepEqual(got, tt.want) {
+ t.Errorf("resolveClaimPath(%v, %q) = %v, want %v", tt.data, tt.path, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestNormalizeClaimToStrings(t *testing.T) {
+ tests := []struct {
+ name string
+ v interface{}
+ want []string
+ }{
+ {
+ name: "string value",
+ v: "admin",
+ want: []string{"admin"},
+ },
+ {
+ name: "string slice",
+ v: []interface{}{"admin", "user"},
+ want: []string{"admin", "user"},
+ },
+ {
+ name: "mixed slice drops non-strings",
+ v: []interface{}{"admin", 42, nil, "readonly"},
+ want: []string{"admin", "readonly"},
+ },
+ {
+ name: "empty slice",
+ v: []interface{}{},
+ want: []string{},
+ },
+ {
+ name: "nil returns nil",
+ v: nil,
+ want: nil,
+ },
+ {
+ name: "unsupported type returns nil",
+ v: map[string]interface{}{"x": "y"},
+ want: nil,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := normalizeClaimToStrings(tt.v)
+ if len(got) != len(tt.want) {
+ t.Errorf("normalizeClaimToStrings(%v) = %v, want %v", tt.v, got, tt.want)
+ return
+ }
+ for i := range got {
+ if got[i] != tt.want[i] {
+ t.Errorf("normalizeClaimToStrings(%v)[%d] = %q, want %q", tt.v, i, got[i], tt.want[i])
+ }
+ }
+ })
+ }
+}
+
+func TestResolveRole(t *testing.T) {
+ svc := &oauthService{
+ oidcRoleClaim: "realm_access.roles",
+ oidcRoleMap: map[string]string{
+ "kc-admin": "admin",
+ "kc-user": "user",
+ "kc-readonly": "readonly",
+ },
+ }
+
+ tests := []struct {
+ name string
+ rawData map[string]interface{}
+ want string
+ }{
+ {
+ name: "maps single matching role",
+ rawData: map[string]interface{}{
+ "realm_access": map[string]interface{}{
+ "roles": []interface{}{"kc-admin"},
+ },
+ },
+ want: "admin",
+ },
+ {
+ name: "highest priority wins",
+ rawData: map[string]interface{}{
+ "realm_access": map[string]interface{}{
+ "roles": []interface{}{"kc-readonly", "kc-admin", "kc-user"},
+ },
+ },
+ want: "admin",
+ },
+ {
+ name: "no matching roles returns empty string",
+ rawData: map[string]interface{}{
+ "realm_access": map[string]interface{}{
+ "roles": []interface{}{"some-other-role"},
+ },
+ },
+ want: "",
+ },
+ {
+ name: "missing claim returns empty string",
+ rawData: map[string]interface{}{},
+ want: "",
+ },
+ {
+ name: "maps readonly",
+ rawData: map[string]interface{}{
+ "realm_access": map[string]interface{}{
+ "roles": []interface{}{"kc-readonly"},
+ },
+ },
+ want: "readonly",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := svc.ResolveRole(tt.rawData)
+ if got != tt.want {
+ t.Errorf("ResolveRole() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestResolveRoleFlatClaim(t *testing.T) {
+ svc := &oauthService{
+ oidcRoleClaim: "groups",
+ oidcRoleMap: map[string]string{"/admins": "admin", "/users": "user"},
+ }
+
+ rawData := map[string]interface{}{
+ "groups": []interface{}{"/admins", "/users"},
+ }
+ got := svc.ResolveRole(rawData)
+ if got != "admin" {
+ t.Errorf("ResolveRole() = %q, want %q", got, "admin")
+ }
+}
+
+func TestExtractURLOrigin(t *testing.T) {
+ tests := []struct {
+ input string
+ want string
+ }{
+ {"https://keycloak.example.com/realms/myrealm/protocol/openid-connect/auth", "https://keycloak.example.com"},
+ {"http://localhost:8080/auth", "http://localhost:8080"},
+ {"https://example.com", "https://example.com"},
+ {"not-a-url", "not-a-url"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got := extractURLOrigin(tt.input)
+ if got != tt.want {
+ t.Errorf("extractURLOrigin(%q) = %q, want %q", tt.input, got, tt.want)
+ }
+ })
+ }
+}
+
+func deepEqual(a, b interface{}) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ aSlice, aIsSlice := a.([]interface{})
+ bSlice, bIsSlice := b.([]interface{})
+ if aIsSlice && bIsSlice {
+ if len(aSlice) != len(bSlice) {
+ return false
+ }
+ for i := range aSlice {
+ if !deepEqual(aSlice[i], bSlice[i]) {
+ return false
+ }
+ }
+ return true
+ }
+ return a == b
+}
diff --git a/docs/pages/learn/sso.mdx b/docs/pages/learn/sso.mdx
index de2afea3..fabc8cd2 100644
--- a/docs/pages/learn/sso.mdx
+++ b/docs/pages/learn/sso.mdx
@@ -1,6 +1,6 @@
# Single Sign-On (SSO)
-Traceway supports signing in with **Google** and **GitHub** in addition to email + password. SSO is optional — if you don't configure a provider, only its `Continue with …` button is hidden, the rest of the dashboard works exactly the same.
+Traceway supports signing in with **Google**, **GitHub**, and any **standards-compliant OIDC provider** (Authentik, Keycloak, Dex, Okta, etc.) in addition to email + password. SSO is optional — if you don't configure a provider, only its `Continue with …` button is hidden, the rest of the dashboard works exactly the same.
When at least one provider is configured, the buttons appear on the login and register pages, the backend exposes `GET /api/auth/providers`, and `GET /api/auth/start/{provider}` kicks off the OAuth flow.
@@ -26,18 +26,33 @@ Sign-in matching, in order:
In **self-hosted mode** (`CLOUD_MODE` unset or not `true`), once any organization exists, OAuth signups for unknown emails are blocked with `invite_required` — they have to be invited to the org first, just like password signups. In cloud mode (`CLOUD_MODE=true`), OAuth signups always create an account and prompt the user through `/finish-setup`.
-## Environment variables
+The OIDC provider can bypass this restriction with `OIDC_AUTO_CREATE_USERS=true` — see below.
-Set these on the backend container/process. Both pairs are independent — you can configure one provider, both, or neither.
+## Environment variables
-| Variable | Required when | Description |
-| ---------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `APP_BASE_URL` | Either provider configured | Public URL of your Traceway instance, e.g. `https://traceway.example.com`. Used to build the OAuth callback URL the providers redirect back to. |
-| `GOOGLE_CLIENT_ID` | Enabling Google | OAuth client ID from Google Cloud Console |
-| `GOOGLE_CLIENT_SECRET` | Enabling Google | OAuth client secret from Google Cloud Console |
-| `GITHUB_CLIENT_ID` | Enabling GitHub | OAuth App client ID from GitHub |
-| `GITHUB_CLIENT_SECRET` | Enabling GitHub | OAuth App client secret from GitHub |
-| `OAUTH_SESSION_SECRET` | Optional | Cookie-store signing secret used during the OAuth round-trip. Falls back to `JWT_SECRET` when unset. Set explicitly to rotate cookie-signing independently from JWTs. |
+Set these on the backend container/process. All provider pairs are independent — configure one, several, or none.
+
+| Variable | Required when | Description |
+| ------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `APP_BASE_URL` | Any provider configured | Public URL of your Traceway instance, e.g. `https://traceway.example.com`. Used to build the OAuth callback URL the providers redirect back to. |
+| `GOOGLE_CLIENT_ID` | Enabling Google | OAuth client ID from Google Cloud Console |
+| `GOOGLE_CLIENT_SECRET` | Enabling Google | OAuth client secret from Google Cloud Console |
+| `GITHUB_CLIENT_ID` | Enabling GitHub | OAuth App client ID from GitHub |
+| `GITHUB_CLIENT_SECRET` | Enabling GitHub | OAuth App client secret from GitHub |
+| `OIDC_CLIENT_ID` | Enabling OIDC | Client ID from your OIDC provider |
+| `OIDC_CLIENT_SECRET` | Enabling OIDC | Client secret from your OIDC provider |
+| `OIDC_DISCOVERY_URL` | Enabling OIDC (discovery) | Full URL to the provider's OpenID Connect discovery document (usually ends in `/.well-known/openid-configuration`). Either this or all three `OIDC_*_URL` vars below must be set. |
+| `OIDC_AUTH_URL` | Enabling OIDC (manual) | Authorization endpoint URL. Use when your provider does not support OIDC discovery. Requires `OIDC_TOKEN_URL` and `OIDC_USER_INFO_URL` too. |
+| `OIDC_TOKEN_URL` | Enabling OIDC (manual) | Token endpoint URL. See `OIDC_AUTH_URL`. |
+| `OIDC_USER_INFO_URL` | Enabling OIDC (manual) | UserInfo endpoint URL. See `OIDC_AUTH_URL`. |
+| `OIDC_DISPLAY_NAME` | Optional | Label shown on the login/register button. Defaults to `SSO` if unset. |
+| `OIDC_AUTO_CREATE_USERS` | Optional | Set `true` to allow automatic account creation and org membership for unknown emails in self-hosted mode. See [Auto-creating OIDC users](#auto-creating-oidc-users). |
+| `OIDC_ORG_CLAIM` | Optional | Multi-org only. Name of a custom claim in the ID token whose value is the Traceway organization name to join. Falls back to the first organization if unset or the claim is absent. See [Routing users to organizations](#routing-users-to-organizations). |
+| `OIDC_EXTRA_SCOPES` | Optional | Comma-separated list of additional OAuth scopes to request. Required when using `OIDC_ORG_CLAIM` so the provider includes the custom claim in the token (e.g. `traceway`). |
+| `OIDC_ROLE_CLAIM` | Optional | Dot-notation path to the claim in the ID token that holds the user's role(s), e.g. `realm_access.roles` or `groups`. See [Role mapping](#role-mapping). |
+| `OIDC_ROLE_MAP` | Optional | JSON object mapping claim values to Traceway roles (`admin`, `user`, `readonly`), e.g. `{"kc-admin":"admin","kc-ro":"readonly"}`. See [Role mapping](#role-mapping). |
+| `OAUTH_SESSION_SECRET` | Optional | Cookie-store signing secret used during the OAuth round-trip. Falls back to `JWT_SECRET` when unset. Set explicitly to rotate cookie-signing independently from JWTs. |
+| `DISABLE_PASSWORD_LOGIN` | Optional | Set `true` to hide the email/password form and block the `/api/login` and `/api/register` endpoints. Users can only sign in via a configured SSO provider. See [Forcing SSO-only login](#forcing-sso-only-login). |
The cookie used during the round-trip is automatically marked `Secure` when `APP_BASE_URL` starts with `https://`, and `SameSite=Lax` either way.
@@ -88,20 +103,268 @@ The SDK requests the `user:email` scope, so the user's primary email needs to be
6. Restart the backend.
+## Setting up a generic OIDC provider
+
+Any provider that implements OpenID Connect works: Authentik, Keycloak, Dex, Okta, and others. The steps below use **Authentik** as a worked example, but the redirect URI and discovery URL patterns are the same for all compliant providers.
+
+### Creating the application in Authentik
+
+1. In the Authentik admin UI, go to **Applications → Providers → Create**.
+2. Choose **OAuth2/OpenID Connect Provider**.
+3. Configure it:
+ - **Name** — e.g. `traceway`.
+ - **Client type** — **Confidential**.
+ - **Client ID / Client Secret** — Authentik generates these; copy them.
+ - **Redirect URIs** — add exactly: `{APP_BASE_URL}/api/auth/callback/oidc`
+ (e.g. `https://traceway.example.com/api/auth/callback/oidc`). No trailing slash.
+ - **Scopes** — ensure `openid`, `email`, and `profile` are selected.
+4. Go to **Applications → Create** and link the provider you just created.
+
+### Finding the discovery URL
+
+In Authentik the discovery URL follows this pattern:
+
+```
+https://{authentik-host}/application/o/{app-slug}/.well-known/openid-configuration
+```
+
+For example:
+
+```
+https://auth.example.com/application/o/traceway/.well-known/openid-configuration
+```
+
+Open it in a browser to confirm it returns a JSON document — this is the URL you set as `OIDC_DISCOVERY_URL`.
+
+### Environment variables
+
+```
+APP_BASE_URL=https://traceway.example.com
+OIDC_CLIENT_ID=<client id from Authentik>
+OIDC_CLIENT_SECRET=<client secret from Authentik>
+OIDC_DISCOVERY_URL=https://auth.example.com/application/o/traceway/.well-known/openid-configuration
+OIDC_DISPLAY_NAME=Authentik SSO
+```
+
+Restart the backend. The discovery document is fetched once at startup; if the URL is unreachable the OIDC provider is disabled and an error is logged.
+
+## Setting up Keycloak
+
+Keycloak is a popular open-source identity provider. The setup follows the same pattern as other OIDC providers, with realm-based URLs.
+
+### Creating the client in Keycloak
+
+1. In the Keycloak admin console, select your realm (or create one).
+2. Go to **Clients → Create client**.
+3. Configure it:
+ - **Client type** — **OpenID Connect**.
+ - **Client ID** — e.g. `traceway`.
+ - **Client authentication** — **On** (makes it a confidential client).
+4. On the **Settings** tab:
+ - **Valid redirect URIs** — add `{APP_BASE_URL}/api/auth/callback/oidc` (e.g. `https://traceway.example.com/api/auth/callback/oidc`).
+ - **Web origins** — add your `APP_BASE_URL`.
+5. On the **Credentials** tab, copy the **Client secret**.
+
+### Discovery URL
+
+Keycloak exposes a per-realm discovery document at:
+
+```
+https://{keycloak-host}/realms/{realm}/.well-known/openid-configuration
+```
+
+For example:
+
+```
+https://keycloak.example.com/realms/myrealm/.well-known/openid-configuration
+```
+
+Open it in a browser to confirm it returns JSON before setting it as `OIDC_DISCOVERY_URL`.
+
+### Environment variables
+
+```
+APP_BASE_URL=https://traceway.example.com
+OIDC_CLIENT_ID=traceway
+OIDC_CLIENT_SECRET=<client secret from Keycloak>
+OIDC_DISCOVERY_URL=https://keycloak.example.com/realms/myrealm/.well-known/openid-configuration
+OIDC_DISPLAY_NAME=Keycloak SSO
+```
+
+Restart the backend.
+
+## Auto-creating OIDC users
+
+By default, OIDC follows the same rules as Google and GitHub: in self-hosted mode, once an organization exists, unknown emails get `invite_required`. Set `OIDC_AUTO_CREATE_USERS=true` to bypass this:
+
+```
+OIDC_AUTO_CREATE_USERS=true
+```
+
+With this flag, any user who authenticates successfully via OIDC is automatically:
+- Given a Traceway account (if they don't have one yet), and
+- Added to a Traceway organization with the `user` role (or the role resolved by `OIDC_ROLE_MAP` if configured — see [Role mapping](#role-mapping)).
+
+This applies on every sign-in, not just the first — so existing accounts that were created before this flag was set will also be joined to the organization on their next login.
+
+On a **single-organization** instance this is all you need. No additional configuration is required.
+
+Do not enable this on a public-facing instance with an external OIDC provider unless you want anyone with a valid OIDC account to be able to register.
+
+## Role mapping
+
+By default, OIDC users are added to organizations with the `user` role. Role mapping lets you automatically assign Traceway roles based on claims in the OIDC token — useful for enterprise IAM systems like Keycloak where group or role membership is already managed centrally.
+
+Two env vars control this:
+
+| Variable | Example value | Description |
+| ----------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
+| `OIDC_ROLE_CLAIM` | `realm_access.roles` | Dot-notation path to the claim holding the role value(s). Supports nested objects and string arrays. |
+| `OIDC_ROLE_MAP` | `{"traceway-admin":"admin","traceway-ro":"readonly"}` | JSON object mapping claim values to Traceway roles (`admin`, `user`, or `readonly`). |
+
+Role mapping is applied on **every login**, not just the first — so changing a user's role in your IdP takes effect on their next sign-in.
+
+**Priority order:** When a user has multiple claim values that match different roles, the highest-privilege match wins: `admin` > `user` > `readonly`. The `owner` role is never assigned automatically — it can only be set manually by an existing owner.
+
+### Keycloak example — realm roles
+
+Keycloak includes realm-level roles in the token under `realm_access.roles`:
+
+```json
+{
+ "realm_access": {
+ "roles": ["traceway-admin", "offline_access", "uma_authorization"]
+ }
+}
+```
+
+To map `traceway-admin` to the Traceway `admin` role:
+
+```
+OIDC_ROLE_CLAIM=realm_access.roles
+OIDC_ROLE_MAP={"traceway-admin":"admin","traceway-user":"user","traceway-readonly":"readonly"}
+```
+
+Create matching realm roles in Keycloak (**Realm Settings → Roles → Create role**) and assign them to users or groups.
+
+### Generic example — groups claim
+
+Many providers expose group membership as a top-level `groups` claim:
+
+```json
+{
+ "groups": ["/admins", "/users"]
+}
+```
+
+```
+OIDC_ROLE_CLAIM=groups
+OIDC_ROLE_MAP={"/admins":"admin","/users":"user"}
+```
+
+### Adding the claim in Authentik
+
+Authentik doesn't include role or group claims by default. Add them via a scope mapping:
+
+1. Go to **Customization → Property Mappings → Create → Scope Mapping**.
+2. Set the **Scope name** to a custom scope (e.g. `traceway`).
+3. Set the **Expression** to return the claim:
+ ```python
+ return {"groups": [g.name for g in request.user.ak_groups.all()]}
+ ```
+4. Add `traceway` to your provider's scope list and to `OIDC_EXTRA_SCOPES`:
+ ```
+ OIDC_EXTRA_SCOPES=traceway
+ OIDC_ROLE_CLAIM=groups
+ OIDC_ROLE_MAP={"traceway-admins":"admin","traceway-users":"user"}
+ ```
+
+## Routing users to organizations
+
+> This section only applies to **multi-organization** instances. If you have one organization, `OIDC_AUTO_CREATE_USERS=true` is sufficient — users are automatically added to it.
+
+By default, auto-created OIDC users are added to the first organization in the instance. To route users to a specific organization on a multi-org instance, use a custom claim in the ID token:
+
+**Step 1** — Set `OIDC_ORG_CLAIM` to the name of the claim that will carry the organization name:
+
+```
+OIDC_ORG_CLAIM=traceway_org
+```
+
+**Step 2** — Set `OIDC_EXTRA_SCOPES` to the scope that exposes the claim (so Traceway requests it from the provider):
+
+```
+OIDC_EXTRA_SCOPES=traceway
+```
+
+**Step 3** — Configure your OIDC provider to include the claim in the token (see below).
+
+When a user signs in, Traceway reads the `traceway_org` claim from the ID token and looks up the organization by name. If the claim is absent or the name doesn't match any organization, it falls back to the first organization.
+
+The organization name in the claim must exactly match the name in Traceway — it is case-sensitive.
+
+### Adding the claim in Authentik
+
+1. Go to **Customization → Property Mappings → Create → Scope Mapping**.
+2. Set the **Scope name** to `traceway` (must match `OIDC_EXTRA_SCOPES`).
+3. Set the **Expression** to return the claim:
+ ```python
+ return {"traceway_org": "My Organization Name"}
+ ```
+ You can make this dynamic per-user using Authentik's expression variables (e.g. `request.user.ak_groups.all()`).
+4. Go to your Traceway OIDC provider → **Advanced protocol settings → Scopes** and add `traceway` to the list alongside `openid email profile`.
+
+This works identically with any OIDC-compliant provider — Keycloak, Okta, Dex, and others all support custom claims via their own claim/attribute mapping configuration.
+
+## Providers without OIDC discovery
+
+Most modern OIDC providers support the discovery document at `/.well-known/openid-configuration`. For providers that don't, you can specify the three endpoint URLs directly instead of `OIDC_DISCOVERY_URL`:
+
+```
+OIDC_CLIENT_ID=traceway
+OIDC_CLIENT_SECRET=<secret>
+OIDC_AUTH_URL=https://provider.example.com/oauth/authorize
+OIDC_TOKEN_URL=https://provider.example.com/oauth/token
+OIDC_USER_INFO_URL=https://provider.example.com/oauth/userinfo
+```
+
+All three manual URLs must be set together — you cannot mix them with `OIDC_DISCOVERY_URL`. If `OIDC_DISCOVERY_URL` is set, it takes precedence and the manual URLs are ignored.
+
+## Forcing SSO-only login
+
+Set `DISABLE_PASSWORD_LOGIN=true` to remove the email/password form entirely and require all users to authenticate via a configured SSO provider:
+
+```
+DISABLE_PASSWORD_LOGIN=true
+```
+
+With this flag:
+- The email/password form is hidden on the login and register pages.
+- `POST /api/login` and `POST /api/register` return `403 Forbidden` — existing scripts or integrations that use password auth will fail explicitly rather than silently.
+- The "or" divider between SSO buttons and the password form is also removed.
+
+On a self-hosted instance with no organizations yet, the first user is created and onboarded through the SSO flow (via `/finish-setup`) rather than the register page. Pair this with `OIDC_AUTO_CREATE_USERS=true` so the first login automatically provisions the account without needing an invitation.
+
## Verifying
After restart:
```bash
curl https://traceway.example.com/api/auth/providers
-# {"providers":["google","github"]}
+# {"providers":["google","github","oidc"],"providerLabels":{"oidc":"Authentik SSO"},"passwordLoginEnabled":true}
```
-If the array is empty, the backend didn't see your env vars. Common causes:
+`passwordLoginEnabled` is `false` when `DISABLE_PASSWORD_LOGIN=true`.
+
+If the `oidc` entry is missing but you set the env vars, check the backend logs — a failed discovery URL fetch is logged at startup. Common causes:
+
+- The discovery URL is wrong or the OIDC provider is not reachable from the backend container at startup.
+- Only some of the required OIDC vars are set. Either `OIDC_DISCOVERY_URL` or all three of `OIDC_AUTH_URL` + `OIDC_TOKEN_URL` + `OIDC_USER_INFO_URL` must be provided, together with `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`.
+
+If the array is empty for all providers, the backend didn't see your env vars. Common causes:
- The container was started before the secrets were set — recreate, don't just restart.
- The variables were set in a different shell than the one that launched `go run` / `docker run`.
-- For embedded backend usage (`cmd.Run(opts...)`), the option-mode config path doesn't read OS env vars — set them at the call site or use the no-options form.
Once `/api/auth/providers` reports the providers, the buttons appear automatically on the login and register pages.
@@ -121,3 +384,4 @@ The OAuth callback redirects back to `/login?error=<code>` when something goes w
- The transient cookie used by gothic during the round-trip is `HttpOnly`, `SameSite=Lax`, and 10-minute lifetime. It only carries the OAuth state and PKCE verifier — never a long-lived session.
- `OAUTH_SESSION_SECRET` rotates the cookie signing key. Rotating it invalidates any in-flight OAuth round-trips but does not affect issued JWTs (those are signed with `JWT_SECRET`).
- An OAuth-only user has an empty password hash. Password login for them always fails — `CheckPassword` short-circuits on empty hashes.
+- Role mapping (`OIDC_ROLE_MAP`) never elevates a user to `owner` — that role can only be assigned manually by an existing owner.
diff --git a/frontend/src/lib/components/oauth-buttons.svelte b/frontend/src/lib/components/oauth-buttons.svelte
index aa85ddfa..a128054e 100644
--- a/frontend/src/lib/components/oauth-buttons.svelte
+++ b/frontend/src/lib/components/oauth-buttons.svelte
@@ -2,8 +2,10 @@
import { Button } from "$lib/components/ui/button";
import { onMount } from 'svelte';
+ let { passwordLoginEnabled = $bindable(true), loaded = $bindable(false) } = $props();
+
let providers = $state<string[]>([]);
- let loaded = $state(false);
+ let providerLabels = $state<Record<string, string>>({});
onMount(async () => {
try {
@@ -11,6 +13,8 @@
if (response.ok) {
const data = await response.json();
providers = data.providers || [];
+ providerLabels = data.providerLabels || {};
+ passwordLoginEnabled = data.passwordLoginEnabled ?? true;
}
} catch {
providers = [];
@@ -23,10 +27,13 @@
window.location.href = `/api/auth/start/${provider}`;
}
- const labels: Record<string, string> = {
- google: 'Continue with Google',
- github: 'Continue with GitHub',
- };
+ function getLabel(provider: string): string {
+ if (provider === 'google') return 'Continue with Google';
+ if (provider === 'github') return 'Continue with GitHub';
+ const custom = providerLabels[provider];
+ if (provider === 'oidc') return `Continue with ${custom ?? 'SSO'}`;
+ return `Continue with ${custom ?? provider}`;
+ }
</script>
{#if loaded && providers.length > 0}
@@ -50,13 +57,15 @@
<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}`}
+ {getLabel(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>
+ {#if passwordLoginEnabled}
+ <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>
+ {/if}
</div>
{/if}
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte
index 5d59600f..c1223c3b 100644
--- a/frontend/src/routes/login/+page.svelte
+++ b/frontend/src/routes/login/+page.svelte
@@ -32,6 +32,8 @@
let error = $state(initialError ? (ERROR_MESSAGES[initialError] ?? 'Sign-in failed. Please try again.') : '');
let loading = $state(false);
+ let passwordLoginEnabled = $state(true);
+ let providersLoaded = $state(false);
if (initialError) {
const cleanUrl = new URL(window.location.href);
@@ -44,7 +46,9 @@
if (!__CLOUD_MODE__) {
$effect(() => {
- // if we're not in the cloud mode we have to check if an organization exists and if it does not we need to take the user to the register page
+ // Wait for providers to load — if password login is disabled, skip the /register redirect.
+ if (!providersLoaded) return;
+ if (!passwordLoginEnabled) return;
loading = true;
fetch('/api/has-organizations', {
@@ -123,7 +127,8 @@
</AlertDescription>
</Alert>
{/if}
- <OauthButtons />
+ <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />
+ {#if providersLoaded && passwordLoginEnabled}
<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>
@@ -142,6 +147,7 @@
{/if}
</Button>
</form>
+ {/if}
</CardContent>
<!-- If the backend is running in the cloud mode we'll allow registration to take place -->
diff --git a/frontend/src/routes/register/+page.svelte b/frontend/src/routes/register/+page.svelte
index 1ffc9532..6564d395 100644
--- a/frontend/src/routes/register/+page.svelte
+++ b/frontend/src/routes/register/+page.svelte
@@ -34,6 +34,8 @@
let error = $state('');
let loading = $state(false);
let captchaToken = $state('');
+ let passwordLoginEnabled = $state(true);
+ let providersLoaded = $state(false);
const turnstileSiteKey = __TURNSTILE_SITE_KEY__;
const captchaEnabled = turnstileSiteKey !== '';
@@ -42,8 +44,15 @@
if (!__CLOUD_MODE__) {
$effect(() => {
- // if we're not in the cloud mode we have to check if an organization exists and if it does we should go to the login page
+ if (!providersLoaded) return;
+
+ // Password login is disabled — this page is inaccessible, send to login.
+ if (!passwordLoginEnabled) {
+ goto("/login");
+ return;
+ }
+ // if we're not in the cloud mode we have to check if an organization exists and if it does we should go to the login page
loading = true;
fetch('/api/has-organizations', {
method: 'GET',
@@ -146,7 +155,8 @@
</AlertDescription>
</Alert>
{/if}
- <OauthButtons />
+ <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />
+ {#if providersLoaded && passwordLoginEnabled}
<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>
@@ -222,6 +232,7 @@
{/if}
</Button>
</form>
+ {/if}
</CardContent>
{#if __CLOUD_MODE__}