From c615c21af12c418018abc9bc1f1938637b8a5a88 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Noch kein Konto? Registrieren Noch kein Konto? Registrieren
+ Deine Organisation verlangt Zwei-Faktor-Anmeldung.
+ Jetzt einrichten
+ Noch keine Monitore angelegt. ● aktiv ● nicht eingerichtet Deine Organisation verlangt Zwei-Faktor-Anmeldung. Jetzt einrichten Noch keine Monitore angelegt. ● aktiv ● nicht eingerichtet uptimesebi uptimesebi uptimesebi uptimesebi Noch kein Konto? Registrieren
+ { i18n.T(ctx, "auth.login.no_account") }
+ { i18n.T(ctx, "auth.login.to_signup") }
+ { i18n.T(ctx, "auth.signup.to_login") } Code aus der Authenticator-App eingeben. ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = field("Code", "code", "text", "one-time-code", false).Render(ctx, templ_7745c5c3_Buffer)
+ var templ_7745c5c3_Var3 string
+ templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.totp_hint"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 17, Col: 76}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "Monitore
+ Sicherheit
+ Zwei-Faktor (TOTP)
+ if me.TOTP {
+
+
+
+
Monitore
Sicherheit
Zwei-Faktor (TOTP)
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ if me.TOTP {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "{ heading }
+ { children... }
+ ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var6 string
+ templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(heading)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 32, Col: 51}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templ_7745c5c3_Var4.Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "" dynamically.
+func TestEveryLanguageHasAName(t *testing.T) {
+ c, err := Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ en := catalogKeys(t)["en"]
+ for _, l := range c.Supported() {
+ if !en["lang."+l] {
+ t.Errorf("en.json is missing %q", "lang."+l)
+ }
+ }
+}
+
+func TestMatch(t *testing.T) {
+ c, err := Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ tests := []struct {
+ prefs []string
+ want string
+ }{
+ {nil, "en"},
+ {[]string{"de"}, "de"},
+ {[]string{"", "de-AT,en;q=0.5"}, "de"},
+ {[]string{"fr-FR,fr;q=0.9"}, "en"},
+ {[]string{"en", "de"}, "en"},
+ {[]string{"garbage", "de"}, "de"},
+ }
+ for _, tt := range tests {
+ if got := c.Match(tt.prefs...).Lang(); got != tt.want {
+ t.Errorf("Match(%q) = %q, want %q", tt.prefs, got, tt.want)
+ }
+ }
+}
+
+func TestT(t *testing.T) {
+ c, err := Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := NewContext(context.Background(), c.Match("de"))
+ if got, want := T(ctx, "error.password_too_short", "Min", 12), "Das Passwort braucht mindestens 12 Zeichen."; got != want {
+ t.Errorf("T(de, password_too_short) = %q, want %q", got, want)
+ }
+ if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want {
+ t.Errorf("T(missing) = %q, want %q", got, want)
+ }
+ if got, want := T(context.Background(), "auth.login.title"), "auth.login.title"; got != want {
+ t.Errorf("T(no localizer) = %q, want %q", got, want)
+ }
+}
diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json
new file mode 100644
index 0000000..b59be86
--- /dev/null
+++ b/internal/i18n/locales/de.json
@@ -0,0 +1,57 @@
+{
+ "app.network_error": "Verbindung fehlgeschlagen.",
+ "lang.en": "English",
+ "lang.de": "Deutsch",
+
+ "auth.login.title": "Anmelden",
+ "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.",
+ "auth.login.submit": "Weiter",
+ "auth.login.no_account": "Noch kein Konto?",
+ "auth.login.to_signup": "Registrieren",
+ "auth.signup.title": "Konto anlegen",
+ "auth.signup.submit": "Anlegen",
+ "auth.signup.to_login": "Zur Anmeldung",
+ "auth.field.name": "Name",
+ "auth.field.email": "E-Mail",
+ "auth.field.password": "Passwort",
+ "auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)",
+ "auth.field.org_name": "Organisation",
+ "auth.field.org_slug": "Kurzname (a–z, 0–9, -)",
+ "auth.field.code": "Code",
+
+ "console.nav.security": "Sicherheit",
+ "console.nav.logout": "Abmelden",
+ "console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.",
+ "console.totp_missing_action": "Jetzt einrichten",
+ "console.monitors.title": "Monitore",
+ "console.monitors.empty": "Noch keine Monitore angelegt.",
+
+ "security.title": "Sicherheit",
+ "security.totp.heading": "Zwei-Faktor (TOTP)",
+ "security.totp.active": "aktiv",
+ "security.totp.inactive": "nicht eingerichtet",
+ "security.totp.disable": "Deaktivieren",
+ "security.totp.current_code": "Aktueller Code",
+ "security.totp.start": "Einrichten",
+ "security.totp.qr_alt": "QR-Code für die Authenticator-App",
+ "security.totp.app_code": "Code aus der App",
+ "security.totp.confirm": "Bestätigen",
+
+ "error.internal": "Interner Fehler.",
+ "error.invalid_input": "Eingaben prüfen.",
+ "error.rate_limited": "Zu viele Versuche, bitte später erneut.",
+ "error.signup_closed": "Registrierung ist deaktiviert.",
+ "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
+ "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
+ "error.slug_taken": "Dieser Kurzname ist bereits vergeben.",
+ "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.",
+ "error.invalid_credentials": "E-Mail oder Passwort falsch.",
+ "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.",
+ "error.invalid_code": "Code ungültig.",
+ "error.org_not_found": "Organisation nicht gefunden.",
+ "error.totp_already_enabled": "TOTP ist bereits aktiv.",
+ "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
+ "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.",
+ "error.no_password": "Konto ohne Passwort.",
+ "error.unsupported_locale": "Sprache wird nicht unterstützt."
+}
diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json
new file mode 100644
index 0000000..8023c23
--- /dev/null
+++ b/internal/i18n/locales/en.json
@@ -0,0 +1,57 @@
+{
+ "app.network_error": "Connection failed.",
+ "lang.en": "English",
+ "lang.de": "Deutsch",
+
+ "auth.login.title": "Sign in",
+ "auth.login.totp_hint": "Enter the code from your authenticator app.",
+ "auth.login.submit": "Continue",
+ "auth.login.no_account": "No account yet?",
+ "auth.login.to_signup": "Sign up",
+ "auth.signup.title": "Create account",
+ "auth.signup.submit": "Create",
+ "auth.signup.to_login": "Back to sign in",
+ "auth.field.name": "Name",
+ "auth.field.email": "Email",
+ "auth.field.password": "Password",
+ "auth.field.new_password": "Password (min. {{.Min}} characters)",
+ "auth.field.org_name": "Organization",
+ "auth.field.org_slug": "Short name (a–z, 0–9, -)",
+ "auth.field.code": "Code",
+
+ "console.nav.security": "Security",
+ "console.nav.logout": "Sign out",
+ "console.totp_missing": "Your organization requires two-factor sign-in.",
+ "console.totp_missing_action": "Set up now",
+ "console.monitors.title": "Monitors",
+ "console.monitors.empty": "No monitors yet.",
+
+ "security.title": "Security",
+ "security.totp.heading": "Two-factor (TOTP)",
+ "security.totp.active": "active",
+ "security.totp.inactive": "not set up",
+ "security.totp.disable": "Disable",
+ "security.totp.current_code": "Current code",
+ "security.totp.start": "Set up",
+ "security.totp.qr_alt": "QR code for your authenticator app",
+ "security.totp.app_code": "Code from the app",
+ "security.totp.confirm": "Confirm",
+
+ "error.internal": "Internal error.",
+ "error.invalid_input": "Please check your input.",
+ "error.rate_limited": "Too many attempts, please try again later.",
+ "error.signup_closed": "Sign-up is disabled.",
+ "error.password_too_short": "The password needs at least {{.Min}} characters.",
+ "error.email_taken": "This email address is already registered.",
+ "error.slug_taken": "This short name is already taken.",
+ "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.",
+ "error.invalid_credentials": "Wrong email or password.",
+ "error.mfa_expired": "Sign-in expired, please start again.",
+ "error.invalid_code": "Invalid code.",
+ "error.org_not_found": "Organization not found.",
+ "error.totp_already_enabled": "TOTP is already active.",
+ "error.totp_setup_expired": "Setup expired, please start again.",
+ "error.totp_required_by_org": "One of your organizations requires TOTP.",
+ "error.no_password": "This account has no password.",
+ "error.unsupported_locale": "Unsupported language."
+}
--
2.54.1
From dde7b890b8cde9152a03f87cf80347f40ef7fa3b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= ". kv fills placeholders in that message.
+func fail(c *gin.Context, status int, code string, kv ...any) {
+ c.AbortWithStatusJSON(status, apiError{
+ Error: code,
+ Message: i18n.T(c.Request.Context(), "error."+code, kv...),
+ })
}
func internalError(c *gin.Context, err error) {
_ = c.Error(err)
- c.AbortWithStatusJSON(http.StatusInternalServerError, apiError{Error: "internal", Message: "Interner Fehler."})
+ fail(c, http.StatusInternalServerError, "internal")
}
func bind(c *gin.Context, dst any) bool {
- if err := c.ShouldBindJSON(dst); err != nil {
- e := apiError{Error: "invalid_input", Message: "Eingaben prüfen."}
- var ve validator.ValidationErrors
- if errors.As(err, &ve) {
- e.Fields = map[string]string{}
- for _, f := range ve {
- e.Fields[f.Field()] = f.Tag()
- }
- }
- c.AbortWithStatusJSON(http.StatusBadRequest, e)
- return false
+ err := c.ShouldBindJSON(dst)
+ if err == nil {
+ return true
}
- return true
+ e := apiError{Error: "invalid_input", Message: i18n.T(c.Request.Context(), "error.invalid_input")}
+ var ve validator.ValidationErrors
+ if errors.As(err, &ve) {
+ e.Fields = map[string]string{}
+ for _, f := range ve {
+ e.Fields[f.Field()] = f.Tag()
+ }
+ }
+ c.AbortWithStatusJSON(http.StatusBadRequest, e)
+ return false
}
func setCookie(c *gin.Context, name, value string, maxAge int) {
@@ -98,4 +173,12 @@ func setCookie(c *gin.Context, name, value string, maxAge int) {
})
}
-func randomToken() string { return auth.RandomToken() }
+func ptr[T any](v T) *T { return &v }
+
+func deref[T any](p *T) T {
+ var zero T
+ if p == nil {
+ return zero
+ }
+ return *p
+}
diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js
index 3aa3820..9f8fb8b 100644
--- a/internal/web/assets/app.js
+++ b/internal/web/assets/app.js
@@ -8,7 +8,7 @@
window.api = api;
const message = (err) =>
- err.response?.data?.message ?? "Verbindung fehlgeschlagen.";
+ err.response?.data?.message ?? document.body.dataset.msgNetwork;
const showError = (form, text) => {
const el = form.querySelector("[data-error]");
@@ -50,6 +50,12 @@
});
document.addEventListener("click", async (ev) => {
+ const locale = ev.target.closest("[data-locale]");
+ if (locale) {
+ await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {});
+ location.reload();
+ return;
+ }
if (ev.target.closest("[data-logout]")) {
await api.post("/auth/logout").catch(() => {});
location.assign("/login");
diff --git a/internal/web/auth.templ b/internal/web/auth.templ
index 912a2d7..c0f86d6 100644
--- a/internal/web/auth.templ
+++ b/internal/web/auth.templ
@@ -1,37 +1,45 @@
package web
+import (
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
+)
+
templ Login(p Page, signupAllowed bool) {
- @authShell(p, "Anmelden") {
+ @authShell(p) {
if signupAllowed {
-
Noch kein Konto? Registrieren
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 24, Col: 42} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 25, Col: 105} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } return nil }) - templ_7745c5c3_Err = authShell(p, "Anmelden").Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -111,7 +155,7 @@ func Signup(p Page) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var4 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -123,7 +167,7 @@ func Signup(p Page) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = authShell(p, "Konto anlegen").Render(templ.WithChildren(ctx, templ_7745c5c3_Var4), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/console.templ b/internal/web/console.templ index 5645c7b..4a7a5f0 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -1,5 +1,8 @@ package web +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Me is the signed-in user as the console templates see it. type Me struct { Email string DisplayName string @@ -9,6 +12,7 @@ type Me struct { TOTPMissing bool } +// Org is one entry of the organization switcher. type Org struct { ID string Name string @@ -31,16 +35,17 @@ templ consoleShell(p Page, me Me) { { me.Orgs[0].Name } } if me.TOTPMissing {- Deine Organisation verlangt Zwei-Faktor-Anmeldung. - Jetzt einrichten + { i18n.T(ctx, "console.totp_missing") } + { i18n.T(ctx, "console.totp_missing_action") }
Noch keine Monitore angelegt.
+{ i18n.T(ctx, "console.monitors.empty") }
} } templ Security(p Page, me Me) { @consoleShell(p, me) { -● aktiv
+● { i18n.T(ctx, "security.totp.active") }
} else { -● nicht eingerichtet
+● { i18n.T(ctx, "security.totp.inactive") }
Deine Organisation verlangt Zwei-Faktor-Anmeldung. Jetzt einrichten
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 47, Col: 42} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 48, Col: 115} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "
Noch keine Monitore angelegt.
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 61, Col: 76} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -221,7 +311,7 @@ func Security(p Page, me Me) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var9 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var15 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -233,12 +323,51 @@ func Security(p Page, me Me) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "● aktiv
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "● nicht eingerichtet
uptimesebi
-uptimesebi
+ @languageSwitch(p.Languages) +uptimesebi
uptimesebi
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var6 string - templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(heading) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 32, Col: 51} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + templ_7745c5c3_Err = languageSwitch(p.Languages).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "". kv fills placeholders in that message.
func fail(c *gin.Context, status int, code string, kv ...any) {
+ ctx := c.Request.Context()
c.AbortWithStatusJSON(status, apiError{
- Error: code,
- Message: i18n.T(c.Request.Context(), "error."+code, kv...),
+ Error: code,
+ Message: i18n.T(ctx, "error."+code, kv...),
+ RequestID: requestid.FromContext(ctx),
})
}
@@ -154,7 +158,8 @@ func bind(c *gin.Context, dst any) bool {
if err == nil {
return true
}
- e := apiError{Error: "invalid_input", Message: i18n.T(c.Request.Context(), "error.invalid_input")}
+ ctx := c.Request.Context()
+ e := apiError{Error: "invalid_input", Message: i18n.T(ctx, "error.invalid_input"), RequestID: requestid.FromContext(ctx)}
var ve validator.ValidationErrors
if errors.As(err, &ve) {
e.Fields = map[string]string{}
diff --git a/internal/platform/log.go b/internal/platform/log.go
index 5592947..640fed1 100644
--- a/internal/platform/log.go
+++ b/internal/platform/log.go
@@ -1,19 +1,49 @@
package platform
import (
+ "context"
+ "io"
"log/slog"
"os"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
)
// NewLogger returns a JSON logger tagged with component and the release
// version, and the level variable controlling it. The level can be changed
// once configuration is loaded; the logger is needed before that to report
// configuration errors.
+//
+// Records logged with a request context carry its request_id, so handlers
+// should prefer the *Context logging methods.
func NewLogger(component string) (*slog.Logger, *slog.LevelVar) {
+ return newLogger(os.Stderr, component)
+}
+
+func newLogger(w io.Writer, component string) (*slog.Logger, *slog.LevelVar) {
level := new(slog.LevelVar)
- l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})).
- With("component", component, "app_version", buildinfo.Version)
- return l, level
+ h := contextHandler{slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})}
+ return slog.New(h).With("component", component, "app_version", buildinfo.Version), level
+}
+
+// contextHandler adds attributes carried in the context to each record.
+type contextHandler struct{ slog.Handler }
+
+// Handle implements slog.Handler.
+func (h contextHandler) Handle(ctx context.Context, r slog.Record) error {
+ if id := requestid.FromContext(ctx); id != "" {
+ r.AddAttrs(slog.String("request_id", id))
+ }
+ return h.Handler.Handle(ctx, r)
+}
+
+// WithAttrs keeps the wrapper so derived loggers still add the request ID.
+func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return contextHandler{h.Handler.WithAttrs(attrs)}
+}
+
+// WithGroup keeps the wrapper so derived loggers still add the request ID.
+func (h contextHandler) WithGroup(name string) slog.Handler {
+ return contextHandler{h.Handler.WithGroup(name)}
}
diff --git a/internal/platform/log_test.go b/internal/platform/log_test.go
new file mode 100644
index 0000000..84e4ef1
--- /dev/null
+++ b/internal/platform/log_test.go
@@ -0,0 +1,33 @@
+package platform
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "testing"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
+)
+
+func TestLoggerAddsRequestID(t *testing.T) {
+ var buf bytes.Buffer
+ log, _ := newLogger(&buf, "test")
+ log = log.With("extra", 1)
+
+ log.InfoContext(requestid.NewContext(context.Background(), "abc"), "with id")
+ log.InfoContext(context.Background(), "without id")
+
+ dec := json.NewDecoder(&buf)
+ for _, want := range []any{"abc", nil} {
+ var rec map[string]any
+ if err := dec.Decode(&rec); err != nil {
+ t.Fatalf("decoding log line: %v", err)
+ }
+ if got := rec["request_id"]; got != want {
+ t.Errorf("%q: request_id = %v, want %v", rec["msg"], got, want)
+ }
+ if rec["extra"] != float64(1) || rec["component"] != "test" {
+ t.Errorf("%q: lost attributes from With: %v", rec["msg"], rec)
+ }
+ }
+}
diff --git a/internal/platform/router.go b/internal/platform/router.go
index 2dd1219..d9fae7c 100644
--- a/internal/platform/router.go
+++ b/internal/platform/router.go
@@ -8,18 +8,20 @@ import (
"time"
"github.com/gin-gonic/gin"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
)
var quietPaths = map[string]bool{"/healthz": true, "/readyz": true}
-// NewRouter returns a gin engine that logs requests and panics through log
-// as JSON and writes nothing to stdout itself.
+// NewRouter returns a gin engine that assigns request IDs, logs requests and
+// panics through log as JSON and writes nothing to stdout itself.
func NewRouter(log *slog.Logger) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = io.Discard
gin.DefaultErrorWriter = io.Discard
r := gin.New()
- r.Use(accessLog(log), recovery(log))
+ r.Use(requestid.Middleware(), accessLog(log), recovery(log))
return r
}
diff --git a/internal/requestid/requestid.go b/internal/requestid/requestid.go
new file mode 100644
index 0000000..f288d62
--- /dev/null
+++ b/internal/requestid/requestid.go
@@ -0,0 +1,53 @@
+// Package requestid assigns every HTTP request an ID that ties together the
+// response, all log lines written for it and error reports from users.
+package requestid
+
+import (
+ "context"
+ "regexp"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+)
+
+// Header carries the ID in both directions.
+const Header = "X-Request-ID"
+
+// Incoming IDs end up in logs and response headers, so anything beyond a
+// conservative token alphabet is replaced rather than passed through.
+var valid = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
+
+type ctxKey struct{}
+
+// NewContext returns ctx carrying id.
+func NewContext(ctx context.Context, id string) context.Context {
+ return context.WithValue(ctx, ctxKey{}, id)
+}
+
+// FromContext returns the request ID in ctx, or "" outside a request.
+func FromContext(ctx context.Context) string {
+ id, _ := ctx.Value(ctxKey{}).(string)
+ return id
+}
+
+// Middleware keeps a well-formed X-Request-ID set by a proxy in front of us
+// and otherwise generates a time-ordered UUIDv7, so IDs sort by arrival.
+// It must run before any middleware that logs.
+func Middleware() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ id := c.GetHeader(Header)
+ if !valid.MatchString(id) {
+ id = newID()
+ }
+ c.Request = c.Request.WithContext(NewContext(c.Request.Context(), id))
+ c.Header(Header, id)
+ c.Next()
+ }
+}
+
+func newID() string {
+ if id, err := uuid.NewV7(); err == nil {
+ return id.String()
+ }
+ return uuid.NewString()
+}
diff --git a/internal/requestid/requestid_test.go b/internal/requestid/requestid_test.go
new file mode 100644
index 0000000..1af7f61
--- /dev/null
+++ b/internal/requestid/requestid_test.go
@@ -0,0 +1,56 @@
+package requestid
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+)
+
+func TestMiddleware(t *testing.T) {
+ tests := []struct {
+ name string
+ incoming string
+ keep bool
+ }{
+ {name: "none", incoming: "", keep: false},
+ {name: "uuid from proxy", incoming: "0b9a7c3e-6a43-4d2c-9a55-2f3b1c0d4e5f", keep: true},
+ {name: "trace style", incoming: "Root=1-5759e988-bd862e3fe1be46a994272793", keep: false},
+ {name: "opaque token", incoming: "edge:abc.123_X", keep: true},
+ {name: "header injection", incoming: "abc\r\nSet-Cookie: x=y", keep: false},
+ {name: "too long", incoming: strings.Repeat("a", 129), keep: false},
+ }
+ gin.SetMode(gin.TestMode)
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var seen string
+ r := gin.New()
+ r.Use(Middleware())
+ r.GET("/", func(c *gin.Context) { seen = FromContext(c.Request.Context()) })
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ if tt.incoming != "" {
+ req.Header.Set(Header, tt.incoming)
+ }
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+
+ got := w.Header().Get(Header)
+ if got != seen {
+ t.Errorf("response header %q != context ID %q", got, seen)
+ }
+ if tt.keep {
+ if got != tt.incoming {
+ t.Errorf("ID = %q, want incoming %q", got, tt.incoming)
+ }
+ return
+ }
+ if u, err := uuid.Parse(got); err != nil || u.Version() != 7 {
+ t.Errorf("ID = %q, want generated UUIDv7", got)
+ }
+ })
+ }
+}
--
2.54.1
From d1976ed57aaffa9481aa347736f310c389b7b5c7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?=
Date: Sun, 22 Nov 2026 00:30:43 +0100
Subject: [PATCH 18/22] feat(store): add per-organization sso providers and
linked identities
Identities are keyed by provider and subject. Both tables are tenant
scoped; org_id_by_slug resolves a slug before sign-in without opening a
broader scope.
Refs #4
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
---
internal/migrations/sql/00007_sso.sql | 70 +++++
internal/store/memberships.sql.go | 21 ++
internal/store/models.go | 25 ++
internal/store/querier.go | 13 +
internal/store/queries/memberships.sql | 3 +
internal/store/queries/sso.sql | 54 ++++
internal/store/sso.sql.go | 353 +++++++++++++++++++++++++
sqlc.yaml | 5 +
8 files changed, 544 insertions(+)
create mode 100644 internal/migrations/sql/00007_sso.sql
create mode 100644 internal/store/queries/sso.sql
create mode 100644 internal/store/sso.sql.go
diff --git a/internal/migrations/sql/00007_sso.sql b/internal/migrations/sql/00007_sso.sql
new file mode 100644
index 0000000..2cb4957
--- /dev/null
+++ b/internal/migrations/sql/00007_sso.sql
@@ -0,0 +1,70 @@
+-- +goose Up
+CREATE TABLE sso_providers (
+ id uuid PRIMARY KEY,
+ org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
+ name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
+ issuer text NOT NULL CHECK (issuer ~ '^https?://[^\s]+$' AND length(issuer) <= 500),
+ client_id text NOT NULL CHECK (length(client_id) BETWEEN 1 AND 500),
+ -- Sealed with the application keyring, bound to the provider id.
+ client_secret bytea,
+ scopes text[] NOT NULL DEFAULT '{openid,email,profile}',
+ -- Lower-case domains; empty means any. Applies to auto-provisioning only.
+ allowed_domains text[] NOT NULL DEFAULT '{}',
+ auto_provision boolean NOT NULL DEFAULT false,
+ enabled boolean NOT NULL DEFAULT true,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX sso_providers_org_idx ON sso_providers (org_id);
+
+-- Accounts are linked by issuer subject, never by email: an org admin
+-- controls their IdP and could otherwise assert any address.
+CREATE TABLE user_identities (
+ provider_id uuid NOT NULL REFERENCES sso_providers (id) ON DELETE CASCADE,
+ subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),
+ org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+ email citext,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ last_login_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (provider_id, subject)
+);
+
+CREATE INDEX user_identities_user_idx ON user_identities (user_id);
+
+ALTER TABLE sso_providers ENABLE ROW LEVEL SECURITY;
+ALTER TABLE sso_providers FORCE ROW LEVEL SECURITY;
+CREATE POLICY sso_providers_tenant ON sso_providers FOR ALL
+ USING (app_scope_system() OR org_id = app_org_id())
+ WITH CHECK (app_scope_system() OR org_id = app_org_id());
+
+ALTER TABLE user_identities ENABLE ROW LEVEL SECURITY;
+ALTER TABLE user_identities FORCE ROW LEVEL SECURITY;
+CREATE POLICY user_identities_tenant ON user_identities FOR ALL
+ USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id())
+ WITH CHECK (app_scope_system() OR org_id = app_org_id());
+
+-- SSO starts before anyone is signed in. This reveals only whether a slug
+-- exists, which the public /sso/ URL does anyway. FORCE ROW LEVEL
+-- SECURITY applies to the table owner too, so SECURITY DEFINER would not
+-- help; the system scope is raised for this single lookup and restored.
+-- +goose StatementBegin
+CREATE FUNCTION org_id_by_slug(s citext) RETURNS uuid
+LANGUAGE plpgsql VOLATILE AS $$
+DECLARE
+ prev text := coalesce(current_setting('app.scope', true), '');
+ result uuid;
+BEGIN
+ PERFORM set_config('app.scope', 'system', true);
+ SELECT id INTO result FROM orgs WHERE slug = s;
+ PERFORM set_config('app.scope', prev, true);
+ RETURN result;
+END
+$$;
+-- +goose StatementEnd
+
+-- +goose Down
+DROP FUNCTION org_id_by_slug(citext);
+DROP TABLE user_identities;
+DROP TABLE sso_providers;
diff --git a/internal/store/memberships.sql.go b/internal/store/memberships.sql.go
index ee9eee7..3551c0a 100644
--- a/internal/store/memberships.sql.go
+++ b/internal/store/memberships.sql.go
@@ -27,6 +27,27 @@ func (q *Queries) AddMembership(ctx context.Context, arg AddMembershipParams) er
return err
}
+const getMembership = `-- name: GetMembership :one
+SELECT org_id, user_id, is_owner, created_at FROM memberships WHERE org_id = $1 AND user_id = $2
+`
+
+type GetMembershipParams struct {
+ OrgID uuid.UUID
+ UserID uuid.UUID
+}
+
+func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
+ row := q.db.QueryRow(ctx, getMembership, arg.OrgID, arg.UserID)
+ var i Membership
+ err := row.Scan(
+ &i.OrgID,
+ &i.UserID,
+ &i.IsOwner,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const listOrgMembers = `-- name: ListOrgMembers :many
SELECT u.id, u.email, u.display_name, m.is_owner, m.created_at AS joined_at
FROM memberships m
diff --git a/internal/store/models.go b/internal/store/models.go
index 899f582..d54331e 100644
--- a/internal/store/models.go
+++ b/internal/store/models.go
@@ -26,6 +26,21 @@ type Org struct {
RequireTotp bool
}
+type SsoProvider struct {
+ ID uuid.UUID
+ OrgID uuid.UUID
+ Name string
+ Issuer string
+ ClientID string
+ ClientSecret []byte
+ Scopes []string
+ AllowedDomains []string
+ AutoProvision bool
+ Enabled bool
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
type User struct {
ID uuid.UUID
Email string
@@ -38,3 +53,13 @@ type User struct {
TotpEnabledAt *time.Time
Locale *string
}
+
+type UserIdentity struct {
+ ProviderID uuid.UUID
+ Subject string
+ OrgID uuid.UUID
+ UserID uuid.UUID
+ Email *string
+ CreatedAt time.Time
+ LastLoginAt time.Time
+}
diff --git a/internal/store/querier.go b/internal/store/querier.go
index aa4f651..1fc7a89 100644
--- a/internal/store/querier.go
+++ b/internal/store/querier.go
@@ -13,22 +13,35 @@ import (
type Querier interface {
AddMembership(ctx context.Context, arg AddMembershipParams) error
AnyUserExists(ctx context.Context) (bool, error)
+ CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
+ CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
+ DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error)
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
DisableTOTP(ctx context.Context, id uuid.UUID) error
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
+ GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error)
+ GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
GetOrg(ctx context.Context, id uuid.UUID) (Org, error)
GetOrgBySlug(ctx context.Context, slug string) (Org, error)
+ GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error)
GetUser(ctx context.Context, id uuid.UUID) (User, error)
GetUserByEmail(ctx context.Context, email string) (User, error)
+ IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
+ ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error)
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
ListOrgs(ctx context.Context) ([]Org, error)
+ ListSSOProviders(ctx context.Context) ([]SsoProvider, error)
+ ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error)
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
+ OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
+ TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
+ UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
}
var _ Querier = (*Queries)(nil)
diff --git a/internal/store/queries/memberships.sql b/internal/store/queries/memberships.sql
index 443a104..faba066 100644
--- a/internal/store/queries/memberships.sql
+++ b/internal/store/queries/memberships.sql
@@ -17,3 +17,6 @@ FROM memberships m
JOIN orgs o ON o.id = m.org_id
WHERE m.user_id = $1
ORDER BY o.name;
+
+-- name: GetMembership :one
+SELECT * FROM memberships WHERE org_id = $1 AND user_id = $2;
diff --git a/internal/store/queries/sso.sql b/internal/store/queries/sso.sql
new file mode 100644
index 0000000..32e25b6
--- /dev/null
+++ b/internal/store/queries/sso.sql
@@ -0,0 +1,54 @@
+-- name: OrgIDBySlug :one
+SELECT coalesce(org_id_by_slug(sqlc.arg(slug)::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id;
+
+-- name: CreateSSOProvider :one
+INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+RETURNING *;
+
+-- name: UpdateSSOProvider :one
+UPDATE sso_providers SET
+ name = $2,
+ issuer = $3,
+ client_id = $4,
+ client_secret = coalesce(sqlc.narg(client_secret), client_secret),
+ scopes = $5,
+ allowed_domains = $6,
+ auto_provision = $7,
+ enabled = $8,
+ updated_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: DeleteSSOProvider :execrows
+DELETE FROM sso_providers WHERE id = $1;
+
+-- name: GetSSOProvider :one
+SELECT * FROM sso_providers WHERE id = $1;
+
+-- name: ListSSOProviders :many
+SELECT * FROM sso_providers ORDER BY name;
+
+-- name: ListEnabledSSOProviders :many
+SELECT id, name FROM sso_providers WHERE enabled ORDER BY name;
+
+-- name: GetIdentity :one
+SELECT * FROM user_identities WHERE provider_id = $1 AND subject = $2;
+
+-- name: CreateIdentity :exec
+INSERT INTO user_identities (provider_id, subject, org_id, user_id, email)
+VALUES ($1, $2, $3, $4, $5);
+
+-- name: TouchIdentity :exec
+UPDATE user_identities SET email = $3, last_login_at = now()
+WHERE provider_id = $1 AND subject = $2;
+
+-- name: IsMember :one
+SELECT EXISTS (SELECT 1 FROM memberships WHERE org_id = $1 AND user_id = $2);
+
+-- name: ListUserIdentitiesInOrg :many
+SELECT p.name AS provider_name, i.email, i.created_at, i.last_login_at
+FROM user_identities i
+JOIN sso_providers p ON p.id = i.provider_id
+WHERE i.user_id = $1
+ORDER BY p.name;
diff --git a/internal/store/sso.sql.go b/internal/store/sso.sql.go
new file mode 100644
index 0000000..2ed150f
--- /dev/null
+++ b/internal/store/sso.sql.go
@@ -0,0 +1,353 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: sso.sql
+
+package store
+
+import (
+ "context"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const createIdentity = `-- name: CreateIdentity :exec
+INSERT INTO user_identities (provider_id, subject, org_id, user_id, email)
+VALUES ($1, $2, $3, $4, $5)
+`
+
+type CreateIdentityParams struct {
+ ProviderID uuid.UUID
+ Subject string
+ OrgID uuid.UUID
+ UserID uuid.UUID
+ Email *string
+}
+
+func (q *Queries) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error {
+ _, err := q.db.Exec(ctx, createIdentity,
+ arg.ProviderID,
+ arg.Subject,
+ arg.OrgID,
+ arg.UserID,
+ arg.Email,
+ )
+ return err
+}
+
+const createSSOProvider = `-- name: CreateSSOProvider :one
+INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at
+`
+
+type CreateSSOProviderParams struct {
+ ID uuid.UUID
+ OrgID uuid.UUID
+ Name string
+ Issuer string
+ ClientID string
+ ClientSecret []byte
+ Scopes []string
+ AllowedDomains []string
+ AutoProvision bool
+ Enabled bool
+}
+
+func (q *Queries) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) {
+ row := q.db.QueryRow(ctx, createSSOProvider,
+ arg.ID,
+ arg.OrgID,
+ arg.Name,
+ arg.Issuer,
+ arg.ClientID,
+ arg.ClientSecret,
+ arg.Scopes,
+ arg.AllowedDomains,
+ arg.AutoProvision,
+ arg.Enabled,
+ )
+ var i SsoProvider
+ err := row.Scan(
+ &i.ID,
+ &i.OrgID,
+ &i.Name,
+ &i.Issuer,
+ &i.ClientID,
+ &i.ClientSecret,
+ &i.Scopes,
+ &i.AllowedDomains,
+ &i.AutoProvision,
+ &i.Enabled,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const deleteSSOProvider = `-- name: DeleteSSOProvider :execrows
+DELETE FROM sso_providers WHERE id = $1
+`
+
+func (q *Queries) DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteSSOProvider, id)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const getIdentity = `-- name: GetIdentity :one
+SELECT provider_id, subject, org_id, user_id, email, created_at, last_login_at FROM user_identities WHERE provider_id = $1 AND subject = $2
+`
+
+type GetIdentityParams struct {
+ ProviderID uuid.UUID
+ Subject string
+}
+
+func (q *Queries) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) {
+ row := q.db.QueryRow(ctx, getIdentity, arg.ProviderID, arg.Subject)
+ var i UserIdentity
+ err := row.Scan(
+ &i.ProviderID,
+ &i.Subject,
+ &i.OrgID,
+ &i.UserID,
+ &i.Email,
+ &i.CreatedAt,
+ &i.LastLoginAt,
+ )
+ return i, err
+}
+
+const getSSOProvider = `-- name: GetSSOProvider :one
+SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers WHERE id = $1
+`
+
+func (q *Queries) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) {
+ row := q.db.QueryRow(ctx, getSSOProvider, id)
+ var i SsoProvider
+ err := row.Scan(
+ &i.ID,
+ &i.OrgID,
+ &i.Name,
+ &i.Issuer,
+ &i.ClientID,
+ &i.ClientSecret,
+ &i.Scopes,
+ &i.AllowedDomains,
+ &i.AutoProvision,
+ &i.Enabled,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const isMember = `-- name: IsMember :one
+SELECT EXISTS (SELECT 1 FROM memberships WHERE org_id = $1 AND user_id = $2)
+`
+
+type IsMemberParams struct {
+ OrgID uuid.UUID
+ UserID uuid.UUID
+}
+
+func (q *Queries) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) {
+ row := q.db.QueryRow(ctx, isMember, arg.OrgID, arg.UserID)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
+const listEnabledSSOProviders = `-- name: ListEnabledSSOProviders :many
+SELECT id, name FROM sso_providers WHERE enabled ORDER BY name
+`
+
+type ListEnabledSSOProvidersRow struct {
+ ID uuid.UUID
+ Name string
+}
+
+func (q *Queries) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) {
+ rows, err := q.db.Query(ctx, listEnabledSSOProviders)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListEnabledSSOProvidersRow{}
+ for rows.Next() {
+ var i ListEnabledSSOProvidersRow
+ if err := rows.Scan(&i.ID, &i.Name); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSSOProviders = `-- name: ListSSOProviders :many
+SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers ORDER BY name
+`
+
+func (q *Queries) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) {
+ rows, err := q.db.Query(ctx, listSSOProviders)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []SsoProvider{}
+ for rows.Next() {
+ var i SsoProvider
+ if err := rows.Scan(
+ &i.ID,
+ &i.OrgID,
+ &i.Name,
+ &i.Issuer,
+ &i.ClientID,
+ &i.ClientSecret,
+ &i.Scopes,
+ &i.AllowedDomains,
+ &i.AutoProvision,
+ &i.Enabled,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listUserIdentitiesInOrg = `-- name: ListUserIdentitiesInOrg :many
+SELECT p.name AS provider_name, i.email, i.created_at, i.last_login_at
+FROM user_identities i
+JOIN sso_providers p ON p.id = i.provider_id
+WHERE i.user_id = $1
+ORDER BY p.name
+`
+
+type ListUserIdentitiesInOrgRow struct {
+ ProviderName string
+ Email *string
+ CreatedAt time.Time
+ LastLoginAt time.Time
+}
+
+func (q *Queries) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) {
+ rows, err := q.db.Query(ctx, listUserIdentitiesInOrg, userID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListUserIdentitiesInOrgRow{}
+ for rows.Next() {
+ var i ListUserIdentitiesInOrgRow
+ if err := rows.Scan(
+ &i.ProviderName,
+ &i.Email,
+ &i.CreatedAt,
+ &i.LastLoginAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const orgIDBySlug = `-- name: OrgIDBySlug :one
+SELECT coalesce(org_id_by_slug($1::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id
+`
+
+func (q *Queries) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) {
+ row := q.db.QueryRow(ctx, orgIDBySlug, slug)
+ var id uuid.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
+const touchIdentity = `-- name: TouchIdentity :exec
+UPDATE user_identities SET email = $3, last_login_at = now()
+WHERE provider_id = $1 AND subject = $2
+`
+
+type TouchIdentityParams struct {
+ ProviderID uuid.UUID
+ Subject string
+ Email *string
+}
+
+func (q *Queries) TouchIdentity(ctx context.Context, arg TouchIdentityParams) error {
+ _, err := q.db.Exec(ctx, touchIdentity, arg.ProviderID, arg.Subject, arg.Email)
+ return err
+}
+
+const updateSSOProvider = `-- name: UpdateSSOProvider :one
+UPDATE sso_providers SET
+ name = $2,
+ issuer = $3,
+ client_id = $4,
+ client_secret = coalesce($9, client_secret),
+ scopes = $5,
+ allowed_domains = $6,
+ auto_provision = $7,
+ enabled = $8,
+ updated_at = now()
+WHERE id = $1
+RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at
+`
+
+type UpdateSSOProviderParams struct {
+ ID uuid.UUID
+ Name string
+ Issuer string
+ ClientID string
+ Scopes []string
+ AllowedDomains []string
+ AutoProvision bool
+ Enabled bool
+ ClientSecret []byte
+}
+
+func (q *Queries) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) {
+ row := q.db.QueryRow(ctx, updateSSOProvider,
+ arg.ID,
+ arg.Name,
+ arg.Issuer,
+ arg.ClientID,
+ arg.Scopes,
+ arg.AllowedDomains,
+ arg.AutoProvision,
+ arg.Enabled,
+ arg.ClientSecret,
+ )
+ var i SsoProvider
+ err := row.Scan(
+ &i.ID,
+ &i.OrgID,
+ &i.Name,
+ &i.Issuer,
+ &i.ClientID,
+ &i.ClientSecret,
+ &i.Scopes,
+ &i.AllowedDomains,
+ &i.AutoProvision,
+ &i.Enabled,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/sqlc.yaml b/sqlc.yaml
index 2a12748..d017061 100644
--- a/sqlc.yaml
+++ b/sqlc.yaml
@@ -16,6 +16,11 @@ sql:
go_type: github.com/google/uuid.UUID
- db_type: citext
go_type: string
+ - db_type: citext
+ nullable: true
+ go_type:
+ type: string
+ pointer: true
- db_type: timestamptz
go_type: time.Time
- db_type: timestamptz
--
2.54.1
From 9ad5f29f1b608caf96cedff39dc3313345fd7ee4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?=
Date: Sun, 22 Nov 2026 00:30:43 +0100
Subject: [PATCH 19/22] feat(sso): add openid connect client with pkce and
guarded discovery
Issuer URLs come from customers, so requests to their IdPs refuse
non-public addresses unless private networks are explicitly allowed.
Refs #4
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
---
go.mod | 13 ++-
go.sum | 22 ++--
internal/sso/httpclient.go | 45 ++++++++
internal/sso/httpclient_test.go | 46 ++++++++
internal/sso/sso.go | 188 ++++++++++++++++++++++++++++++++
internal/sso/sso_test.go | 115 +++++++++++++++++++
internal/sso/ssotest/idp.go | 166 ++++++++++++++++++++++++++++
7 files changed, 576 insertions(+), 19 deletions(-)
create mode 100644 internal/sso/httpclient.go
create mode 100644 internal/sso/httpclient_test.go
create mode 100644 internal/sso/sso.go
create mode 100644 internal/sso/sso_test.go
create mode 100644 internal/sso/ssotest/idp.go
diff --git a/go.mod b/go.mod
index 6efc2e3..7c78cd5 100644
--- a/go.mod
+++ b/go.mod
@@ -5,11 +5,19 @@ go 1.27.1
require (
github.com/a-h/templ v0.3.1118
github.com/caarlos0/env/v11 v11.4.2
+ github.com/coreos/go-oidc/v3 v3.21.0
github.com/gin-gonic/gin v1.12.0
+ github.com/go-jose/go-jose/v4 v4.1.4
+ github.com/go-playground/validator/v10 v10.30.6
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.13.0
+ github.com/nicksnyder/go-i18n/v2 v2.7.0
+ github.com/pquerna/otp v1.5.0
github.com/pressly/goose/v3 v3.30.1
github.com/redis/go-redis/v9 v9.23.0
+ golang.org/x/crypto v0.59.0
+ golang.org/x/oauth2 v0.38.0
+ golang.org/x/text v0.44.0
)
require (
@@ -29,7 +37,6 @@ require (
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
- github.com/go-playground/validator/v10 v10.30.6 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
@@ -44,9 +51,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/natefinch/atomic v1.0.1 // indirect
- github.com/nicksnyder/go-i18n/v2 v2.7.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
- github.com/pquerna/otp v1.5.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
@@ -56,12 +61,10 @@ require (
go.uber.org/atomic v1.12.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.22.0 // indirect
- golang.org/x/crypto v0.59.0 // indirect
golang.org/x/mod v0.43.0 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
- golang.org/x/text v0.44.0 // indirect
golang.org/x/tools v0.52.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
)
diff --git a/go.sum b/go.sum
index dc44847..ea1bd41 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,5 @@
+github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
+github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ=
github.com/a-h/parse v0.0.42/go.mod h1:X9OHJ1IjgakwZoDSoHYhdtKKD0zXZ2agpoIztPAA95w=
github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI=
@@ -26,6 +28,8 @@ github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
+github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
+github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -35,26 +39,20 @@ github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
-github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
-github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
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.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
+github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
+github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
-github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
-github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
-github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
-github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
-github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
-github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo=
github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
@@ -78,8 +76,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
-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/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
@@ -116,8 +112,6 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
-github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
-github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -150,14 +144,14 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
-golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
-golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
+golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
+golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
diff --git a/internal/sso/httpclient.go b/internal/sso/httpclient.go
new file mode 100644
index 0000000..c132918
--- /dev/null
+++ b/internal/sso/httpclient.go
@@ -0,0 +1,45 @@
+package sso
+
+import (
+ "context"
+ "errors"
+ "net"
+ "net/http"
+ "net/netip"
+ "syscall"
+ "time"
+)
+
+// ErrForbiddenAddress is returned when an IdP resolves to an address the
+// client may not contact.
+var ErrForbiddenAddress = errors.New("sso: issuer resolves to a non-public address")
+
+var cgnat = netip.MustParsePrefix("100.64.0.0/10")
+
+// SafeHTTPClient returns a client for talking to customer-configured IdPs.
+// Unless allowPrivate is set it refuses to connect to loopback, private,
+// link-local and similar ranges. The check runs on the resolved address at
+// dial time, so DNS rebinding and redirects cannot bypass it.
+func SafeHTTPClient(allowPrivate bool) *http.Client {
+ d := &net.Dialer{Timeout: 5 * time.Second}
+ if !allowPrivate {
+ d.Control = func(_, address string, _ syscall.RawConn) error {
+ ap, err := netip.ParseAddrPort(address)
+ if err != nil || !isPublic(ap.Addr()) {
+ return ErrForbiddenAddress
+ }
+ return nil
+ }
+ }
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.Proxy = nil
+ tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return d.DialContext(ctx, network, addr)
+ }
+ return &http.Client{Transport: tr, Timeout: 10 * time.Second}
+}
+
+func isPublic(a netip.Addr) bool {
+ a = a.Unmap()
+ return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a)
+}
diff --git a/internal/sso/httpclient_test.go b/internal/sso/httpclient_test.go
new file mode 100644
index 0000000..226344d
--- /dev/null
+++ b/internal/sso/httpclient_test.go
@@ -0,0 +1,46 @@
+package sso
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "testing"
+)
+
+func TestIsPublic(t *testing.T) {
+ tests := map[string]bool{
+ "8.8.8.8": true,
+ "2606:4700::1111": true,
+ "127.0.0.1": false,
+ "10.1.2.3": false,
+ "172.16.0.1": false,
+ "192.168.1.1": false,
+ "169.254.169.254": false,
+ "100.64.0.1": false,
+ "0.0.0.0": false,
+ "::1": false,
+ "fd00::1": false,
+ "fe80::1": false,
+ "::ffff:127.0.0.1": false,
+ }
+ for addr, want := range tests {
+ if got := isPublic(netip.MustParseAddr(addr)); got != want {
+ t.Errorf("isPublic(%s) = %t, want %t", addr, got, want)
+ }
+ }
+}
+
+func TestSafeHTTPClientBlocksLoopback(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ defer srv.Close()
+
+ if _, err := SafeHTTPClient(false).Get(srv.URL); !errors.Is(err, ErrForbiddenAddress) {
+ t.Errorf("Get(%s) with private networks denied: error = %v, want %v", srv.URL, err, ErrForbiddenAddress)
+ }
+ resp, err := SafeHTTPClient(true).Get(srv.URL)
+ if err != nil {
+ t.Fatalf("Get(%s) with private networks allowed failed: %v", srv.URL, err)
+ }
+ _ = resp.Body.Close()
+}
diff --git a/internal/sso/sso.go b/internal/sso/sso.go
new file mode 100644
index 0000000..c46bb03
--- /dev/null
+++ b/internal/sso/sso.go
@@ -0,0 +1,188 @@
+// Package sso implements OpenID Connect sign-in against identity providers
+// that each organization configures for itself.
+package sso
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "slices"
+ "sync"
+ "time"
+
+ "github.com/coreos/go-oidc/v3/oidc"
+ "golang.org/x/oauth2"
+)
+
+// Provider is one organization's IdP registration.
+type Provider struct {
+ Issuer string
+ ClientID string
+ ClientSecret string
+ Scopes []string
+}
+
+// Claims are the ID token fields used to identify and provision a user.
+type Claims struct {
+ Subject string `json:"sub"`
+ Email string `json:"email"`
+ EmailVerified bool `json:"email_verified"`
+ Name string `json:"name"`
+}
+
+// Flow holds the per-attempt secrets that must survive the redirect to the
+// IdP. Callers store it server side, keyed by State.
+type Flow struct {
+ State string
+ Nonce string
+ Verifier string
+}
+
+// ErrInvalidIssuer is returned for issuer URLs that are malformed or use a
+// scheme the client does not allow.
+var ErrInvalidIssuer = errors.New("sso: invalid issuer url")
+
+const discoveryTTL = time.Hour
+
+// Client performs discovery, builds authorization URLs and verifies
+// callbacks. Discovery documents are cached per issuer.
+type Client struct {
+ http *http.Client
+ redirectURL string
+ allowHTTP bool
+ now func() time.Time
+
+ mu sync.Mutex
+ cache map[string]cached
+}
+
+type cached struct {
+ provider *oidc.Provider
+ expires time.Time
+}
+
+// New returns a Client whose callbacks land on redirectURL. httpClient is
+// used for every request to an IdP; pass one from SafeHTTPClient. allowHTTP
+// permits plain-http issuers, which only makes sense for IdPs on a private
+// network.
+func New(httpClient *http.Client, redirectURL string, allowHTTP bool) *Client {
+ return &Client{
+ http: httpClient,
+ redirectURL: redirectURL,
+ allowHTTP: allowHTTP,
+ now: time.Now,
+ cache: map[string]cached{},
+ }
+}
+
+// RedirectURL is the callback URL to register at the IdP.
+func (c *Client) RedirectURL() string { return c.redirectURL }
+
+// ValidateIssuer checks the URL syntactically and runs discovery, so that
+// misconfiguration surfaces when an admin saves the provider rather than
+// when users try to sign in.
+func (c *Client) ValidateIssuer(ctx context.Context, issuer string) error {
+ if err := c.checkIssuer(issuer); err != nil {
+ return err
+ }
+ _, err := c.discover(ctx, issuer)
+ return err
+}
+
+func (c *Client) checkIssuer(issuer string) error {
+ u, err := url.Parse(issuer)
+ if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
+ return ErrInvalidIssuer
+ }
+ if u.Scheme != "https" && !(c.allowHTTP && u.Scheme == "http") {
+ return ErrInvalidIssuer
+ }
+ return nil
+}
+
+func (c *Client) discover(ctx context.Context, issuer string) (*oidc.Provider, error) {
+ c.mu.Lock()
+ if e, ok := c.cache[issuer]; ok && c.now().Before(e.expires) {
+ c.mu.Unlock()
+ return e.provider, nil
+ }
+ c.mu.Unlock()
+
+ p, err := oidc.NewProvider(oidc.ClientContext(ctx, c.http), issuer)
+ if err != nil {
+ return nil, fmt.Errorf("sso: discovery for %s: %w", issuer, err)
+ }
+ c.mu.Lock()
+ c.cache[issuer] = cached{provider: p, expires: c.now().Add(discoveryTTL)}
+ c.mu.Unlock()
+ return p, nil
+}
+
+func (c *Client) oauth(p Provider, op *oidc.Provider) *oauth2.Config {
+ scopes := p.Scopes
+ if !slices.Contains(scopes, oidc.ScopeOpenID) {
+ scopes = append([]string{oidc.ScopeOpenID}, scopes...)
+ }
+ return &oauth2.Config{
+ ClientID: p.ClientID,
+ ClientSecret: p.ClientSecret,
+ Endpoint: op.Endpoint(),
+ RedirectURL: c.redirectURL,
+ Scopes: scopes,
+ }
+}
+
+// NewFlow returns fresh state, nonce and PKCE verifier.
+func NewFlow(random func() string) Flow {
+ return Flow{State: random(), Nonce: random(), Verifier: oauth2.GenerateVerifier()}
+}
+
+// AuthURL returns the IdP URL to redirect the browser to.
+func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error) {
+ if err := c.checkIssuer(p.Issuer); err != nil {
+ return "", err
+ }
+ op, err := c.discover(ctx, p.Issuer)
+ if err != nil {
+ return "", err
+ }
+ return c.oauth(p, op).AuthCodeURL(f.State,
+ oidc.Nonce(f.Nonce),
+ oauth2.S256ChallengeOption(f.Verifier),
+ ), nil
+}
+
+// Exchange redeems the authorization code and verifies the ID token's
+// signature, issuer, audience, expiry and nonce.
+func (c *Client) Exchange(ctx context.Context, p Provider, f Flow, code string) (Claims, error) {
+ op, err := c.discover(ctx, p.Issuer)
+ if err != nil {
+ return Claims{}, err
+ }
+ ctx = oidc.ClientContext(ctx, c.http)
+ tok, err := c.oauth(p, op).Exchange(ctx, code, oauth2.VerifierOption(f.Verifier))
+ if err != nil {
+ return Claims{}, fmt.Errorf("sso: code exchange: %w", err)
+ }
+ raw, ok := tok.Extra("id_token").(string)
+ if !ok {
+ return Claims{}, errors.New("sso: token response without id_token")
+ }
+ idt, err := op.VerifierContext(ctx, &oidc.Config{ClientID: p.ClientID, Now: c.now}).Verify(ctx, raw)
+ if err != nil {
+ return Claims{}, fmt.Errorf("sso: id token: %w", err)
+ }
+ if idt.Nonce != f.Nonce {
+ return Claims{}, errors.New("sso: id token nonce mismatch")
+ }
+ var cl Claims
+ if err := idt.Claims(&cl); err != nil {
+ return Claims{}, fmt.Errorf("sso: id token claims: %w", err)
+ }
+ if cl.Subject == "" {
+ return Claims{}, errors.New("sso: id token without subject")
+ }
+ return cl, nil
+}
diff --git a/internal/sso/sso_test.go b/internal/sso/sso_test.go
new file mode 100644
index 0000000..d79cda0
--- /dev/null
+++ b/internal/sso/sso_test.go
@@ -0,0 +1,115 @@
+package sso_test
+
+import (
+ "context"
+ "crypto/rand"
+ "errors"
+ "net/http"
+ "net/url"
+ "testing"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
+)
+
+const callback = "https://uptime.example/sso/callback"
+
+// authorize follows the IdP redirect and returns the code and state it
+// would deliver to the callback.
+func authorize(t *testing.T, authURL string) (code, state string) {
+ t.Helper()
+ noFollow := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ resp, err := noFollow.Get(authURL)
+ if err != nil {
+ t.Fatalf("GET %s failed: %v", authURL, err)
+ }
+ _ = resp.Body.Close()
+ loc, err := url.Parse(resp.Header.Get("Location"))
+ if err != nil || resp.StatusCode != http.StatusFound {
+ t.Fatalf("authorize = %d %q, want 302 to callback", resp.StatusCode, resp.Header.Get("Location"))
+ }
+ return loc.Query().Get("code"), loc.Query().Get("state")
+}
+
+func setup(t *testing.T) (*ssotest.IDP, *sso.Client, sso.Provider) {
+ t.Helper()
+ idp := ssotest.New(t)
+ c := sso.New(sso.SafeHTTPClient(true), callback, true)
+ p := sso.Provider{Issuer: idp.Issuer(), ClientID: idp.ClientID, ClientSecret: idp.Secret, Scopes: []string{"email"}}
+ return idp, c, p
+}
+
+func TestFlow(t *testing.T) {
+ idp, c, p := setup(t)
+ idp.SetUser(ssotest.User{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"})
+ ctx := context.Background()
+
+ flow := sso.NewFlow(rand.Text)
+ authURL, err := c.AuthURL(ctx, p, flow)
+ if err != nil {
+ t.Fatalf("AuthURL() failed: %v", err)
+ }
+ code, state := authorize(t, authURL)
+ if state != flow.State {
+ t.Fatalf("state = %q, want %q", state, flow.State)
+ }
+ got, err := c.Exchange(ctx, p, flow, code)
+ if err != nil {
+ t.Fatalf("Exchange() failed: %v", err)
+ }
+ want := sso.Claims{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"}
+ if got != want {
+ t.Errorf("Exchange() = %+v, want %+v", got, want)
+ }
+}
+
+func TestExchangeRejects(t *testing.T) {
+ tests := []struct {
+ name string
+ tamper func(*ssotest.IDP, *sso.Flow)
+ }{
+ {"wrong nonce", func(i *ssotest.IDP, _ *sso.Flow) { i.NonceOverride = "other" }},
+ {"wrong audience", func(i *ssotest.IDP, _ *sso.Flow) { i.AudienceOverride = "someone-else" }},
+ {"wrong pkce verifier", func(_ *ssotest.IDP, f *sso.Flow) { f.Verifier = "x" + f.Verifier[1:] }},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ idp, c, p := setup(t)
+ idp.SetUser(ssotest.User{Subject: "u-1"})
+ ctx := context.Background()
+ flow := sso.NewFlow(rand.Text)
+ authURL, err := c.AuthURL(ctx, p, flow)
+ if err != nil {
+ t.Fatalf("AuthURL() failed: %v", err)
+ }
+ code, _ := authorize(t, authURL)
+ tt.tamper(idp, &flow)
+ if _, err := c.Exchange(ctx, p, flow, code); err == nil {
+ t.Error("Exchange() error = nil, want rejection")
+ }
+ })
+ }
+}
+
+func TestValidateIssuer(t *testing.T) {
+ idp, _, _ := setup(t)
+ strict := sso.New(sso.SafeHTTPClient(false), callback, false)
+ tests := []struct {
+ issuer string
+ client *sso.Client
+ want error
+ }{
+ {"ftp://idp.test", strict, sso.ErrInvalidIssuer},
+ {"https://idp.test/?q=1", strict, sso.ErrInvalidIssuer},
+ {"https://user@idp.test", strict, sso.ErrInvalidIssuer},
+ {idp.Issuer(), strict, sso.ErrInvalidIssuer},
+ {"https://127.0.0.1:1", strict, sso.ErrForbiddenAddress},
+ {idp.Issuer(), sso.New(sso.SafeHTTPClient(true), callback, true), nil},
+ }
+ for _, tt := range tests {
+ err := tt.client.ValidateIssuer(context.Background(), tt.issuer)
+ if !errors.Is(err, tt.want) {
+ t.Errorf("ValidateIssuer(%q) = %v, want %v", tt.issuer, err, tt.want)
+ }
+ }
+}
diff --git a/internal/sso/ssotest/idp.go b/internal/sso/ssotest/idp.go
new file mode 100644
index 0000000..062a66a
--- /dev/null
+++ b/internal/sso/ssotest/idp.go
@@ -0,0 +1,166 @@
+// Package ssotest provides a minimal OpenID Connect provider for tests.
+package ssotest
+
+import (
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/go-jose/go-jose/v4"
+ "github.com/go-jose/go-jose/v4/jwt"
+)
+
+// User is the identity the IDP asserts for the next login.
+type User struct {
+ Subject string
+ Email string
+ EmailVerified bool
+ Name string
+}
+
+// IDP is an in-memory authorization server. It signs ID tokens with a fresh
+// RSA key and enforces PKCE.
+type IDP struct {
+ Server *httptest.Server
+ ClientID string
+ Secret string
+
+ key *rsa.PrivateKey
+ signer jose.Signer
+
+ mu sync.Mutex
+ user User
+ codes map[string]grant
+ // NonceOverride, when set, replaces the nonce in issued tokens.
+ NonceOverride string
+ // AudienceOverride, when set, replaces the audience in issued tokens.
+ AudienceOverride string
+}
+
+type grant struct {
+ nonce, challenge, redirect string
+ user User
+}
+
+// New starts an IDP that is shut down when t ends.
+func New(t *testing.T) *IDP {
+ t.Helper()
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatal(err)
+ }
+ signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: jose.JSONWebKey{Key: key, KeyID: "k1"}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ idp := &IDP{ClientID: "client-1", Secret: "secret-1", key: key, signer: signer, codes: map[string]grant{}}
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /.well-known/openid-configuration", idp.discovery)
+ mux.HandleFunc("GET /keys", idp.keys)
+ mux.HandleFunc("GET /authorize", idp.authorize)
+ mux.HandleFunc("POST /token", idp.token)
+ idp.Server = httptest.NewServer(mux)
+ t.Cleanup(idp.Server.Close)
+ return idp
+}
+
+// Issuer is the issuer URL to configure.
+func (i *IDP) Issuer() string { return i.Server.URL }
+
+// SetUser selects who the next authorization asserts.
+func (i *IDP) SetUser(u User) {
+ i.mu.Lock()
+ defer i.mu.Unlock()
+ i.user = u
+}
+
+func (i *IDP) discovery(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, map[string]any{
+ "issuer": i.Issuer(),
+ "authorization_endpoint": i.Issuer() + "/authorize",
+ "token_endpoint": i.Issuer() + "/token",
+ "jwks_uri": i.Issuer() + "/keys",
+ "response_types_supported": []string{"code"},
+ "subject_types_supported": []string{"public"},
+ "id_token_signing_alg_values_supported": []string{"RS256"},
+ })
+}
+
+func (i *IDP) keys(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &i.key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}})
+}
+
+// authorize skips the login screen and immediately redirects back with a code.
+func (i *IDP) authorize(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ if q.Get("client_id") != i.ClientID || q.Get("code_challenge_method") != "S256" {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ code := rand.Text()
+ i.mu.Lock()
+ i.codes[code] = grant{nonce: q.Get("nonce"), challenge: q.Get("code_challenge"), redirect: q.Get("redirect_uri"), user: i.user}
+ i.mu.Unlock()
+ back, _ := url.Parse(q.Get("redirect_uri"))
+ v := back.Query()
+ v.Set("code", code)
+ v.Set("state", q.Get("state"))
+ back.RawQuery = v.Encode()
+ http.Redirect(w, r, back.String(), http.StatusFound)
+}
+
+func (i *IDP) token(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "bad form", http.StatusBadRequest)
+ return
+ }
+ id, secret, ok := r.BasicAuth()
+ if !ok {
+ id, secret = r.PostForm.Get("client_id"), r.PostForm.Get("client_secret")
+ }
+ if id != i.ClientID || secret != i.Secret {
+ http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized)
+ return
+ }
+ i.mu.Lock()
+ g, ok := i.codes[r.PostForm.Get("code")]
+ delete(i.codes, r.PostForm.Get("code"))
+ i.mu.Unlock()
+ sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
+ if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != g.challenge || r.PostForm.Get("redirect_uri") != g.redirect {
+ http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest)
+ return
+ }
+ nonce, aud := g.nonce, i.ClientID
+ if i.NonceOverride != "" {
+ nonce = i.NonceOverride
+ }
+ if i.AudienceOverride != "" {
+ aud = i.AudienceOverride
+ }
+ now := time.Now()
+ claims := map[string]any{
+ "iss": i.Issuer(), "sub": g.user.Subject, "aud": aud, "nonce": nonce,
+ "iat": now.Unix(), "exp": now.Add(5 * time.Minute).Unix(),
+ "email": g.user.Email, "email_verified": g.user.EmailVerified, "name": g.user.Name,
+ }
+ raw, err := jwt.Signed(i.signer).Claims(claims).Serialize()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ writeJSON(w, map[string]any{"access_token": "at", "token_type": "Bearer", "expires_in": 300, "id_token": raw})
+}
+
+func writeJSON(w http.ResponseWriter, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(v)
+}
--
2.54.1
From 3f21361995a3f51dedc8671ccab59a4344479abc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?=
Date: Sun, 22 Nov 2026 00:30:43 +0100
Subject: [PATCH 20/22] feat(api): let each organization sign in through its
own identity provider
Owners manage OIDC providers under /settings/sso. Users start at
/sso/. New users can be provisioned for verified emails in allowed
domains; existing accounts are never matched by email and must link
their SSO sign-in while signed in.
Closes #4
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
---
.env.example | 5 +
internal/api/pages.go | 102 ++++-
internal/api/server.go | 15 +
internal/api/sso.go | 436 ++++++++++++++++++
internal/api/sso_admin.go | 246 +++++++++++
internal/api/sso_test.go | 288 ++++++++++++
internal/config/config.go | 26 ++
internal/i18n/i18n_test.go | 3 +
internal/i18n/locales/de.json | 119 +++--
internal/i18n/locales/en.json | 119 +++--
internal/web/assets/app.js | 34 +-
internal/web/auth.templ | 14 +
internal/web/auth_templ.go | 96 +++-
internal/web/console.templ | 30 +-
internal/web/console_templ.go | 355 ++++++++++-----
internal/web/layout.templ | 14 +
internal/web/layout_templ.go | 97 +++-
internal/web/sso.templ | 156 +++++++
internal/web/sso_templ.go | 807 ++++++++++++++++++++++++++++++++++
19 files changed, 2731 insertions(+), 231 deletions(-)
create mode 100644 internal/api/sso.go
create mode 100644 internal/api/sso_admin.go
create mode 100644 internal/api/sso_test.go
create mode 100644 internal/web/sso.templ
create mode 100644 internal/web/sso_templ.go
diff --git a/.env.example b/.env.example
index 095a33c..b1b024e 100644
--- a/.env.example
+++ b/.env.example
@@ -8,3 +8,8 @@ UPTIME_CHECKER_REGION=local
# Generate with: echo "k1:$(head -c32 /dev/urandom | base64)"
UPTIME_SECRET_KEYS=dev:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+
+UPTIME_PUBLIC_URL=http://localhost:8080
+# Lets organizations use IdPs on private networks (e.g. an internal Keycloak).
+# auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud.
+UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto
diff --git a/internal/api/pages.go b/internal/api/pages.go
index 2d208cd..398e84f 100644
--- a/internal/api/pages.go
+++ b/internal/api/pages.go
@@ -2,11 +2,15 @@ package api
import (
"net/http"
+ "strings"
"github.com/a-h/templ"
"github.com/gin-gonic/gin"
+ "github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/store"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
@@ -14,7 +18,16 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/login", s.loginPage)
r.GET("/signup", s.signupPage)
r.GET("/", s.page("console.monitors.title", web.Dashboard))
- r.GET("/settings/security", s.page("security.title", web.Security))
+ r.GET("/settings/security", s.securityPage)
+ r.GET("/settings/sso", s.ssoSettingsPage)
+}
+
+// flashErrors lists the codes a redirect may ask a page to display. Anything
+// else in the query string is ignored so links cannot inject messages.
+var flashErrors = map[ssoError]bool{
+ "sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
+ "sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
+ "sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
}
func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
@@ -22,6 +35,12 @@ func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
if sess := auth.Current(c); sess != nil {
p.CSRF = sess.CSRF
}
+ if code := ssoError(c.Query("sso_error")); flashErrors[code] {
+ p.ErrorID = "error." + string(code)
+ }
+ if c.Query("sso") == "linked" {
+ p.NoticeID = "security.sso.linked"
+ }
return p
}
@@ -67,6 +86,83 @@ func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Componen
}
}
+func (s *Server) securityPage(c *gin.Context) {
+ sess := auth.Current(c)
+ if sess == nil {
+ c.Redirect(http.StatusSeeOther, "/login")
+ return
+ }
+ ctx := c.Request.Context()
+ me, err := s.loadMe(ctx, sess)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ var (
+ identities []web.Identity
+ canLink bool
+ )
+ if sess.OrgID != uuid.Nil {
+ err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
+ rows, err := q.ListUserIdentitiesInOrg(ctx, sess.UserID)
+ if err != nil {
+ return err
+ }
+ for _, r := range rows {
+ identities = append(identities, web.Identity{Provider: r.ProviderName, Email: deref(r.Email)})
+ }
+ providers, err := q.ListEnabledSSOProviders(ctx)
+ canLink = len(providers) > 0
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ }
+ web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), toWebMe(me), identities, canLink))
+}
+
+func (s *Server) ssoSettingsPage(c *gin.Context) {
+ sess := auth.Current(c)
+ if sess == nil {
+ c.Redirect(http.StatusSeeOther, "/login")
+ return
+ }
+ ctx := c.Request.Context()
+ me, err := s.loadMe(ctx, sess)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ wm := toWebMe(me)
+ if !wm.IsOwner {
+ c.Redirect(http.StatusSeeOther, "/")
+ return
+ }
+ var rows []store.SsoProvider
+ err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
+ rows, err = q.ListSSOProviders(ctx)
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ view := web.SSOSettings{
+ RedirectURL: s.sso.RedirectURL(),
+ LoginURL: s.cfg.PublicURL + "/sso/" + wm.ActiveSlug,
+ }
+ for _, r := range rows {
+ view.Providers = append(view.Providers, web.SSOProvider{
+ ID: r.ID.String(), Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID,
+ HasSecret: r.ClientSecret != nil, AllowedDomains: strings.Join(r.AllowedDomains, ", "),
+ AutoProvision: r.AutoProvision, Enabled: r.Enabled,
+ })
+ }
+ web.Render(c, http.StatusOK, web.SSOSettingsPage(s.pageFor(c, "sso.settings.title"), wm, view))
+}
+
func toWebMe(m meView) web.Me {
out := web.Me{
Email: m.Email,
@@ -77,6 +173,10 @@ func toWebMe(m meView) web.Me {
}
for _, o := range m.Orgs {
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
+ if o.ID == m.ActiveOrg {
+ out.IsOwner = o.IsOwner
+ out.ActiveSlug = o.Slug
+ }
}
return out
}
diff --git a/internal/api/server.go b/internal/api/server.go
index 537a894..c0ba9d3 100644
--- a/internal/api/server.go
+++ b/internal/api/server.go
@@ -16,6 +16,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
@@ -33,6 +34,7 @@ type Server struct {
sessions *auth.Sessions
limiter *auth.Limiter
totp *auth.TOTPVerifier
+ sso *sso.Client
}
// Deps are the external resources a Server needs.
@@ -46,6 +48,7 @@ type Deps struct {
// New returns a Server. It does not register any routes; see Mount.
func New(cfg config.API, d Deps) *Server {
+ allowPrivate := cfg.SSOAllowPrivate()
return &Server{
cfg: cfg,
log: d.Log,
@@ -56,6 +59,7 @@ func New(cfg config.API, d Deps) *Server {
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
limiter: auth.NewLimiter(d.Redis),
totp: auth.NewTOTPVerifier(d.Redis),
+ sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
}
}
@@ -80,6 +84,17 @@ func (s *Server) Mount(r gin.IRouter) {
me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable)
+ org := v1.Group("/org", auth.Require(), s.requireOwner())
+ org.GET("/sso", s.listSSOProviders)
+ org.POST("/sso", s.createSSOProvider)
+ org.PUT("/sso/:id", s.updateSSOProvider)
+ org.DELETE("/sso/:id", s.deleteSSOProvider)
+
+ g.GET("/sso", s.ssoLookup)
+ g.GET("/sso/callback", s.ssoCallback)
+ g.GET("/sso/:slug", s.ssoChoose)
+ g.GET("/sso/:slug/:provider", s.ssoStartProvider)
+
s.registerPages(g)
}
diff --git a/internal/api/sso.go b/internal/api/sso.go
new file mode 100644
index 0000000..252e9b5
--- /dev/null
+++ b/internal/api/sso.go
@@ -0,0 +1,436 @@
+package api
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/store"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/web"
+)
+
+const (
+ ssoCookie = "__Host-sso"
+ ssoFlowTTL = 10 * time.Minute
+)
+
+// ssoFlow is kept in Redis between the redirect to the IdP and the callback.
+type ssoFlow struct {
+ Provider uuid.UUID `json:"provider"`
+ Org uuid.UUID `json:"org"`
+ Nonce string `json:"nonce"`
+ Verifier string `json:"verifier"`
+ // LinkUser is set when a signed-in user connects this IdP to their
+ // existing account instead of signing in.
+ LinkUser uuid.UUID `json:"link_user,omitempty"`
+}
+
+// ssoError aborts a browser flow by redirecting with a code the target page
+// translates. Unlike JSON errors, the user has navigated away from our page.
+type ssoError string
+
+func ssoFlowKey(state string) string {
+ sum := sha256.Sum256([]byte(state))
+ return "sso_flow:" + hex.EncodeToString(sum[:])
+}
+
+func (s *Server) ssoProvider(row store.SsoProvider) (sso.Provider, error) {
+ p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: row.Scopes}
+ if row.ClientSecret != nil {
+ secret, err := s.keys.Open(row.ClientSecret, row.ID[:])
+ if err != nil {
+ return p, err
+ }
+ p.ClientSecret = string(secret)
+ }
+ return p, nil
+}
+
+// ssoLookup redirects the login page's slug form to the org's SSO URL.
+func (s *Server) ssoLookup(c *gin.Context) {
+ slug := strings.ToLower(strings.TrimSpace(c.Query("org")))
+ if slug == "" {
+ c.Redirect(http.StatusSeeOther, "/login")
+ return
+ }
+ c.Redirect(http.StatusSeeOther, "/sso/"+url.PathEscape(slug))
+}
+
+// ssoChoose starts the flow if the org has exactly one enabled provider and
+// otherwise lets the user pick.
+func (s *Server) ssoChoose(c *gin.Context) {
+ ctx := c.Request.Context()
+ if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
+ return
+ }
+ org, err := s.orgIDBySlug(ctx, c.Param("slug"))
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ var providers []store.ListEnabledSSOProvidersRow
+ if org != uuid.Nil {
+ err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
+ providers, err = q.ListEnabledSSOProviders(ctx)
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ }
+ switch len(providers) {
+ case 0:
+ s.ssoAbort(c, uuid.Nil, "sso_unavailable")
+ case 1:
+ s.ssoStart(c, org, providers[0].ID)
+ default:
+ opts := make([]web.SSOOption, len(providers))
+ for i, p := range providers {
+ opts[i] = web.SSOOption{Name: p.Name, URL: "/sso/" + url.PathEscape(c.Param("slug")) + "/" + p.ID.String() + linkSuffix(c)}
+ }
+ web.Render(c, http.StatusOK, web.SSOChooser(s.pageFor(c, "sso.choose.title"), opts))
+ }
+}
+
+func linkSuffix(c *gin.Context) string {
+ if c.Query("link") == "1" {
+ return "?link=1"
+ }
+ return ""
+}
+
+func (s *Server) ssoStartProvider(c *gin.Context) {
+ ctx := c.Request.Context()
+ if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
+ return
+ }
+ org, err := s.orgIDBySlug(ctx, c.Param("slug"))
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ id, err := uuid.Parse(c.Param("provider"))
+ if err != nil || org == uuid.Nil {
+ s.ssoAbort(c, uuid.Nil, "sso_unavailable")
+ return
+ }
+ s.ssoStart(c, org, id)
+}
+
+func (s *Server) ssoStart(c *gin.Context, org, providerID uuid.UUID) {
+ ctx := c.Request.Context()
+ var linkUser uuid.UUID
+ if c.Query("link") == "1" {
+ sess := auth.Current(c)
+ if sess == nil {
+ c.Redirect(http.StatusSeeOther, "/login")
+ return
+ }
+ linkUser = sess.UserID
+ }
+ var row store.SsoProvider
+ err := s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
+ var err error
+ row, err = q.GetSSOProvider(ctx, providerID)
+ return err
+ })
+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
+ s.ssoAbort(c, linkUser, "sso_unavailable")
+ return
+ }
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ p, err := s.ssoProvider(row)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ flow := sso.NewFlow(auth.RandomToken)
+ authURL, err := s.sso.AuthURL(ctx, p, flow)
+ if err != nil {
+ s.log.WarnContext(ctx, "sso discovery failed", "provider", providerID, "error", err)
+ s.ssoAbort(c, linkUser, "sso_provider_error")
+ return
+ }
+ state, _ := json.Marshal(ssoFlow{Provider: row.ID, Org: org, Nonce: flow.Nonce, Verifier: flow.Verifier, LinkUser: linkUser})
+ if err := s.rdb.Set(ctx, ssoFlowKey(flow.State), state, ssoFlowTTL).Err(); err != nil {
+ internalError(c, err)
+ return
+ }
+ // Binding the state to this browser stops an attacker from completing
+ // their own flow in a victim's browser (login CSRF).
+ setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds()))
+ c.Redirect(http.StatusFound, authURL)
+}
+
+func (s *Server) ssoCallback(c *gin.Context) {
+ ctx := c.Request.Context()
+ state := c.Query("state")
+ cookie, _ := c.Cookie(ssoCookie)
+ setCookie(c, ssoCookie, "", -1)
+ if state == "" || cookie != state {
+ s.ssoAbort(c, uuid.Nil, "sso_expired")
+ return
+ }
+ raw, err := s.rdb.GetDel(ctx, ssoFlowKey(state)).Bytes()
+ if err != nil {
+ s.ssoAbort(c, uuid.Nil, "sso_expired")
+ return
+ }
+ var f ssoFlow
+ if err := json.Unmarshal(raw, &f); err != nil {
+ internalError(c, err)
+ return
+ }
+ if c.Query("error") != "" {
+ s.ssoAbort(c, f.LinkUser, "sso_denied")
+ return
+ }
+
+ var row store.SsoProvider
+ err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error {
+ row, err = q.GetSSOProvider(ctx, f.Provider)
+ return err
+ })
+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
+ s.ssoAbort(c, f.LinkUser, "sso_unavailable")
+ return
+ }
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ p, err := s.ssoProvider(row)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ claims, err := s.sso.Exchange(ctx, p, sso.Flow{State: state, Nonce: f.Nonce, Verifier: f.Verifier}, c.Query("code"))
+ if err != nil {
+ s.log.WarnContext(ctx, "sso exchange failed", "provider", row.ID, "error", err)
+ s.ssoAbort(c, f.LinkUser, "sso_provider_error")
+ return
+ }
+
+ if f.LinkUser != uuid.Nil {
+ s.ssoLink(c, row, f.LinkUser, claims)
+ return
+ }
+ userID, code, err := s.ssoResolveUser(ctx, row, claims)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ if code != "" {
+ s.ssoAbort(c, uuid.Nil, code)
+ return
+ }
+ var user store.User
+ err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
+ user, err = q.GetUser(ctx, userID)
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ if user.DisabledAt != nil {
+ s.ssoAbort(c, uuid.Nil, "invalid_credentials")
+ return
+ }
+ if old := auth.Current(c); old != nil {
+ _ = s.sessions.Delete(ctx, old)
+ }
+ locale := deref(user.Locale)
+ if locale == "" {
+ locale = i18n.Lang(ctx)
+ }
+ sess, err := s.sessions.Create(ctx, userID, row.OrgID, locale)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
+ c.Redirect(http.StatusSeeOther, "/")
+}
+
+// ssoResolveUser maps an IdP identity to a user. It returns a non-empty
+// error code when sign-in must be refused.
+//
+// Existing accounts are only ever reached through a stored identity. A
+// matching email is not enough: the org controls its IdP and could assert
+// the address of a user who also belongs to other orgs.
+func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl sso.Claims) (uuid.UUID, ssoError, error) {
+ var (
+ userID uuid.UUID
+ code ssoError
+ )
+ email := normalizeEmail(cl.Email)
+ err := s.db.Tx(ctx, tenant.Org(row.OrgID, uuid.Nil), func(q *store.Queries) error {
+ ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
+ switch {
+ case err == nil:
+ member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: ident.UserID})
+ if err != nil {
+ return err
+ }
+ if !member {
+ code = "sso_not_member"
+ return nil
+ }
+ userID = ident.UserID
+ return q.TouchIdentity(ctx, store.TouchIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)})
+ case !errors.Is(err, pgx.ErrNoRows):
+ return err
+ }
+
+ if !row.AutoProvision || email == "" || !cl.EmailVerified || !domainAllowed(email, row.AllowedDomains) {
+ code = "sso_not_provisioned"
+ return nil
+ }
+ if _, err := q.GetUserByEmail(ctx, email); err == nil {
+ code = "sso_link_required"
+ return nil
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return err
+ }
+ u, err := q.CreateUser(ctx, store.CreateUserParams{
+ Email: email,
+ DisplayName: truncate(strings.TrimSpace(cl.Name), 200),
+ Locale: ptr(i18n.Lang(ctx)),
+ })
+ if err != nil {
+ return err
+ }
+ if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil {
+ return err
+ }
+ userID = u.ID
+ return q.CreateIdentity(ctx, store.CreateIdentityParams{ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: u.ID, Email: nonEmpty(email)})
+ })
+ return userID, code, err
+}
+
+func (s *Server) ssoLink(c *gin.Context, row store.SsoProvider, userID uuid.UUID, cl sso.Claims) {
+ ctx := c.Request.Context()
+ sess := auth.Current(c)
+ if sess == nil || sess.UserID != userID {
+ s.ssoAbort(c, uuid.Nil, "sso_expired")
+ return
+ }
+ var code ssoError
+ err := s.db.Tx(ctx, tenant.Org(row.OrgID, userID), func(q *store.Queries) error {
+ member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: userID})
+ if err != nil {
+ return err
+ }
+ if !member {
+ code = "sso_not_member"
+ return nil
+ }
+ ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
+ switch {
+ case err == nil && ident.UserID == userID:
+ return nil
+ case err == nil:
+ code = "sso_identity_taken"
+ return nil
+ case !errors.Is(err, pgx.ErrNoRows):
+ return err
+ }
+ return q.CreateIdentity(ctx, store.CreateIdentityParams{
+ ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)),
+ })
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ if code != "" {
+ s.ssoAbort(c, userID, code)
+ return
+ }
+ c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked")
+}
+
+// ssoAbort sends the browser back to where the flow started with an error
+// code the page renders in the user's language.
+func (s *Server) ssoAbort(c *gin.Context, linkUser uuid.UUID, code ssoError) {
+ target := "/login"
+ if linkUser != uuid.Nil {
+ target = "/settings/security"
+ }
+ c.Redirect(http.StatusSeeOther, target+"?sso_error="+url.QueryEscape(string(code)))
+}
+
+func (s *Server) orgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) {
+ var id uuid.UUID
+ err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
+ var err error
+ id, err = q.OrgIDBySlug(ctx, strings.ToLower(slug))
+ return err
+ })
+ return id, err
+}
+
+func (s *Server) limitPage(c *gin.Context, key string, n int, window time.Duration) bool {
+ ok, err := s.limiter.Allow(c.Request.Context(), key, n, window)
+ if err != nil {
+ internalError(c, err)
+ return false
+ }
+ if !ok {
+ c.Header("Retry-After", "60")
+ c.AbortWithStatus(http.StatusTooManyRequests)
+ return false
+ }
+ return true
+}
+
+func domainAllowed(email string, allowed []string) bool {
+ if len(allowed) == 0 {
+ return true
+ }
+ at := strings.LastIndexByte(email, '@')
+ if at < 0 {
+ return false
+ }
+ domain := email[at+1:]
+ for _, d := range allowed {
+ if domain == d {
+ return true
+ }
+ }
+ return false
+}
+
+func nonEmpty(s string) *string {
+ if s == "" {
+ return nil
+ }
+ return &s
+}
+
+func truncate(s string, n int) string {
+ if r := []rune(s); len(r) > n {
+ return string(r[:n])
+ }
+ return s
+}
diff --git a/internal/api/sso_admin.go b/internal/api/sso_admin.go
new file mode 100644
index 0000000..5d72986
--- /dev/null
+++ b/internal/api/sso_admin.go
@@ -0,0 +1,246 @@
+package api
+
+import (
+ "errors"
+ "net/http"
+ "regexp"
+ "slices"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/store"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
+)
+
+const ctxOrgKey = "api.org"
+
+// requireOwner admits only the owner of the session's active org. It is a
+// stand-in until role-based permissions exist (#6).
+func (s *Server) requireOwner() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ sess := auth.Current(c)
+ if sess == nil || sess.OrgID == uuid.Nil {
+ fail(c, http.StatusForbidden, "forbidden")
+ return
+ }
+ ctx := c.Request.Context()
+ var m store.Membership
+ err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
+ var err error
+ m, err = q.GetMembership(ctx, store.GetMembershipParams{OrgID: sess.OrgID, UserID: sess.UserID})
+ return err
+ })
+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && !m.IsOwner) {
+ fail(c, http.StatusForbidden, "forbidden")
+ return
+ }
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ c.Set(ctxOrgKey, sess.OrgID)
+ c.Next()
+ }
+}
+
+func orgOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxOrgKey).(uuid.UUID) }
+
+type ssoProviderView struct {
+ ID uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ Issuer string `json:"issuer"`
+ ClientID string `json:"client_id"`
+ HasClientSecret bool `json:"has_client_secret"`
+ Scopes []string `json:"scopes"`
+ AllowedDomains []string `json:"allowed_domains"`
+ AutoProvision bool `json:"auto_provision"`
+ Enabled bool `json:"enabled"`
+}
+
+func viewSSOProvider(p store.SsoProvider) ssoProviderView {
+ return ssoProviderView{
+ ID: p.ID, Name: p.Name, Issuer: p.Issuer, ClientID: p.ClientID,
+ HasClientSecret: p.ClientSecret != nil, Scopes: p.Scopes,
+ AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, Enabled: p.Enabled,
+ }
+}
+
+type ssoProviderRequest struct {
+ Name string `json:"name" binding:"required,max=100"`
+ Issuer string `json:"issuer" binding:"required,max=500"`
+ ClientID string `json:"client_id" binding:"required,max=500"`
+ // Empty on update keeps the stored secret; it is never returned.
+ ClientSecret string `json:"client_secret" binding:"max=2000"`
+ Scopes []string `json:"scopes" binding:"max=20,dive,max=100"`
+ AllowedDomains []string `json:"allowed_domains" binding:"max=50,dive,max=253"`
+ AutoProvision bool `json:"auto_provision"`
+ Enabled *bool `json:"enabled"`
+}
+
+var domainRE = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
+
+// normalize cleans the request and returns an error code for invalid input.
+func (r *ssoProviderRequest) normalize() string {
+ r.Name = strings.TrimSpace(r.Name)
+ r.Issuer = strings.TrimSuffix(strings.TrimSpace(r.Issuer), "/")
+ r.ClientID = strings.TrimSpace(r.ClientID)
+ if r.Name == "" || r.ClientID == "" {
+ return "invalid_input"
+ }
+ scopes := []string{"openid"}
+ for _, sc := range r.Scopes {
+ if sc = strings.TrimSpace(sc); sc != "" && !slices.Contains(scopes, sc) {
+ scopes = append(scopes, sc)
+ }
+ }
+ if len(r.Scopes) == 0 {
+ scopes = append(scopes, "email", "profile")
+ }
+ r.Scopes = scopes
+ domains := []string{}
+ for _, d := range r.AllowedDomains {
+ d = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(d)), "@")
+ if d == "" {
+ continue
+ }
+ if !domainRE.MatchString(d) {
+ return "invalid_domain"
+ }
+ if !slices.Contains(domains, d) {
+ domains = append(domains, d)
+ }
+ }
+ r.AllowedDomains = domains
+ return ""
+}
+
+func (s *Server) listSSOProviders(c *gin.Context) {
+ ctx := c.Request.Context()
+ var rows []store.SsoProvider
+ err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
+ var err error
+ rows, err = q.ListSSOProviders(ctx)
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ out := make([]ssoProviderView, len(rows))
+ for i, r := range rows {
+ out[i] = viewSSOProvider(r)
+ }
+ c.JSON(http.StatusOK, gin.H{"providers": out, "redirect_url": s.sso.RedirectURL()})
+}
+
+func (s *Server) validateSSORequest(c *gin.Context, req *ssoProviderRequest) bool {
+ if code := req.normalize(); code != "" {
+ fail(c, http.StatusUnprocessableEntity, code)
+ return false
+ }
+ if err := s.sso.ValidateIssuer(c.Request.Context(), req.Issuer); err != nil {
+ code := "sso_discovery_failed"
+ switch {
+ case errors.Is(err, sso.ErrInvalidIssuer):
+ code = "sso_invalid_issuer"
+ case errors.Is(err, sso.ErrForbiddenAddress):
+ code = "sso_forbidden_address"
+ }
+ fail(c, http.StatusUnprocessableEntity, code)
+ return false
+ }
+ return true
+}
+
+func (s *Server) createSSOProvider(c *gin.Context) {
+ var req ssoProviderRequest
+ if !bind(c, &req) || !s.validateSSORequest(c, &req) {
+ return
+ }
+ ctx := c.Request.Context()
+ id := uuid.New()
+ var secret []byte
+ if req.ClientSecret != "" {
+ secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
+ }
+ var row store.SsoProvider
+ err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
+ var err error
+ row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{
+ ID: id, OrgID: orgOf(c), Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
+ ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains,
+ AutoProvision: req.AutoProvision, Enabled: req.Enabled == nil || *req.Enabled,
+ })
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ c.JSON(http.StatusCreated, viewSSOProvider(row))
+}
+
+func (s *Server) updateSSOProvider(c *gin.Context) {
+ id, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ fail(c, http.StatusNotFound, "not_found")
+ return
+ }
+ var req ssoProviderRequest
+ if !bind(c, &req) || !s.validateSSORequest(c, &req) {
+ return
+ }
+ ctx := c.Request.Context()
+ var secret []byte
+ if req.ClientSecret != "" {
+ secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
+ }
+ var row store.SsoProvider
+ err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
+ var err error
+ row, err = q.UpdateSSOProvider(ctx, store.UpdateSSOProviderParams{
+ ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret,
+ Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, AutoProvision: req.AutoProvision,
+ Enabled: req.Enabled == nil || *req.Enabled,
+ })
+ return err
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ fail(c, http.StatusNotFound, "not_found")
+ return
+ }
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, viewSSOProvider(row))
+}
+
+func (s *Server) deleteSSOProvider(c *gin.Context) {
+ id, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ fail(c, http.StatusNotFound, "not_found")
+ return
+ }
+ ctx := c.Request.Context()
+ var n int64
+ err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
+ var err error
+ n, err = q.DeleteSSOProvider(ctx, id)
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ if n == 0 {
+ fail(c, http.StatusNotFound, "not_found")
+ return
+ }
+ c.Status(http.StatusNoContent)
+}
diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go
new file mode 100644
index 0000000..9c9d57d
--- /dev/null
+++ b/internal/api/sso_test.go
@@ -0,0 +1,288 @@
+package api_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/redis/go-redis/v9"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/api"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/config"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
+)
+
+type env struct {
+ srv *httptest.Server
+ dbPool *pgxpool.Pool
+}
+
+func newEnv(t *testing.T) *env {
+ t.Helper()
+ dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL")
+ if dsn == "" || redisURL == "" {
+ t.Skip("UPTIME_TEST_DATABASE_URL and UPTIME_TEST_REDIS_URL must be set")
+ }
+ ctx := context.Background()
+ if _, err := migrations.Up(ctx, dsn); err != nil {
+ t.Fatalf("migrations.Up() failed: %v", err)
+ }
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ opts, err := redis.ParseURL(redisURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rdb := redis.NewClient(opts)
+ t.Cleanup(func() { _ = rdb.Close() })
+
+ key := make([]byte, 32)
+ _, _ = rand.Read(key)
+ keys, err := sealed.Parse("t:" + base64.StdEncoding.EncodeToString(key))
+ if err != nil {
+ t.Fatal(err)
+ }
+ catalog, err := i18n.Load()
+ if err != nil {
+ t.Fatal(err)
+ }
+ log := slog.New(slog.DiscardHandler)
+
+ e := &env{dbPool: pool}
+ r := platform.NewRouter(log)
+ e.srv = httptest.NewUnstartedServer(r)
+ e.srv.StartTLS()
+ t.Cleanup(e.srv.Close)
+
+ cfg := config.API{
+ Common: config.Common{Edition: config.EditionSelfHosted},
+ Signup: config.SignupOpen,
+ SessionIdle: time.Hour,
+ SessionAbsolute: 24 * time.Hour,
+ PublicURL: e.srv.URL,
+ SSOPrivateNetworks: "true",
+ }
+ api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}).Mount(r)
+ return e
+}
+
+// browser is a cookie-keeping client that follows redirects like a browser.
+type browser struct {
+ t *testing.T
+ base string
+ hc *http.Client
+ csrf string
+}
+
+func (e *env) browser(t *testing.T) *browser {
+ jar, _ := cookiejar.New(nil)
+ // Client() returns a shared instance; copy it so each browser has its own jar.
+ hc := *e.srv.Client()
+ hc.Jar = jar
+ return &browser{t: t, base: e.srv.URL, hc: &hc}
+}
+
+func (b *browser) do(method, path string, body any) (int, map[string]any) {
+ b.t.Helper()
+ var rd io.Reader
+ if body != nil {
+ raw, _ := json.Marshal(body)
+ rd = bytes.NewReader(raw)
+ }
+ req, _ := http.NewRequest(method, b.base+path, rd)
+ req.Header.Set("Content-Type", "application/json")
+ if b.csrf != "" {
+ req.Header.Set("X-CSRF-Token", b.csrf)
+ }
+ resp, err := b.hc.Do(req)
+ if err != nil {
+ b.t.Fatalf("%s %s failed: %v", method, path, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var out map[string]any
+ _ = json.NewDecoder(resp.Body).Decode(&out)
+ if tok, ok := out["csrf_token"].(string); ok {
+ b.csrf = tok
+ }
+ return resp.StatusCode, out
+}
+
+// visit follows redirects and returns the final URL.
+func (b *browser) visit(path string) *url.URL {
+ b.t.Helper()
+ resp, err := b.hc.Get(b.base + path)
+ if err != nil {
+ b.t.Fatalf("GET %s failed: %v", path, err)
+ }
+ _ = resp.Body.Close()
+ return resp.Request.URL
+}
+
+func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") }
+
+func (b *browser) signup(email, slug string) {
+ b.t.Helper()
+ st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{
+ "email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug,
+ })
+ if st != http.StatusOK {
+ b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body)
+ }
+}
+
+func TestSSO(t *testing.T) {
+ e := newEnv(t)
+ idp := ssotest.New(t)
+ slug := uniq("sso-")
+ domain := uniq("d") + ".test"
+
+ owner := e.browser(t)
+ owner.signup("owner@"+domain, slug)
+
+ st, body := owner.do("POST", "/api/v1/org/sso", map[string]any{
+ "name": "Corp IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
+ "allowed_domains": []string{domain}, "auto_provision": true,
+ })
+ if st != http.StatusCreated {
+ t.Fatalf("create provider = %d %v, want 201", st, body)
+ }
+ if body["has_client_secret"] != true || body["client_secret"] != nil {
+ t.Errorf("create provider response = %v, want has_client_secret and no secret", body)
+ }
+
+ t.Run("other org cannot see provider", func(t *testing.T) {
+ other := e.browser(t)
+ other.signup("x@"+uniq("o")+".test", uniq("other-"))
+ st, body := other.do("GET", "/api/v1/org/sso", nil)
+ if st != http.StatusOK || len(body["providers"].([]any)) != 0 {
+ t.Errorf("GET /api/v1/org/sso as other org = %d %v, want 200 with no providers", st, body)
+ }
+ })
+
+ t.Run("auto provisioning", func(t *testing.T) {
+ idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "new@" + domain, EmailVerified: true, Name: "New"})
+ u := e.browser(t)
+ if got := u.visit("/sso/" + slug); got.Path != "/" || got.Query().Get("sso_error") != "" {
+ t.Fatalf("SSO login landed on %s, want /", got)
+ }
+ st, me := u.do("GET", "/api/v1/me", nil)
+ if st != http.StatusOK || me["email"] != "new@"+domain {
+ t.Errorf("GET /api/v1/me = %d %v, want new@%s", st, me, domain)
+ }
+ st, _ = u.do("GET", "/api/v1/org/sso", nil)
+ if st != http.StatusForbidden {
+ t.Errorf("GET /api/v1/org/sso as member = %d, want 403", st)
+ }
+ })
+
+ t.Run("unverified email is not provisioned", func(t *testing.T) {
+ idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "unverified@" + domain, EmailVerified: false})
+ if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" {
+ t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got)
+ }
+ })
+
+ t.Run("foreign domain is not provisioned", func(t *testing.T) {
+ idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "x@elsewhere.test", EmailVerified: true})
+ if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" {
+ t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got)
+ }
+ })
+
+ t.Run("existing email requires explicit linking", func(t *testing.T) {
+ subject := uniq("s")
+ idp.SetUser(ssotest.User{Subject: subject, Email: "owner@" + domain, EmailVerified: true})
+ if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_link_required" {
+ t.Fatalf("SSO login landed on %s, want sso_error=sso_link_required", got)
+ }
+
+ if got := owner.visit("/sso/" + slug + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" {
+ t.Fatalf("link flow landed on %s, want /settings/security?sso=linked", got)
+ }
+ fresh := e.browser(t)
+ if got := fresh.visit("/sso/" + slug); got.Path != "/" {
+ t.Fatalf("SSO login after linking landed on %s, want /", got)
+ }
+ if _, me := fresh.do("GET", "/api/v1/me", nil); me["email"] != "owner@"+domain {
+ t.Errorf("GET /api/v1/me after linked login = %v, want owner", me)
+ }
+ })
+
+ t.Run("callback without browser binding is rejected", func(t *testing.T) {
+ attacker := e.browser(t)
+ attacker.hc.CheckRedirect = func(req *http.Request, _ []*http.Request) error {
+ if strings.HasPrefix(req.URL.Path, "/sso/callback") {
+ return http.ErrUseLastResponse
+ }
+ return nil
+ }
+ resp, err := attacker.hc.Get(attacker.base + "/sso/" + slug)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = resp.Body.Close()
+ callback := resp.Header.Get("Location")
+ if got := e.browser(t).visit(strings.TrimPrefix(callback, attacker.base)); got.Query().Get("sso_error") != "sso_expired" {
+ t.Errorf("replaying callback in another browser landed on %s, want sso_error=sso_expired", got)
+ }
+ })
+
+ t.Run("disabled provider", func(t *testing.T) {
+ _, list := owner.do("GET", "/api/v1/org/sso", nil)
+ p := list["providers"].([]any)[0].(map[string]any)
+ st, body := owner.do("PUT", "/api/v1/org/sso/"+p["id"].(string), map[string]any{
+ "name": p["name"], "issuer": p["issuer"], "client_id": p["client_id"], "enabled": false,
+ })
+ if st != http.StatusOK || body["has_client_secret"] != true {
+ t.Fatalf("PUT provider = %d %v, want 200 keeping the secret", st, body)
+ }
+ if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_unavailable" {
+ t.Errorf("SSO login with disabled provider landed on %s, want sso_error=sso_unavailable", got)
+ }
+ })
+}
+
+func TestSSOProviderValidation(t *testing.T) {
+ e := newEnv(t)
+ owner := e.browser(t)
+ owner.signup("o@"+uniq("v")+".test", uniq("val-"))
+ tests := []struct {
+ name string
+ body map[string]any
+ want string
+ }{
+ {"bad scheme", map[string]any{"name": "x", "issuer": "ftp://idp.test", "client_id": "c"}, "sso_invalid_issuer"},
+ {"unreachable", map[string]any{"name": "x", "issuer": "http://127.0.0.1:1", "client_id": "c"}, "sso_discovery_failed"},
+ {"bad domain", map[string]any{"name": "x", "issuer": "https://idp.test", "client_id": "c", "allowed_domains": []string{"not a domain"}}, "invalid_domain"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ st, body := owner.do("POST", "/api/v1/org/sso", tt.body)
+ if st != http.StatusUnprocessableEntity || body["error"] != tt.want {
+ t.Errorf("POST /api/v1/org/sso = %d %v, want 422 %s", st, body["error"], tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 92d7ae8..3aead1d 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -5,6 +5,8 @@ package config
import (
"fmt"
"log/slog"
+ "net/url"
+ "strings"
"time"
"github.com/caarlos0/env/v11"
@@ -61,6 +63,22 @@ type API struct {
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"`
SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"`
+ // PublicURL is the externally reachable base URL, used for SSO callbacks.
+ PublicURL string `env:"UPTIME_PUBLIC_URL" envDefault:"http://localhost:8080"`
+ // SSOPrivateNetworks is "auto", "true" or "false". Auto allows
+ // organizations' IdPs on private networks only in the self-hosted edition.
+ SSOPrivateNetworks string `env:"UPTIME_SSO_ALLOW_PRIVATE_NETWORKS" envDefault:"auto"`
+}
+
+// SSOAllowPrivate resolves SSOPrivateNetworks.
+func (a API) SSOAllowPrivate() bool {
+ switch a.SSOPrivateNetworks {
+ case "true":
+ return true
+ case "false":
+ return false
+ }
+ return a.Edition == EditionSelfHosted
}
// Validate checks API-specific settings in addition to Common.Validate.
@@ -76,6 +94,14 @@ func (a API) Validate() error {
default:
return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup)
}
+ switch a.SSOPrivateNetworks {
+ case "auto", "true", "false":
+ default:
+ return fmt.Errorf("config: UPTIME_SSO_ALLOW_PRIVATE_NETWORKS must be auto, true or false")
+ }
+ if u, err := url.Parse(a.PublicURL); err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || strings.HasSuffix(a.PublicURL, "/") {
+ return fmt.Errorf("config: UPTIME_PUBLIC_URL must be an absolute http(s) URL without trailing slash")
+ }
if a.SessionIdle <= 0 || a.SessionAbsolute < a.SessionIdle {
return fmt.Errorf("config: UPTIME_SESSION_ABSOLUTE must be >= UPTIME_SESSION_IDLE > 0")
}
diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go
index 614fe8c..998a6d6 100644
--- a/internal/i18n/i18n_test.go
+++ b/internal/i18n/i18n_test.go
@@ -61,6 +61,9 @@ var usagePatterns = []struct {
{regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""},
{regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."},
{regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""},
+ {regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), "error."},
+ {regexp.MustCompile(`return "(invalid_[a-z_]+)"`), "error."},
+ {regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`), ""},
}
// TestUsedKeysExist scans the source tree for literal message IDs so a typo
diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json
index b59be86..df5e12e 100644
--- a/internal/i18n/locales/de.json
+++ b/internal/i18n/locales/de.json
@@ -1,57 +1,96 @@
{
"app.network_error": "Verbindung fehlgeschlagen.",
- "lang.en": "English",
- "lang.de": "Deutsch",
-
- "auth.login.title": "Anmelden",
- "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.",
- "auth.login.submit": "Weiter",
- "auth.login.no_account": "Noch kein Konto?",
- "auth.login.to_signup": "Registrieren",
- "auth.signup.title": "Konto anlegen",
- "auth.signup.submit": "Anlegen",
- "auth.signup.to_login": "Zur Anmeldung",
- "auth.field.name": "Name",
+ "auth.field.code": "Code",
"auth.field.email": "E-Mail",
- "auth.field.password": "Passwort",
+ "auth.field.name": "Name",
"auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)",
"auth.field.org_name": "Organisation",
"auth.field.org_slug": "Kurzname (a–z, 0–9, -)",
- "auth.field.code": "Code",
-
- "console.nav.security": "Sicherheit",
+ "auth.field.password": "Passwort",
+ "auth.login.no_account": "Noch kein Konto?",
+ "auth.login.submit": "Weiter",
+ "auth.login.title": "Anmelden",
+ "auth.login.to_signup": "Registrieren",
+ "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.",
+ "auth.signup.submit": "Anlegen",
+ "auth.signup.title": "Konto anlegen",
+ "auth.signup.to_login": "Zur Anmeldung",
+ "auth.sso.heading": "Single Sign-on",
+ "auth.sso.org_placeholder": "Kurzname der Organisation",
+ "auth.sso.submit": "Weiter",
+ "common.no": "nein",
+ "common.save": "Speichern",
+ "common.yes": "ja",
+ "console.monitors.empty": "Noch keine Monitore angelegt.",
+ "console.monitors.title": "Monitore",
"console.nav.logout": "Abmelden",
+ "console.nav.security": "Sicherheit",
+ "console.nav.sso": "SSO",
"console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.",
"console.totp_missing_action": "Jetzt einrichten",
- "console.monitors.title": "Monitore",
- "console.monitors.empty": "Noch keine Monitore angelegt.",
-
- "security.title": "Sicherheit",
- "security.totp.heading": "Zwei-Faktor (TOTP)",
- "security.totp.active": "aktiv",
- "security.totp.inactive": "nicht eingerichtet",
- "security.totp.disable": "Deaktivieren",
- "security.totp.current_code": "Aktueller Code",
- "security.totp.start": "Einrichten",
- "security.totp.qr_alt": "QR-Code für die Authenticator-App",
- "security.totp.app_code": "Code aus der App",
- "security.totp.confirm": "Bestätigen",
-
+ "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
+ "error.forbidden": "Dafür fehlt dir die Berechtigung.",
"error.internal": "Interner Fehler.",
+ "error.invalid_code": "Code ungültig.",
+ "error.invalid_credentials": "E-Mail oder Passwort falsch.",
+ "error.invalid_domain": "Eine der Domains ist ungültig.",
"error.invalid_input": "Eingaben prüfen.",
+ "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.",
+ "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.",
+ "error.no_password": "Konto ohne Passwort.",
+ "error.not_found": "Nicht gefunden.",
+ "error.org_not_found": "Organisation nicht gefunden.",
+ "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
"error.rate_limited": "Zu viele Versuche, bitte später erneut.",
"error.signup_closed": "Registrierung ist deaktiviert.",
- "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
- "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
"error.slug_taken": "Dieser Kurzname ist bereits vergeben.",
- "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.",
- "error.invalid_credentials": "E-Mail oder Passwort falsch.",
- "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.",
- "error.invalid_code": "Code ungültig.",
- "error.org_not_found": "Organisation nicht gefunden.",
+ "error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.",
+ "error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.",
+ "error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.",
+ "error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.",
+ "error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.",
+ "error.sso_invalid_issuer": "Der Issuer muss eine https-URL ohne Query und Zugangsdaten sein.",
+ "error.sso_link_required": "Es gibt bereits ein Konto mit dieser E-Mail. Melde dich mit Passwort an und verknüpfe SSO unter Sicherheit.",
+ "error.sso_not_member": "Dein Konto ist kein Mitglied dieser Organisation.",
+ "error.sso_not_provisioned": "Für diese Anmeldung gibt es kein Konto. Bitte lass dich von einem Admin einladen.",
+ "error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.",
+ "error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.",
"error.totp_already_enabled": "TOTP ist bereits aktiv.",
- "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
"error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.",
- "error.no_password": "Konto ohne Passwort.",
- "error.unsupported_locale": "Sprache wird nicht unterstützt."
+ "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
+ "error.unsupported_locale": "Sprache wird nicht unterstützt.",
+ "lang.de": "Deutsch",
+ "lang.en": "English",
+ "security.sso.heading": "Single Sign-on",
+ "security.sso.link": "SSO-Anmeldung verknüpfen",
+ "security.sso.linked": "SSO-Anmeldung verknüpft.",
+ "security.sso.none": "In dieser Organisation ist keine SSO-Anmeldung verknüpft.",
+ "security.title": "Sicherheit",
+ "security.totp.active": "aktiv",
+ "security.totp.app_code": "Code aus der App",
+ "security.totp.confirm": "Bestätigen",
+ "security.totp.current_code": "Aktueller Code",
+ "security.totp.disable": "Deaktivieren",
+ "security.totp.heading": "Zwei-Faktor (TOTP)",
+ "security.totp.inactive": "nicht eingerichtet",
+ "security.totp.qr_alt": "QR-Code für die Authenticator-App",
+ "security.totp.start": "Einrichten",
+ "sso.action.delete": "Provider löschen",
+ "sso.action.delete_confirm": "Diesen Provider löschen? Verknüpfte Anmeldungen funktionieren dann nicht mehr.",
+ "sso.action.edit": "Bearbeiten",
+ "sso.choose.title": "Anmeldung wählen",
+ "sso.field.allowed_domains": "Erlaubte E-Mail-Domains",
+ "sso.field.allowed_domains_hint": "Kommagetrennt. Gilt nur für automatisch angelegte Konten; leer erlaubt jede Domain.",
+ "sso.field.auto_provision": "Konten automatisch anlegen",
+ "sso.field.client_id": "Client-ID",
+ "sso.field.client_secret": "Client-Secret",
+ "sso.field.client_secret_keep": "unverändert",
+ "sso.field.enabled": "Aktiv",
+ "sso.field.issuer": "Issuer-URL",
+ "sso.field.name": "Name",
+ "sso.settings.add": "Provider hinzufügen",
+ "sso.settings.intro": "Mitglieder dieser Organisation können sich über euren eigenen OpenID-Connect-Identity-Provider anmelden. Tragt die Redirect-URL unten bei eurem Provider als erlaubten Callback ein.",
+ "sso.settings.login_url": "Anmelde-URL",
+ "sso.settings.redirect_url": "Redirect-URL",
+ "sso.settings.title": "Single Sign-on"
}
diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json
index 8023c23..a480d22 100644
--- a/internal/i18n/locales/en.json
+++ b/internal/i18n/locales/en.json
@@ -1,57 +1,96 @@
{
"app.network_error": "Connection failed.",
- "lang.en": "English",
- "lang.de": "Deutsch",
-
- "auth.login.title": "Sign in",
- "auth.login.totp_hint": "Enter the code from your authenticator app.",
- "auth.login.submit": "Continue",
- "auth.login.no_account": "No account yet?",
- "auth.login.to_signup": "Sign up",
- "auth.signup.title": "Create account",
- "auth.signup.submit": "Create",
- "auth.signup.to_login": "Back to sign in",
- "auth.field.name": "Name",
+ "auth.field.code": "Code",
"auth.field.email": "Email",
- "auth.field.password": "Password",
+ "auth.field.name": "Name",
"auth.field.new_password": "Password (min. {{.Min}} characters)",
"auth.field.org_name": "Organization",
"auth.field.org_slug": "Short name (a–z, 0–9, -)",
- "auth.field.code": "Code",
-
- "console.nav.security": "Security",
+ "auth.field.password": "Password",
+ "auth.login.no_account": "No account yet?",
+ "auth.login.submit": "Continue",
+ "auth.login.title": "Sign in",
+ "auth.login.to_signup": "Sign up",
+ "auth.login.totp_hint": "Enter the code from your authenticator app.",
+ "auth.signup.submit": "Create",
+ "auth.signup.title": "Create account",
+ "auth.signup.to_login": "Back to sign in",
+ "auth.sso.heading": "Single sign-on",
+ "auth.sso.org_placeholder": "Organization short name",
+ "auth.sso.submit": "Continue",
+ "common.no": "no",
+ "common.save": "Save",
+ "common.yes": "yes",
+ "console.monitors.empty": "No monitors yet.",
+ "console.monitors.title": "Monitors",
"console.nav.logout": "Sign out",
+ "console.nav.security": "Security",
+ "console.nav.sso": "SSO",
"console.totp_missing": "Your organization requires two-factor sign-in.",
"console.totp_missing_action": "Set up now",
- "console.monitors.title": "Monitors",
- "console.monitors.empty": "No monitors yet.",
-
- "security.title": "Security",
- "security.totp.heading": "Two-factor (TOTP)",
- "security.totp.active": "active",
- "security.totp.inactive": "not set up",
- "security.totp.disable": "Disable",
- "security.totp.current_code": "Current code",
- "security.totp.start": "Set up",
- "security.totp.qr_alt": "QR code for your authenticator app",
- "security.totp.app_code": "Code from the app",
- "security.totp.confirm": "Confirm",
-
+ "error.email_taken": "This email address is already registered.",
+ "error.forbidden": "You are not allowed to do this.",
"error.internal": "Internal error.",
+ "error.invalid_code": "Invalid code.",
+ "error.invalid_credentials": "Wrong email or password.",
+ "error.invalid_domain": "One of the domains is not valid.",
"error.invalid_input": "Please check your input.",
+ "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.",
+ "error.mfa_expired": "Sign-in expired, please start again.",
+ "error.no_password": "This account has no password.",
+ "error.not_found": "Not found.",
+ "error.org_not_found": "Organization not found.",
+ "error.password_too_short": "The password needs at least {{.Min}} characters.",
"error.rate_limited": "Too many attempts, please try again later.",
"error.signup_closed": "Sign-up is disabled.",
- "error.password_too_short": "The password needs at least {{.Min}} characters.",
- "error.email_taken": "This email address is already registered.",
"error.slug_taken": "This short name is already taken.",
- "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.",
- "error.invalid_credentials": "Wrong email or password.",
- "error.mfa_expired": "Sign-in expired, please start again.",
- "error.invalid_code": "Invalid code.",
- "error.org_not_found": "Organization not found.",
+ "error.sso_denied": "Sign-in was cancelled at the identity provider.",
+ "error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.",
+ "error.sso_expired": "The sign-in attempt expired, please start again.",
+ "error.sso_forbidden_address": "The issuer points to a non-public address.",
+ "error.sso_identity_taken": "This SSO sign-in is already linked to another account.",
+ "error.sso_invalid_issuer": "The issuer must be an https URL without query or credentials.",
+ "error.sso_link_required": "An account with this email already exists. Sign in with your password and link SSO under Security.",
+ "error.sso_not_member": "Your account is not a member of this organization.",
+ "error.sso_not_provisioned": "No account exists for this sign-in. Ask an administrator to invite you.",
+ "error.sso_provider_error": "The identity provider could not complete the sign-in.",
+ "error.sso_unavailable": "Single sign-on is not available for this organization.",
"error.totp_already_enabled": "TOTP is already active.",
- "error.totp_setup_expired": "Setup expired, please start again.",
"error.totp_required_by_org": "One of your organizations requires TOTP.",
- "error.no_password": "This account has no password.",
- "error.unsupported_locale": "Unsupported language."
+ "error.totp_setup_expired": "Setup expired, please start again.",
+ "error.unsupported_locale": "Unsupported language.",
+ "lang.de": "Deutsch",
+ "lang.en": "English",
+ "security.sso.heading": "Single sign-on",
+ "security.sso.link": "Link SSO sign-in",
+ "security.sso.linked": "SSO sign-in linked.",
+ "security.sso.none": "No SSO sign-in linked in this organization.",
+ "security.title": "Security",
+ "security.totp.active": "active",
+ "security.totp.app_code": "Code from the app",
+ "security.totp.confirm": "Confirm",
+ "security.totp.current_code": "Current code",
+ "security.totp.disable": "Disable",
+ "security.totp.heading": "Two-factor (TOTP)",
+ "security.totp.inactive": "not set up",
+ "security.totp.qr_alt": "QR code for your authenticator app",
+ "security.totp.start": "Set up",
+ "sso.action.delete": "Delete provider",
+ "sso.action.delete_confirm": "Delete this provider? Linked sign-ins stop working.",
+ "sso.action.edit": "Edit",
+ "sso.choose.title": "Choose sign-in",
+ "sso.field.allowed_domains": "Allowed email domains",
+ "sso.field.allowed_domains_hint": "Comma-separated. Only applies to automatically created accounts; empty allows any domain.",
+ "sso.field.auto_provision": "Create accounts automatically",
+ "sso.field.client_id": "Client ID",
+ "sso.field.client_secret": "Client secret",
+ "sso.field.client_secret_keep": "unchanged",
+ "sso.field.enabled": "Enabled",
+ "sso.field.issuer": "Issuer URL",
+ "sso.field.name": "Name",
+ "sso.settings.add": "Add provider",
+ "sso.settings.intro": "Members of this organization can sign in through your own OpenID Connect identity provider. Register the redirect URL below as an allowed callback at your provider.",
+ "sso.settings.login_url": "Sign-in URL",
+ "sso.settings.redirect_url": "Redirect URL",
+ "sso.settings.title": "Single sign-on"
}
diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js
index 9f8fb8b..6ad947f 100644
--- a/internal/web/assets/app.js
+++ b/internal/web/assets/app.js
@@ -17,24 +17,33 @@
el.classList.toggle("hidden", !text);
};
+ // Inputs inside a hidden [data-step] are skipped, checkboxes become
+ // booleans and [data-list] inputs become comma-separated arrays.
+ const serialize = (form) => {
+ const out = {};
+ for (const el of form.elements) {
+ if (!el.name || el.disabled || el.closest("[data-step]")?.hidden) continue;
+ if (el.type === "checkbox") out[el.name] = el.checked;
+ else if (el.dataset.list !== undefined)
+ out[el.name] = el.value.split(",").map((v) => v.trim()).filter(Boolean);
+ else out[el.name] = el.value;
+ }
+ return out;
+ };
+
document.addEventListener("submit", async (ev) => {
const form = ev.target.closest("form[data-api]");
if (!form) return;
ev.preventDefault();
const button = form.querySelector("button[type=submit]");
- const body = Object.fromEntries(
- [...new FormData(form)].filter(([k]) => {
- const step = form.querySelector(`[name="${k}"]`)?.closest("[data-step]");
- return !step || !step.hidden;
- }),
- );
+ const body = serialize(form);
const totpStep = form.querySelector('[data-step="totp"]');
const url = totpStep && !totpStep.hidden ? `${form.dataset.api}/totp` : form.dataset.api;
showError(form, "");
button && (button.disabled = true);
try {
- const res = await api.post(url, body);
+ const res = await api.request({ method: form.dataset.method || "post", url, data: body });
if (res.data?.status === "totp_required" && totpStep) {
form.querySelector('[data-step="password"]').hidden = true;
totpStep.hidden = false;
@@ -56,6 +65,17 @@
location.reload();
return;
}
+ const del = ev.target.closest("[data-delete]");
+ if (del) {
+ if (del.dataset.confirm && !confirm(del.dataset.confirm)) return;
+ try {
+ await api.delete(del.dataset.delete);
+ location.reload();
+ } catch (err) {
+ alert(message(err));
+ }
+ return;
+ }
if (ev.target.closest("[data-logout]")) {
await api.post("/auth/logout").catch(() => {});
location.assign("/login");
diff --git a/internal/web/auth.templ b/internal/web/auth.templ
index c0f86d6..14d9f59 100644
--- a/internal/web/auth.templ
+++ b/internal/web/auth.templ
@@ -19,6 +19,20 @@ templ Login(p Page, signupAllowed bool) {
@submit(i18n.T(ctx, "auth.login.submit"))
+
+ { i18n.T(ctx, "auth.sso.heading") }
+
+
+ { i18n.T(ctx, "auth.sso.submit") }
+
+
if signupAllowed {
{ i18n.T(ctx, "auth.login.no_account") }
diff --git a/internal/web/auth_templ.go b/internal/web/auth_templ.go
index 3e4ffba..6ed711c 100644
--- a/internal/web/auth_templ.go
+++ b/internal/web/auth_templ.go
@@ -92,38 +92,90 @@ func Login(p Page, signupAllowed bool) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var4 string
+ templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 23, Col: 108}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var7 string
+ templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.submit"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 33, Col: 134}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if signupAllowed {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var4 string
- templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account"))
+ var templ_7745c5c3_Var8 string
+ templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 24, Col: 42}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 42}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var5 string
- templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup"))
+ var templ_7745c5c3_Var9 string
+ templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 25, Col: 105}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 105}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -155,7 +207,7 @@ func Signup(p Page) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
- templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -167,7 +219,7 @@ func Signup(p Page) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -187,7 +239,7 @@ func Signup(p Page) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -203,26 +255,26 @@ func Signup(p Page) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
- templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer)
+ templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/internal/web/console.templ b/internal/web/console.templ
index 4a7a5f0..fca2b8e 100644
--- a/internal/web/console.templ
+++ b/internal/web/console.templ
@@ -4,6 +4,9 @@ import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
// Me is the signed-in user as the console templates see it.
type Me struct {
+ // IsOwner refers to the active organization.
+ IsOwner bool
+ ActiveSlug string
Email string
DisplayName string
TOTP bool
@@ -35,6 +38,9 @@ templ consoleShell(p Page, me Me) {
{ me.Orgs[0].Name }
}
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if me.TOTPMissing {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "")
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- var templ_7745c5c3_Var8 string
- templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing"))
- if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 47, Col: 42}
- }
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
- templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action"))
+ templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 48, Col: 115}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 53, Col: 42}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var10 string
+ templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 54, Col: 115}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = flash(p).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -211,7 +241,7 @@ func consoleShell(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -242,7 +272,7 @@ func Dashboard(p Page, me Me) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
- templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_Var12 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -254,39 +284,39 @@ func Dashboard(p Page, me Me) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "")
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- var templ_7745c5c3_Var12 string
- templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title"))
- if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 60, Col: 75}
- }
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
- templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty"))
+ templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 61, Col: 76}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 67, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var14 string
+ templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 68, Col: 76}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
- templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer)
+ templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var12), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -294,7 +324,13 @@ func Dashboard(p Page, me Me) templ.Component {
})
}
-func Security(p Page, me Me) templ.Component {
+// Identity is an SSO sign-in linked to the user in the active organization.
+type Identity struct {
+ Provider string
+ Email string
+}
+
+func Security(p Page, me Me, identities []Identity, canLink bool) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
@@ -311,7 +347,7 @@ func Security(p Page, me Me) templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
- templ_7745c5c3_Var15 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_Var16 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
@@ -323,51 +359,51 @@ func Security(p Page, me Me) templ.Component {
}()
}
ctx = templ.InitializeContext(ctx)
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "")
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- var templ_7745c5c3_Var16 string
- templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title"))
- if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 67, Col: 72}
- }
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var17 string
- templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading"))
+ templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 69, Col: 114}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 80, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var18 string
+ templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 82, Col: 114}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if me.TOTP {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "● ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "
● ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var18 string
- templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active"))
+ var templ_7745c5c3_Var19 string
+ templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 71, Col: 98}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 84, Col: 98}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -387,51 +423,51 @@ func Security(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "● ")
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- var templ_7745c5c3_Var19 string
- templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive"))
- if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 79, Col: 105}
- }
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
- if templ_7745c5c3_Err != nil {
- return templ_7745c5c3_Err
- }
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "● ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var20 string
- templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.start"))
+ templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 81, Col: 141}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 92, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "
![\"")]()
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var21 string
- templ_7745c5c3_Var21, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "security.totp.qr_alt")).Resolve(ctx)
+ templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.start"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 83, Col: 65}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 94, Col: 141}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" class=\"mb-3 h-48 w-48 border border-rule bg-white p-2\">")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, " ![\"")]()
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -447,18 +483,127 @@ func Security(p Page, me Me) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var23 string
+ templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 108, Col: 113}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ if len(identities) == 0 {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var24 string
+ templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 73}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ } else {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ for _, id := range identities {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "- ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var25 string
+ templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 114, Col: 69}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var26 string
+ templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 114, Col: 131}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ if canLink {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var28 string
+ templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 119, Col: 190}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
- templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var15), templ_7745c5c3_Buffer)
+ templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var16), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/internal/web/layout.templ b/internal/web/layout.templ
index 8dc679f..8919b9f 100644
--- a/internal/web/layout.templ
+++ b/internal/web/layout.templ
@@ -7,6 +7,10 @@ type Page struct {
TitleID string
CSRF string
Languages []string
+ // ErrorID and NoticeID name catalog messages shown above the content,
+ // typically after a redirect back from an SSO flow.
+ ErrorID string
+ NoticeID string
}
templ Layout(p Page) {
@@ -49,6 +53,7 @@ templ authShell(p Page) {
@languageSwitch(p.Languages)
{ i18n.T(ctx, p.TitleID) }
+ @flash(p)
{ children... }
}
@@ -73,6 +78,15 @@ templ submit(label string) {
}
+templ flash(p Page) {
+ if p.ErrorID != "" {
+ { i18n.T(ctx, p.ErrorID) }
+ }
+ if p.NoticeID != "" {
+ { i18n.T(ctx, p.NoticeID) }
+ }
+}
+
templ formError() {
}
diff --git a/internal/web/layout_templ.go b/internal/web/layout_templ.go
index 515c1ee..112f0f7 100644
--- a/internal/web/layout_templ.go
+++ b/internal/web/layout_templ.go
@@ -16,6 +16,10 @@ type Page struct {
TitleID string
CSRF string
Languages []string
+ // ErrorID and NoticeID name catalog messages shown above the content,
+ // typically after a redirect back from an SSO flow.
+ ErrorID string
+ NoticeID string
}
func Layout(p Page) templ.Component {
@@ -43,7 +47,7 @@ func Layout(p Page) templ.Component {
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.Lang(ctx)).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 14, Col: 28}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 18, Col: 28}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
@@ -61,7 +65,7 @@ func Layout(p Page) templ.Component {
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(p.CSRF).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 19, Col: 44}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 23, Col: 44}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
@@ -79,7 +83,7 @@ func Layout(p Page) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 21, Col: 34}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 25, Col: 34}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -92,7 +96,7 @@ func Layout(p Page) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "app.network_error")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 26, Col: 80}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 30, Col: 80}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
if templ_7745c5c3_Err != nil {
@@ -144,7 +148,7 @@ func languageSwitch(langs []string) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(l)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 36, Col: 50}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 40, Col: 50}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -162,7 +166,7 @@ func languageSwitch(langs []string) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(l).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 38, Col: 41}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 41}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
if templ_7745c5c3_Err != nil {
@@ -175,7 +179,7 @@ func languageSwitch(langs []string) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "lang."+l)).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 38, Col: 108}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 108}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
if templ_7745c5c3_Err != nil {
@@ -188,7 +192,7 @@ func languageSwitch(langs []string) templ.Component {
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(l)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 38, Col: 114}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 114}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -253,7 +257,7 @@ func authShell(p Page) templ.Component {
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 51, Col: 66}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 55, Col: 66}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
@@ -263,6 +267,10 @@ func authShell(p Page) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+ templ_7745c5c3_Err = flash(p).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
templ_7745c5c3_Err = templ_7745c5c3_Var11.Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
@@ -305,7 +313,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(label)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 59, Col: 90}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 64, Col: 90}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil {
@@ -318,7 +326,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templruntime.NewAttributeExpression(typ).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 62, Col: 13}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 67, Col: 13}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
if templ_7745c5c3_Err != nil {
@@ -331,7 +339,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 63, Col: 14}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 68, Col: 14}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var17)
if templ_7745c5c3_Err != nil {
@@ -344,7 +352,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(autocomplete).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 64, Col: 30}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 69, Col: 30}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
if templ_7745c5c3_Err != nil {
@@ -392,7 +400,7 @@ func submit(label string) templ.Component {
var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(label)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 72, Col: 9}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 77, Col: 9}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil {
@@ -406,6 +414,65 @@ func submit(label string) templ.Component {
})
}
+func flash(p Page) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ if p.ErrorID != "" {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var22 string
+ templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.ErrorID))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 83, Col: 88}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ if p.NoticeID != "" {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var23 string
+ templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.NoticeID))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 86, Col: 77}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ return nil
+ })
+}
+
func formError() templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
@@ -423,7 +490,7 @@ func formError() templ.Component {
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/internal/web/sso.templ b/internal/web/sso.templ
new file mode 100644
index 0000000..2651a50
--- /dev/null
+++ b/internal/web/sso.templ
@@ -0,0 +1,156 @@
+package web
+
+import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
+
+// SSOOption is one provider on the chooser page.
+type SSOOption struct {
+ Name string
+ URL string
+}
+
+templ SSOChooser(p Page, opts []SSOOption) {
+ @authShell(p) {
+
+ for _, o := range opts {
+ - { o.Name }
+ }
+
+ { i18n.T(ctx, "auth.signup.to_login") }
+ }
+}
+
+// SSOProvider is a provider row on the settings page.
+type SSOProvider struct {
+ ID string
+ Name string
+ Issuer string
+ ClientID string
+ HasSecret bool
+ AllowedDomains string
+ AutoProvision bool
+ Enabled bool
+}
+
+// SSOSettings is the data of the organization SSO page.
+type SSOSettings struct {
+ Providers []SSOProvider
+ RedirectURL string
+ LoginURL string
+}
+
+templ SSOSettingsPage(p Page, me Me, s SSOSettings) {
+ @consoleShell(p, me) {
+ { i18n.T(ctx, "sso.settings.title") }
+ { i18n.T(ctx, "sso.settings.intro") }
+
+ - { i18n.T(ctx, "sso.settings.redirect_url") }
+ - { s.RedirectURL }
+ - { i18n.T(ctx, "sso.settings.login_url") }
+ - { s.LoginURL }
+
+ if len(s.Providers) > 0 {
+
+
+
+ { i18n.T(ctx, "sso.field.name") }
+ { i18n.T(ctx, "sso.field.issuer") }
+ { i18n.T(ctx, "sso.field.auto_provision") }
+ { i18n.T(ctx, "sso.field.enabled") }
+
+
+
+
+ for _, pr := range s.Providers {
+
+ { pr.Name }
+ { pr.Issuer }
+ @yesNo(pr.AutoProvision)
+ @yesNo(pr.Enabled)
+
+
+ { i18n.T(ctx, "sso.action.edit") }
+
+ @ssoForm(pr, "put", "/org/sso/"+pr.ID)
+ { i18n.T(ctx, "sso.action.delete") }
+
+
+
+
+ }
+
+
+ }
+
+ { i18n.T(ctx, "sso.settings.add") }
+ @ssoForm(SSOProvider{Enabled: true}, "post", "/org/sso")
+
+ }
+}
+
+templ yesNo(v bool) {
+ if v {
+ ● { i18n.T(ctx, "common.yes") }
+ } else {
+ ● { i18n.T(ctx, "common.no") }
+ }
+}
+
+templ ssoForm(pr SSOProvider, method, action string) {
+
+ @formError()
+ @valueField(i18n.T(ctx, "sso.field.name"), "name", pr.Name, "", true)
+ @valueField(i18n.T(ctx, "sso.field.issuer"), "issuer", pr.Issuer, "https://login.example.com/realms/acme", true)
+ @valueField(i18n.T(ctx, "sso.field.client_id"), "client_id", pr.ClientID, "", true)
+
+ { i18n.T(ctx, "sso.field.client_secret") }
+
+
+
+ { i18n.T(ctx, "sso.field.allowed_domains") }
+
+ { i18n.T(ctx, "sso.field.allowed_domains_hint") }
+
+ @checkbox(i18n.T(ctx, "sso.field.auto_provision"), "auto_provision", pr.AutoProvision)
+ @checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", pr.Enabled)
+ @submit(i18n.T(ctx, "common.save"))
+
+}
+
+templ valueField(label, name, value, placeholder string, required bool) {
+
+ { label }
+
+
+}
+
+templ checkbox(label, name string, checked bool) {
+
+
+ { label }
+
+}
diff --git a/internal/web/sso_templ.go b/internal/web/sso_templ.go
new file mode 100644
index 0000000..5703f68
--- /dev/null
+++ b/internal/web/sso_templ.go
@@ -0,0 +1,807 @@
+// Code generated by templ - DO NOT EDIT.
+
+// templ: version: v0.3.1118
+
+package web
+
+//lint:file-ignore SA4006 This context is only used if a nested component is present.
+
+import "github.com/a-h/templ"
+import templruntime "github.com/a-h/templ/runtime"
+
+import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
+
+// SSOOption is one provider on the chooser page.
+type SSOOption struct {
+ Name string
+ URL string
+}
+
+func SSOChooser(p Page, opts []SSOOption) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ for _, o := range opts {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "- ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var4 string
+ templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 15, Col: 86}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+ templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+}
+
+// SSOProvider is a provider row on the settings page.
+type SSOProvider struct {
+ ID string
+ Name string
+ Issuer string
+ ClientID string
+ HasSecret bool
+ AllowedDomains string
+ AutoProvision bool
+ Enabled bool
+}
+
+// SSOSettings is the data of the organization SSO page.
+type SSOSettings struct {
+ Providers []SSOProvider
+ RedirectURL string
+ LoginURL string
+}
+
+func SSOSettingsPage(p Page, me Me, s SSOSettings) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var8 string
+ templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.title"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 43, Col: 76}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var9 string
+ templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.intro"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 44, Col: 82}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
- ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var10 string
+ templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.redirect_url"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 46, Col: 68}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "
- ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var11 string
+ templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(s.RedirectURL)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 47, Col: 68}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
- ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var12 string
+ templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.login_url"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 48, Col: 65}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "
- ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var13 string
+ templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(s.LoginURL)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 49, Col: 65}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ if len(s.Providers) > 0 {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var14 string
+ templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.name"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 55, Col: 71}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var15 string
+ templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.issuer"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 56, Col: 73}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var16 string
+ templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.auto_provision"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 57, Col: 81}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var17 string
+ templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.enabled"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 58, Col: 74}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ for _, pr := range s.Providers {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var18 string
+ templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(pr.Name)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 65, Col: 40}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var19 string
+ templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(pr.Issuer)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 66, Col: 70}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = yesNo(pr.AutoProvision).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = yesNo(pr.Enabled).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var20 string
+ templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.action.edit"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 71, Col: 99}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = ssoForm(pr, "put", "/org/sso/"+pr.ID).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var23 string
+ templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.action.delete"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 79, Col: 45}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var24 string
+ templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.add"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 89, Col: 109}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = ssoForm(SSOProvider{Enabled: true}, "post", "/org/sso").Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+ templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+}
+
+func yesNo(v bool) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ if v {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "● ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var26 string
+ templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.yes"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 97, Col: 62}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ } else {
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "● ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var27 string
+ templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.no"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 99, Col: 66}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ }
+ return nil
+ })
+}
+
+func ssoForm(pr SSOProvider, method, action string) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", pr.Name, "", true).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.issuer"), "issuer", pr.Issuer, "https://login.example.com/realms/acme", true).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.client_id"), "client_id", pr.ClientID, "", true).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var31 string
+ templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.client_secret"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 110, Col: 124}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var33 string
+ templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.allowed_domains"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 122, Col: 126}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var35 string
+ templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.allowed_domains_hint"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 130, Col: 94}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = checkbox(i18n.T(ctx, "sso.field.auto_provision"), "auto_provision", pr.AutoProvision).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", pr.Enabled).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = submit(i18n.T(ctx, "common.save")).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+}
+
+func valueField(label, name, value, placeholder string, required bool) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var37 string
+ templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(label)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 140, Col: 90}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+}
+
+func checkbox(label, name string, checked bool) templ.Component {
+ return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
+ templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
+ if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
+ return templ_7745c5c3_CtxErr
+ }
+ templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
+ if !templ_7745c5c3_IsBuffer {
+ defer func() {
+ templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err == nil {
+ templ_7745c5c3_Err = templ_7745c5c3_BufErr
+ }
+ }()
+ }
+ ctx = templ.InitializeContext(ctx)
+ ctx = templ.ClearChildren(ctx)
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var43 string
+ templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(label)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 154, Col: 9}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ return nil
+ })
+}
+
+var _ = templruntime.GeneratedTemplate
--
2.54.1
From dbea42e7a572f102f3336e95612f9e2bf28e2c98 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?=
Date: Sun, 22 Nov 2026 00:35:20 +0100
Subject: [PATCH 21/22] feat(auth): add single-use totp recovery codes
Codes are stored as SHA-256 hashes and consumed with one conditional
update, so concurrent use of the same code succeeds at most once.
Refs #40
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
---
internal/auth/recovery.go | 70 +++++++++++++++++++
internal/auth/recovery_test.go | 43 ++++++++++++
.../migrations/sql/00008_recovery_codes.sql | 13 ++++
internal/store/copyfrom.go | 43 ++++++++++++
internal/store/db.go | 1 +
internal/store/models.go | 7 ++
internal/store/querier.go | 4 ++
internal/store/queries/recovery_codes.sql | 12 ++++
internal/store/recovery_codes.sql.go | 55 +++++++++++++++
9 files changed, 248 insertions(+)
create mode 100644 internal/auth/recovery.go
create mode 100644 internal/auth/recovery_test.go
create mode 100644 internal/migrations/sql/00008_recovery_codes.sql
create mode 100644 internal/store/copyfrom.go
create mode 100644 internal/store/queries/recovery_codes.sql
create mode 100644 internal/store/recovery_codes.sql.go
diff --git a/internal/auth/recovery.go b/internal/auth/recovery.go
new file mode 100644
index 0000000..c1f5ad9
--- /dev/null
+++ b/internal/auth/recovery.go
@@ -0,0 +1,70 @@
+package auth
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "strings"
+)
+
+// RecoveryCodeCount is how many codes a user receives per set.
+const RecoveryCodeCount = 10
+
+// recoveryAlphabet omits characters that are easily confused on paper
+// (0/o, 1/l/i).
+const recoveryAlphabet = "abcdefghjkmnpqrstuvwxyz23456789"
+
+const recoveryLen = 10
+
+// NewRecoveryCodes returns RecoveryCodeCount codes formatted as
+// "xxxxx-xxxxx", about 49 bits each.
+func NewRecoveryCodes() []string {
+ codes := make([]string, RecoveryCodeCount)
+ for i := range codes {
+ b := make([]byte, recoveryLen)
+ for j := range b {
+ b[j] = recoveryAlphabet[randIndex(len(recoveryAlphabet))]
+ }
+ codes[i] = string(b[:recoveryLen/2]) + "-" + string(b[recoveryLen/2:])
+ }
+ return codes
+}
+
+// randIndex returns a uniform index below n using rejection sampling.
+func randIndex(n int) int {
+ limit := 256 - 256%n
+ var b [1]byte
+ for {
+ _, _ = rand.Read(b[:])
+ if int(b[0]) < limit {
+ return int(b[0]) % n
+ }
+ }
+}
+
+// NormalizeRecoveryCode strips separators and case so users can type codes
+// the way they wrote them down. It returns "" if the input cannot be a code.
+func NormalizeRecoveryCode(s string) string {
+ s = strings.Map(func(r rune) rune {
+ switch r {
+ case '-', ' ':
+ return -1
+ }
+ return r
+ }, strings.ToLower(strings.TrimSpace(s)))
+ if len(s) != recoveryLen {
+ return ""
+ }
+ for _, r := range s {
+ if !strings.ContainsRune(recoveryAlphabet, r) {
+ return ""
+ }
+ }
+ return s
+}
+
+// HashRecoveryCode hashes a normalized code. The codes carry enough entropy
+// that a fast hash suffices; attempts are rate limited.
+func HashRecoveryCode(normalized string) []byte {
+ sum := sha256.Sum256([]byte(normalized))
+ return sum[:]
+}
diff --git a/internal/auth/recovery_test.go b/internal/auth/recovery_test.go
new file mode 100644
index 0000000..6449c1a
--- /dev/null
+++ b/internal/auth/recovery_test.go
@@ -0,0 +1,43 @@
+package auth
+
+import (
+ "regexp"
+ "testing"
+)
+
+func TestNewRecoveryCodes(t *testing.T) {
+ codes := NewRecoveryCodes()
+ if len(codes) != RecoveryCodeCount {
+ t.Fatalf("len(NewRecoveryCodes()) = %d, want %d", len(codes), RecoveryCodeCount)
+ }
+ format := regexp.MustCompile(`^[a-z2-9]{5}-[a-z2-9]{5}$`)
+ seen := map[string]bool{}
+ for _, c := range codes {
+ if !format.MatchString(c) {
+ t.Errorf("code %q does not match %s", c, format)
+ }
+ if NormalizeRecoveryCode(c) == "" {
+ t.Errorf("NormalizeRecoveryCode(%q) = \"\", want the code", c)
+ }
+ if seen[c] {
+ t.Errorf("duplicate code %q", c)
+ }
+ seen[c] = true
+ }
+}
+
+func TestNormalizeRecoveryCode(t *testing.T) {
+ tests := []struct{ in, want string }{
+ {"abcde-fghjk", "abcdefghjk"},
+ {" ABCDE FGHJK ", "abcdefghjk"},
+ {"abcdefghjk", "abcdefghjk"},
+ {"123456", ""},
+ {"abcde-fghj0", ""},
+ {"abcde-fghjkm", ""},
+ }
+ for _, tt := range tests {
+ if got := NormalizeRecoveryCode(tt.in); got != tt.want {
+ t.Errorf("NormalizeRecoveryCode(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ }
+}
diff --git a/internal/migrations/sql/00008_recovery_codes.sql b/internal/migrations/sql/00008_recovery_codes.sql
new file mode 100644
index 0000000..7367935
--- /dev/null
+++ b/internal/migrations/sql/00008_recovery_codes.sql
@@ -0,0 +1,13 @@
+-- +goose Up
+-- Like users, these rows belong to a person rather than an organization and
+-- are not under row-level security.
+CREATE TABLE recovery_codes (
+ user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+ code_hash bytea NOT NULL,
+ used_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (user_id, code_hash)
+);
+
+-- +goose Down
+DROP TABLE recovery_codes;
diff --git a/internal/store/copyfrom.go b/internal/store/copyfrom.go
new file mode 100644
index 0000000..d60d6fd
--- /dev/null
+++ b/internal/store/copyfrom.go
@@ -0,0 +1,43 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: copyfrom.go
+
+package store
+
+import (
+ "context"
+)
+
+// iteratorForInsertRecoveryCodes implements pgx.CopyFromSource.
+type iteratorForInsertRecoveryCodes struct {
+ rows []InsertRecoveryCodesParams
+ skippedFirstNextCall bool
+}
+
+func (r *iteratorForInsertRecoveryCodes) Next() bool {
+ if len(r.rows) == 0 {
+ return false
+ }
+ if !r.skippedFirstNextCall {
+ r.skippedFirstNextCall = true
+ return true
+ }
+ r.rows = r.rows[1:]
+ return len(r.rows) > 0
+}
+
+func (r iteratorForInsertRecoveryCodes) Values() ([]interface{}, error) {
+ return []interface{}{
+ r.rows[0].UserID,
+ r.rows[0].CodeHash,
+ }, nil
+}
+
+func (r iteratorForInsertRecoveryCodes) Err() error {
+ return nil
+}
+
+func (q *Queries) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) {
+ return q.db.CopyFrom(ctx, []string{"recovery_codes"}, []string{"user_id", "code_hash"}, &iteratorForInsertRecoveryCodes{rows: arg})
+}
diff --git a/internal/store/db.go b/internal/store/db.go
index 24023a5..949da91 100644
--- a/internal/store/db.go
+++ b/internal/store/db.go
@@ -15,6 +15,7 @@ type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
+ CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}
func New(db DBTX) *Queries {
diff --git a/internal/store/models.go b/internal/store/models.go
index d54331e..c4adace 100644
--- a/internal/store/models.go
+++ b/internal/store/models.go
@@ -26,6 +26,13 @@ type Org struct {
RequireTotp bool
}
+type RecoveryCode struct {
+ UserID uuid.UUID
+ CodeHash []byte
+ UsedAt *time.Time
+ CreatedAt time.Time
+}
+
type SsoProvider struct {
ID uuid.UUID
OrgID uuid.UUID
diff --git a/internal/store/querier.go b/internal/store/querier.go
index 1fc7a89..267932a 100644
--- a/internal/store/querier.go
+++ b/internal/store/querier.go
@@ -13,11 +13,13 @@ import (
type Querier interface {
AddMembership(ctx context.Context, arg AddMembershipParams) error
AnyUserExists(ctx context.Context) (bool, error)
+ CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
+ DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error
DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error)
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
DisableTOTP(ctx context.Context, id uuid.UUID) error
@@ -29,6 +31,7 @@ type Querier interface {
GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error)
GetUser(ctx context.Context, id uuid.UUID) (User, error)
GetUserByEmail(ctx context.Context, email string) (User, error)
+ InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error)
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
@@ -42,6 +45,7 @@ type Querier interface {
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
+ UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error)
}
var _ Querier = (*Queries)(nil)
diff --git a/internal/store/queries/recovery_codes.sql b/internal/store/queries/recovery_codes.sql
new file mode 100644
index 0000000..9e1abde
--- /dev/null
+++ b/internal/store/queries/recovery_codes.sql
@@ -0,0 +1,12 @@
+-- name: DeleteRecoveryCodes :exec
+DELETE FROM recovery_codes WHERE user_id = $1;
+
+-- name: InsertRecoveryCodes :copyfrom
+INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2);
+
+-- name: UseRecoveryCode :execrows
+UPDATE recovery_codes SET used_at = now()
+WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL;
+
+-- name: CountUnusedRecoveryCodes :one
+SELECT count(*) FROM recovery_codes WHERE user_id = $1 AND used_at IS NULL;
diff --git a/internal/store/recovery_codes.sql.go b/internal/store/recovery_codes.sql.go
new file mode 100644
index 0000000..c296d9a
--- /dev/null
+++ b/internal/store/recovery_codes.sql.go
@@ -0,0 +1,55 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: recovery_codes.sql
+
+package store
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+)
+
+const countUnusedRecoveryCodes = `-- name: CountUnusedRecoveryCodes :one
+SELECT count(*) FROM recovery_codes WHERE user_id = $1 AND used_at IS NULL
+`
+
+func (q *Queries) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countUnusedRecoveryCodes, userID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const deleteRecoveryCodes = `-- name: DeleteRecoveryCodes :exec
+DELETE FROM recovery_codes WHERE user_id = $1
+`
+
+func (q *Queries) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error {
+ _, err := q.db.Exec(ctx, deleteRecoveryCodes, userID)
+ return err
+}
+
+type InsertRecoveryCodesParams struct {
+ UserID uuid.UUID
+ CodeHash []byte
+}
+
+const useRecoveryCode = `-- name: UseRecoveryCode :execrows
+UPDATE recovery_codes SET used_at = now()
+WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL
+`
+
+type UseRecoveryCodeParams struct {
+ UserID uuid.UUID
+ CodeHash []byte
+}
+
+func (q *Queries) UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) {
+ result, err := q.db.Exec(ctx, useRecoveryCode, arg.UserID, arg.CodeHash)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
--
2.54.1
From 7b063d2cd892397b70673f3581cac5155cfeb2c8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?=
Date: Sun, 22 Nov 2026 00:35:20 +0100
Subject: [PATCH 22/22] feat(api): accept recovery codes as second factor and
let users regenerate them
Enabling TOTP returns ten codes that are shown once. Disabling TOTP and
regenerating codes require the password plus a current code.
Closes #40
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
---
internal/api/auth.go | 9 +-
internal/api/me.go | 136 +++++++++++----
internal/api/pages.go | 11 +-
internal/api/recovery_test.go | 87 ++++++++++
internal/api/server.go | 1 +
internal/api/sso_test.go | 5 +
internal/i18n/i18n_test.go | 5 +
internal/i18n/locales/de.json | 11 +-
internal/i18n/locales/en.json | 11 +-
internal/web/assets/app.js | 10 ++
internal/web/console.templ | 45 ++++-
internal/web/console_templ.go | 302 ++++++++++++++++++++++++++--------
12 files changed, 510 insertions(+), 123 deletions(-)
create mode 100644 internal/api/recovery_test.go
diff --git a/internal/api/auth.go b/internal/api/auth.go
index f650cd4..8f9e229 100644
--- a/internal/api/auth.go
+++ b/internal/api/auth.go
@@ -167,12 +167,17 @@ func (s *Server) login(c *gin.Context) {
s.finishLogin(c, user.ID)
}
+// secondFactorRequest carries a TOTP code or a recovery code.
+type secondFactorRequest struct {
+ Code string `json:"code" binding:"required,max=32"`
+}
+
type totpRequest struct {
Code string `json:"code" binding:"required,len=6,numeric"`
}
func (s *Server) loginTOTP(c *gin.Context) {
- var req totpRequest
+ var req secondFactorRequest
if !bind(c, &req) {
return
}
@@ -195,7 +200,7 @@ func (s *Server) loginTOTP(c *gin.Context) {
internalError(c, err)
return
}
- ok, err := s.verifyUserTOTP(ctx, userID, req.Code)
+ ok, err := s.verifySecondFactor(ctx, userID, req.Code)
if err != nil {
internalError(c, err)
return
diff --git a/internal/api/me.go b/internal/api/me.go
index d60e2b6..4d26dbd 100644
--- a/internal/api/me.go
+++ b/internal/api/me.go
@@ -37,6 +37,7 @@ type meView struct {
Orgs []orgView `json:"orgs"`
// Set when an org the user belongs to enforces TOTP and the user has none.
TOTPEnrollmentRequired bool `json:"totp_enrollment_required"`
+ RecoveryCodesLeft int `json:"recovery_codes_left"`
}
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
@@ -46,11 +47,15 @@ func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error)
if err != nil {
return err
}
+ left, err := q.CountUnusedRecoveryCodes(ctx, sess.UserID)
+ if err != nil {
+ return err
+ }
orgs, err := q.ListUserOrgs(ctx, sess.UserID)
if err != nil {
return err
}
- me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}}
+ me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left)}
for _, o := range orgs {
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
if o.RequireTotp && !me.TOTP {
@@ -154,32 +159,85 @@ func (s *Server) totpEnable(c *gin.Context) {
return
}
sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:])
+ codes := auth.NewRecoveryCodes()
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
- return q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret})
+ if err := q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret}); err != nil {
+ return err
+ }
+ return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
})
if err != nil {
internalError(c, err)
return
}
_ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err()
- c.Status(http.StatusNoContent)
+ c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
}
-type totpDisableRequest struct {
+func replaceRecoveryCodes(ctx context.Context, q *store.Queries, user uuid.UUID, codes []string) error {
+ if err := q.DeleteRecoveryCodes(ctx, user); err != nil {
+ return err
+ }
+ rows := make([]store.InsertRecoveryCodesParams, len(codes))
+ for i, c := range codes {
+ rows[i] = store.InsertRecoveryCodesParams{UserID: user, CodeHash: auth.HashRecoveryCode(auth.NormalizeRecoveryCode(c))}
+ }
+ _, err := q.InsertRecoveryCodes(ctx, rows)
+ return err
+}
+
+// reauthRequest confirms a sensitive change with the password and a second
+// factor, so a hijacked session alone cannot weaken the account.
+type reauthRequest struct {
Password string `json:"password" binding:"required,max=1024"`
- Code string `json:"code" binding:"required,len=6,numeric"`
+ Code string `json:"code" binding:"required,max=32"`
+}
+
+// reauthenticate checks req for the session user and writes the error
+// response itself when it fails.
+func (s *Server) reauthenticate(c *gin.Context, req reauthRequest) bool {
+ ctx := c.Request.Context()
+ sess := auth.Current(c)
+ if !s.limit(c, "reauth:"+sess.UserID.String(), 5, 15*time.Minute) {
+ return false
+ }
+ var user store.User
+ err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
+ var err error
+ user, err = q.GetUser(ctx, sess.UserID)
+ return err
+ })
+ if err != nil {
+ internalError(c, err)
+ return false
+ }
+ if user.PasswordHash == nil {
+ fail(c, http.StatusConflict, "no_password")
+ return false
+ }
+ if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
+ invalidCredentials(c)
+ return false
+ }
+ ok, err := s.verifySecondFactor(ctx, sess.UserID, req.Code)
+ if err != nil {
+ internalError(c, err)
+ return false
+ }
+ if !ok {
+ fail(c, http.StatusUnauthorized, "invalid_code")
+ return false
+ }
+ return true
}
func (s *Server) totpDisable(c *gin.Context) {
- var req totpDisableRequest
+ var req reauthRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
sess := auth.Current(c)
- if !s.limit(c, "totp_disable:"+sess.UserID.String(), 5, 15*time.Minute) {
- return
- }
me, err := s.loadMe(ctx, sess)
if err != nil {
internalError(c, err)
@@ -191,33 +249,14 @@ func (s *Server) totpDisable(c *gin.Context) {
return
}
}
- var user store.User
- err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
- var err error
- user, err = q.GetUser(ctx, sess.UserID)
- return err
- })
- if err != nil {
- internalError(c, err)
- return
- }
- if user.PasswordHash == nil {
- fail(c, http.StatusConflict, "no_password")
- return
- }
- if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
- invalidCredentials(c)
- return
- }
- if ok, err := s.verifyUserTOTP(ctx, sess.UserID, req.Code); err != nil {
- internalError(c, err)
- return
- } else if !ok {
- fail(c, http.StatusUnauthorized, "invalid_code")
+ if !s.reauthenticate(c, req) {
return
}
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
- return q.DisableTOTP(ctx, sess.UserID)
+ if err := q.DisableTOTP(ctx, sess.UserID); err != nil {
+ return err
+ }
+ return q.DeleteRecoveryCodes(ctx, sess.UserID)
})
if err != nil {
internalError(c, err)
@@ -226,9 +265,38 @@ func (s *Server) totpDisable(c *gin.Context) {
c.Status(http.StatusNoContent)
}
+func (s *Server) regenerateRecoveryCodes(c *gin.Context) {
+ var req reauthRequest
+ if !bind(c, &req) || !s.reauthenticate(c, req) {
+ return
+ }
+ ctx := c.Request.Context()
+ sess := auth.Current(c)
+ codes := auth.NewRecoveryCodes()
+ err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
+ return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
+ })
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
+}
+
var errNoTOTP = errors.New("api: user has no totp")
-func (s *Server) verifyUserTOTP(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
+// verifySecondFactor accepts a current TOTP code or an unused recovery code,
+// which is consumed.
+func (s *Server) verifySecondFactor(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
+ if rc := auth.NormalizeRecoveryCode(code); rc != "" {
+ var n int64
+ err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
+ var err error
+ n, err = q.UseRecoveryCode(ctx, store.UseRecoveryCodeParams{UserID: userID, CodeHash: auth.HashRecoveryCode(rc)})
+ return err
+ })
+ return n == 1, err
+ }
var user store.User
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
var err error
diff --git a/internal/api/pages.go b/internal/api/pages.go
index 398e84f..33c8b26 100644
--- a/internal/api/pages.go
+++ b/internal/api/pages.go
@@ -165,11 +165,12 @@ func (s *Server) ssoSettingsPage(c *gin.Context) {
func toWebMe(m meView) web.Me {
out := web.Me{
- Email: m.Email,
- DisplayName: m.DisplayName,
- TOTP: m.TOTP,
- ActiveOrg: m.ActiveOrg.String(),
- TOTPMissing: m.TOTPEnrollmentRequired,
+ Email: m.Email,
+ DisplayName: m.DisplayName,
+ TOTP: m.TOTP,
+ ActiveOrg: m.ActiveOrg.String(),
+ TOTPMissing: m.TOTPEnrollmentRequired,
+ RecoveryCodesLeft: m.RecoveryCodesLeft,
}
for _, o := range m.Orgs {
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
diff --git a/internal/api/recovery_test.go b/internal/api/recovery_test.go
new file mode 100644
index 0000000..58f0368
--- /dev/null
+++ b/internal/api/recovery_test.go
@@ -0,0 +1,87 @@
+package api_test
+
+import (
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/pquerna/otp/totp"
+)
+
+// enableTOTP turns on TOTP for b and returns the secret and recovery codes.
+func (b *browser) enableTOTP() (string, []string) {
+ b.t.Helper()
+ st, setup := b.do("POST", "/api/v1/me/totp/setup", nil)
+ if st != http.StatusOK {
+ b.t.Fatalf("totp setup = %d %v", st, setup)
+ }
+ secret := setup["secret"].(string)
+ code, _ := totp.GenerateCode(secret, time.Now())
+ st, body := b.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code})
+ if st != http.StatusOK {
+ b.t.Fatalf("totp enable = %d %v", st, body)
+ }
+ var codes []string
+ for _, c := range body["recovery_codes"].([]any) {
+ codes = append(codes, c.(string))
+ }
+ return secret, codes
+}
+
+func TestRecoveryCodes(t *testing.T) {
+ e := newEnv(t)
+ email := uniq("r") + "@example.test"
+ owner := e.browser(t)
+ owner.signup(email, uniq("rec-"))
+ _, codes := owner.enableTOTP()
+ if len(codes) != 10 {
+ t.Fatalf("enable returned %d recovery codes, want 10", len(codes))
+ }
+
+ login := func(code string) (int, map[string]any) {
+ b := e.browser(t)
+ if st, body := b.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "correct horse battery"}); body["status"] != "totp_required" {
+ t.Fatalf("login = %d %v, want totp_required", st, body)
+ }
+ return b.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": code})
+ }
+
+ if st, body := login(codes[0]); st != http.StatusOK {
+ t.Fatalf("login with recovery code = %d %v, want 200", st, body)
+ }
+ if st, _ := login(codes[0]); st != http.StatusUnauthorized {
+ t.Errorf("login with used recovery code = %d, want 401", st)
+ }
+ if st, _ := login(" " + upper(codes[1][:5]) + " " + codes[1][6:]); st != http.StatusOK {
+ t.Errorf("login with reformatted recovery code = %d, want 200", st)
+ }
+ if _, me := owner.do("GET", "/api/v1/me", nil); me["recovery_codes_left"] != float64(8) {
+ t.Errorf("recovery_codes_left = %v, want 8", me["recovery_codes_left"])
+ }
+
+ st, body := owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "correct horse battery", "code": codes[2]})
+ if st != http.StatusOK || len(body["recovery_codes"].([]any)) != 10 {
+ t.Fatalf("regenerate = %d %v, want 200 with 10 codes", st, body)
+ }
+ if st, _ := login(codes[3]); st != http.StatusUnauthorized {
+ t.Errorf("login with code from replaced set = %d, want 401", st)
+ }
+ if st, _ := login(body["recovery_codes"].([]any)[0].(string)); st != http.StatusOK {
+ t.Errorf("login with code from new set = %d, want 200", st)
+ }
+
+ st, _ = owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "wrong password!!", "code": codes[4]})
+ if st != http.StatusUnauthorized {
+ t.Errorf("regenerate with wrong password = %d, want 401", st)
+ }
+}
+
+func upper(s string) string {
+ b := []byte(s)
+ for i, c := range b {
+ if c >= 'a' && c <= 'z' {
+ b[i] = c - 32
+ }
+ }
+ return string(b)
+}
diff --git a/internal/api/server.go b/internal/api/server.go
index c0ba9d3..2687d31 100644
--- a/internal/api/server.go
+++ b/internal/api/server.go
@@ -83,6 +83,7 @@ func (s *Server) Mount(r gin.IRouter) {
me.POST("/totp/setup", s.totpSetup)
me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable)
+ me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes)
org := v1.Group("/org", auth.Require(), s.requireOwner())
org.GET("/sso", s.listSSOProviders)
diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go
index 9c9d57d..0c3ace2 100644
--- a/internal/api/sso_test.go
+++ b/internal/api/sso_test.go
@@ -57,6 +57,11 @@ func newEnv(t *testing.T) *env {
}
rdb := redis.NewClient(opts)
t.Cleanup(func() { _ = rdb.Close() })
+ // UPTIME_TEST_REDIS_URL must name a database reserved for tests; clearing
+ // it resets rate limits left over from earlier runs.
+ if err := rdb.FlushDB(ctx).Err(); err != nil {
+ t.Fatalf("FLUSHDB failed: %v", err)
+ }
key := make([]byte, 32)
_, _ = rand.Read(key)
diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go
index 998a6d6..c59d879 100644
--- a/internal/i18n/i18n_test.go
+++ b/internal/i18n/i18n_test.go
@@ -149,6 +149,11 @@ func TestT(t *testing.T) {
if got, want := T(ctx, "error.password_too_short", "Min", 12), "Das Passwort braucht mindestens 12 Zeichen."; got != want {
t.Errorf("T(de, password_too_short) = %q, want %q", got, want)
}
+ for n, want := range map[int]string{1: "1 Wiederherstellungscode übrig", 3: "3 Wiederherstellungscodes übrig"} {
+ if got := T(ctx, "security.recovery.left", "Count", n); got != want {
+ t.Errorf("T(de, recovery.left, %d) = %q, want %q", n, got, want)
+ }
+ }
if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want {
t.Errorf("T(missing) = %q, want %q", got, want)
}
diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json
index df5e12e..e0648c5 100644
--- a/internal/i18n/locales/de.json
+++ b/internal/i18n/locales/de.json
@@ -11,7 +11,7 @@
"auth.login.submit": "Weiter",
"auth.login.title": "Anmelden",
"auth.login.to_signup": "Registrieren",
- "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.",
+ "auth.login.totp_hint": "Code aus der Authenticator-App oder einen Wiederherstellungscode eingeben.",
"auth.signup.submit": "Anlegen",
"auth.signup.title": "Konto anlegen",
"auth.signup.to_login": "Zur Anmeldung",
@@ -61,6 +61,13 @@
"error.unsupported_locale": "Sprache wird nicht unterstützt.",
"lang.de": "Deutsch",
"lang.en": "English",
+ "security.recovery.left": {
+ "one": "{{.Count}} Wiederherstellungscode übrig",
+ "other": "{{.Count}} Wiederherstellungscodes übrig"
+ },
+ "security.recovery.regenerate": "Neue Wiederherstellungscodes erzeugen",
+ "security.recovery.save_now": "Bewahre diese Wiederherstellungscodes sicher auf. Jeder funktioniert einmal, falls du deinen Authenticator verlierst. Sie werden nicht erneut angezeigt.",
+ "security.recovery.saved": "Ich habe sie gespeichert",
"security.sso.heading": "Single Sign-on",
"security.sso.link": "SSO-Anmeldung verknüpfen",
"security.sso.linked": "SSO-Anmeldung verknüpft.",
@@ -69,7 +76,7 @@
"security.totp.active": "aktiv",
"security.totp.app_code": "Code aus der App",
"security.totp.confirm": "Bestätigen",
- "security.totp.current_code": "Aktueller Code",
+ "security.totp.current_code": "Aktueller Code oder Wiederherstellungscode",
"security.totp.disable": "Deaktivieren",
"security.totp.heading": "Zwei-Faktor (TOTP)",
"security.totp.inactive": "nicht eingerichtet",
diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json
index a480d22..9ca4d53 100644
--- a/internal/i18n/locales/en.json
+++ b/internal/i18n/locales/en.json
@@ -11,7 +11,7 @@
"auth.login.submit": "Continue",
"auth.login.title": "Sign in",
"auth.login.to_signup": "Sign up",
- "auth.login.totp_hint": "Enter the code from your authenticator app.",
+ "auth.login.totp_hint": "Enter the code from your authenticator app or one of your recovery codes.",
"auth.signup.submit": "Create",
"auth.signup.title": "Create account",
"auth.signup.to_login": "Back to sign in",
@@ -61,6 +61,13 @@
"error.unsupported_locale": "Unsupported language.",
"lang.de": "Deutsch",
"lang.en": "English",
+ "security.recovery.left": {
+ "one": "{{.Count}} recovery code left",
+ "other": "{{.Count}} recovery codes left"
+ },
+ "security.recovery.regenerate": "Generate new recovery codes",
+ "security.recovery.save_now": "Store these recovery codes somewhere safe. Each works once if you lose your authenticator. They will not be shown again.",
+ "security.recovery.saved": "I have saved them",
"security.sso.heading": "Single sign-on",
"security.sso.link": "Link SSO sign-in",
"security.sso.linked": "SSO sign-in linked.",
@@ -69,7 +76,7 @@
"security.totp.active": "active",
"security.totp.app_code": "Code from the app",
"security.totp.confirm": "Confirm",
- "security.totp.current_code": "Current code",
+ "security.totp.current_code": "Current code or recovery code",
"security.totp.disable": "Disable",
"security.totp.heading": "Two-factor (TOTP)",
"security.totp.inactive": "not set up",
diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js
index 6ad947f..a95524c 100644
--- a/internal/web/assets/app.js
+++ b/internal/web/assets/app.js
@@ -44,6 +44,16 @@
button && (button.disabled = true);
try {
const res = await api.request({ method: form.dataset.method || "post", url, data: body });
+ if (form.dataset.showCodes !== undefined && res.data?.recovery_codes) {
+ const out = form.querySelector("[data-recovery-output]");
+ const list = out.querySelector("[data-recovery-list]");
+ list.replaceChildren(
+ ...res.data.recovery_codes.map((c) => Object.assign(document.createElement("li"), { textContent: c })),
+ );
+ for (const el of form.elements) el.disabled = true;
+ out.hidden = false;
+ return;
+ }
if (res.data?.status === "totp_required" && totpStep) {
form.querySelector('[data-step="password"]').hidden = true;
totpStep.hidden = false;
diff --git a/internal/web/console.templ b/internal/web/console.templ
index fca2b8e..604d2a9 100644
--- a/internal/web/console.templ
+++ b/internal/web/console.templ
@@ -13,6 +13,8 @@ type Me struct {
ActiveOrg string
Orgs []Org
TOTPMissing bool
+ // RecoveryCodesLeft counts unused TOTP recovery codes.
+ RecoveryCodesLeft int
}
// Org is one entry of the organization switcher.
@@ -81,13 +83,29 @@ templ Security(p Page, me Me, identities []Identity, canLink bool) {
{ i18n.T(ctx, "security.totp.heading") }
if me.TOTP {
- ● { i18n.T(ctx, "security.totp.active") }
-
- @formError()
- @field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
- @field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true)
- @submit(i18n.T(ctx, "security.totp.disable"))
-
+ ● { i18n.T(ctx, "security.totp.active") }
+ = 3) }>
+ { i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft) }
+
+
+ { i18n.T(ctx, "security.recovery.regenerate") }
+
+ @formError()
+ @field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
+ @field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true)
+ @submit(i18n.T(ctx, "security.recovery.regenerate"))
+ @recoveryOutput()
+
+
+
+ { i18n.T(ctx, "security.totp.disable") }
+
+ @formError()
+ @field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
+ @field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true)
+ @submit(i18n.T(ctx, "security.totp.disable"))
+
+
} else {
● { i18n.T(ctx, "security.totp.inactive") }
@@ -95,10 +113,11 @@ templ Security(p Page, me Me, identities []Identity, canLink bool) {
-
+
@formError()
@field(i18n.T(ctx, "security.totp.app_code"), "code", "text", "one-time-code", true)
@submit(i18n.T(ctx, "security.totp.confirm"))
+ @recoveryOutput()
@@ -121,3 +140,13 @@ templ Security(p Page, me Me, identities []Identity, canLink bool) {
}
}
+
+// recoveryOutput is filled by app.js with codes returned by the API; they
+// are shown once and never rendered by the server.
+templ recoveryOutput() {
+
+}
diff --git a/internal/web/console_templ.go b/internal/web/console_templ.go
index 3c16bfe..6f6c00c 100644
--- a/internal/web/console_templ.go
+++ b/internal/web/console_templ.go
@@ -22,6 +22,8 @@ type Me struct {
ActiveOrg string
Orgs []Org
TOTPMissing bool
+ // RecoveryCodesLeft counts unused TOTP recovery codes.
+ RecoveryCodesLeft int
}
// Org is one entry of the organization switcher.
@@ -79,7 +81,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(o.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 34, Col: 27}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 36, Col: 27}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
@@ -102,7 +104,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 34, Col: 73}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 36, Col: 73}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -125,7 +127,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(me.Orgs[0].Name)
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 38, Col: 47}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 47}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -148,7 +150,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.sso"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 42, Col: 96}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 44, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
@@ -166,7 +168,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.security"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 44, Col: 105}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 46, Col: 105}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -179,7 +181,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 45, Col: 94}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 47, Col: 94}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -205,7 +207,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 53, Col: 42}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 55, Col: 42}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -218,7 +220,7 @@ func consoleShell(p Page, me Me) templ.Component {
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 54, Col: 115}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 56, Col: 115}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
@@ -291,7 +293,7 @@ func Dashboard(p Page, me Me) templ.Component {
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 67, Col: 75}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 69, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil {
@@ -304,7 +306,7 @@ func Dashboard(p Page, me Me) templ.Component {
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 68, Col: 76}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 70, Col: 76}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
@@ -366,7 +368,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen
var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 80, Col: 72}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 82, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil {
@@ -379,7 +381,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen
var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 82, Col: 114}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 84, Col: 114}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil {
@@ -390,20 +392,123 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen
return templ_7745c5c3_Err
}
if me.TOTP {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "● ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "
● ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 84, Col: 98}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 86, Col: 98}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ {
+ templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer
+ templ_7745c5c3_Buffer := templ.GetBuffer()
+ var templ_7745c5c3_ElementScripts []templ.ComponentScript
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "= 3)}
+ templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var20...)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var21 string
+ templ_7745c5c3_Var21, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var20).String()).Resolve(ctx)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 1, Col: 0}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\"")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_ElementScripts...)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteTo(templ_7745c5c3_ElementWriter)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ.ReleaseBuffer(templ_7745c5c3_Buffer)
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, ">")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var22 string
+ templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 88, Col: 75}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var23 string
+ templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 91, Col: 116}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = submit(i18n.T(ctx, "security.recovery.regenerate")).Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = recoveryOutput().Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, " ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var24 string
+ templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable"))
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 101, Col: 109}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "
")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -423,51 +528,51 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, " ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "● ")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "
● ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var20 string
- templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive"))
+ var templ_7745c5c3_Var25 string
+ templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 92, Col: 105}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 105}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- var templ_7745c5c3_Var21 string
- templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.start"))
+ var templ_7745c5c3_Var26 string
+ templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.start"))
if templ_7745c5c3_Err != nil {
- return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 94, Col: 141}
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 112, Col: 141}
}
- _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, " ![\"")]()
![\"")]()
")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" class=\"mb-3 h-48 w-48 border border-rule bg-white p-2\"> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -483,121 +588,125 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, " ")
+ templ_7745c5c3_Err = recoveryOutput().Render(ctx, templ_7745c5c3_Buffer)
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, " ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var24 string - templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) + var templ_7745c5c3_Var29 string + templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 129, Col: 73} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var35 string + templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.save_now")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 148, Col: 69} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "