refactor: rework backend to frontend context

This commit is contained in:
Stavros
2026-05-10 19:17:22 +03:00
parent 25017a76c9
commit 32595e351d
16 changed files with 326 additions and 162 deletions
+8
View File
@@ -67,6 +67,8 @@ func (app *BootstrapApp) Setup() error {
log.Init()
app.log = log
app.log.App.Info().Msgf("Starting Tinyauth version: %s", model.Version)
// get app url
if app.config.AppURL == "" {
return errors.New("app url cannot be empty, perhaps config loading failed")
@@ -79,6 +81,7 @@ func (app *BootstrapApp) Setup() error {
}
app.runtime.AppURL = appUrl.Scheme + "://" + appUrl.Host
app.runtime.TrustedDomains = append(app.runtime.TrustedDomains, app.runtime.AppURL)
// validate session config
if app.config.Auth.SessionMaxLifetime != 0 && app.config.Auth.SessionMaxLifetime < app.config.Auth.SessionExpiry {
@@ -229,6 +232,11 @@ func (app *BootstrapApp) Setup() error {
app.runtime.ConfiguredProviders = configuredProviders
// throw in tailscale if it's configured just before setting up the controllers
if app.services.tailscaleService != nil {
app.runtime.TrustedDomains = append(app.runtime.TrustedDomains, "https://"+app.services.tailscaleService.GetHostname())
}
// setup router
err = app.setupRouter()
+99 -59
View File
@@ -1,40 +1,74 @@
package controller
import (
"fmt"
"net/url"
"github.com/tinyauthapp/tinyauth/internal/model"
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
"github.com/gin-gonic/gin"
)
// UCR -> User Context Response
type UCRAuth struct {
Authenticated bool `json:"authenticated"`
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
ProviderID string `json:"providerId"`
}
type UCROAuth struct {
Active bool `json:"active"`
DisplayName string `json:"displayName"`
}
type UCRTOTP struct {
Pending bool `json:"pending"`
}
type UCRTailscale struct {
NodeName string `json:"nodeName,omitempty"`
}
type UserContextResponse struct {
Status int `json:"status"`
Message string `json:"message"`
IsLoggedIn bool `json:"isLoggedIn"`
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
Provider string `json:"provider"`
OAuth bool `json:"oauth"`
TOTPPending bool `json:"totpPending"`
OAuthName string `json:"oauthName"`
TailscaleNodeName string `json:"tailscaleNodeName,omitempty"`
Status int `json:"status"`
Message string `json:"message"`
Auth UCRAuth `json:"auth"`
OAuth UCROAuth `json:"oauth"`
TOTP UCRTOTP `json:"totp"`
Tailscale UCRTailscale `json:"tailscale"`
}
// ACR -> App Context Response
type ACRAuth struct {
Providers []model.Provider `json:"providers"`
}
type ACROAuth struct {
AutoRedirect string `json:"autoRedirect"`
}
type ACRUI struct {
Title string `json:"title"`
ForgotPasswordMessage string `json:"forgotPasswordMessage"`
BackgroundImage string `json:"backgroundImage"`
WarningsEnabled bool `json:"warningsEnabled"`
}
type ACRApp struct {
AppURL string `json:"appUrl"`
CookieDomain string `json:"cookieDomain"`
TrustedDomains []string `json:"trustedDomains"`
}
type AppContextResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Providers []model.Provider `json:"providers"`
Title string `json:"title"`
AppURL string `json:"appUrl"`
CookieDomain string `json:"cookieDomain"`
ForgotPasswordMessage string `json:"forgotPasswordMessage"`
BackgroundImage string `json:"backgroundImage"`
OAuthAutoRedirect string `json:"oauthAutoRedirect"`
WarningsEnabled bool `json:"warningsEnabled"`
Status int `json:"status"`
Message string `json:"message"`
Auth ACRAuth `json:"auth"`
OAuth ACROAuth `json:"oauth"`
UI ACRUI `json:"ui"`
App ACRApp `json:"app"`
}
type ContextController struct {
@@ -72,52 +106,58 @@ func (controller *ContextController) userContextHandler(c *gin.Context) {
if err != nil {
controller.log.App.Error().Err(err).Msg("Failed to create user context from request")
c.JSON(200, UserContextResponse{
Status: 401,
Message: "Unauthorized",
IsLoggedIn: false,
Status: 401,
Message: "Unauthorized",
Auth: UCRAuth{Authenticated: false},
})
return
}
userContext := UserContextResponse{
Status: 200,
Message: "Success",
IsLoggedIn: context.Authenticated,
Username: context.GetUsername(),
Name: context.GetName(),
Email: context.GetEmail(),
Provider: context.GetProviderID(),
OAuth: context.IsOAuth(),
TOTPPending: context.TOTPPending(),
OAuthName: context.OAuthName(),
TailscaleNodeName: context.TailscaleNodeName(),
Status: 200,
Message: "Success",
Auth: UCRAuth{
Authenticated: context.Authenticated,
Username: context.GetUsername(),
Name: context.GetName(),
Email: context.GetEmail(),
ProviderID: context.GetProviderID(),
},
OAuth: UCROAuth{
Active: context.IsOAuth(),
DisplayName: context.OAuthName(),
},
TOTP: UCRTOTP{
Pending: context.TOTPPending(),
},
Tailscale: UCRTailscale{
NodeName: context.TailscaleNodeName(),
},
}
c.JSON(200, userContext)
}
func (controller *ContextController) appContextHandler(c *gin.Context) {
appUrl, err := url.Parse(controller.runtime.AppURL)
if err != nil {
controller.log.App.Error().Err(err).Msg("Failed to parse app URL")
c.JSON(500, gin.H{
"status": 500,
"message": "Internal Server Error",
})
return
}
c.JSON(200, AppContextResponse{
Status: 200,
Message: "Success",
Providers: controller.runtime.ConfiguredProviders,
Title: controller.config.UI.Title,
AppURL: fmt.Sprintf("%s://%s", appUrl.Scheme, appUrl.Host),
CookieDomain: controller.runtime.CookieDomain,
ForgotPasswordMessage: controller.config.UI.ForgotPasswordMessage,
BackgroundImage: controller.config.UI.BackgroundImage,
OAuthAutoRedirect: controller.config.OAuth.AutoRedirect,
WarningsEnabled: controller.config.UI.WarningsEnabled,
Status: 200,
Message: "Success",
Auth: ACRAuth{
Providers: controller.runtime.ConfiguredProviders,
},
OAuth: ACROAuth{
AutoRedirect: controller.config.OAuth.AutoRedirect,
},
UI: ACRUI{
Title: controller.config.UI.Title,
ForgotPasswordMessage: controller.config.UI.ForgotPasswordMessage,
BackgroundImage: controller.config.UI.BackgroundImage,
WarningsEnabled: controller.config.UI.WarningsEnabled,
},
App: ACRApp{
AppURL: controller.runtime.AppURL,
CookieDomain: controller.runtime.CookieDomain,
TrustedDomains: controller.runtime.TrustedDomains,
},
})
}
+28 -17
View File
@@ -34,16 +34,25 @@ func TestContextController(t *testing.T) {
path: "/api/context/app",
expected: func() string {
expectedAppContextResponse := controller.AppContextResponse{
Status: 200,
Message: "Success",
Providers: runtime.ConfiguredProviders,
Title: cfg.UI.Title,
AppURL: runtime.AppURL,
CookieDomain: runtime.CookieDomain,
ForgotPasswordMessage: cfg.UI.ForgotPasswordMessage,
BackgroundImage: cfg.UI.BackgroundImage,
OAuthAutoRedirect: cfg.OAuth.AutoRedirect,
WarningsEnabled: cfg.UI.WarningsEnabled,
Status: 200,
Message: "Success",
Auth: controller.ACRAuth{
Providers: runtime.ConfiguredProviders,
},
OAuth: controller.ACROAuth{
AutoRedirect: cfg.OAuth.AutoRedirect,
},
UI: controller.ACRUI{
Title: cfg.UI.Title,
ForgotPasswordMessage: cfg.UI.ForgotPasswordMessage,
BackgroundImage: cfg.UI.BackgroundImage,
WarningsEnabled: cfg.UI.WarningsEnabled,
},
App: controller.ACRApp{
AppURL: runtime.AppURL,
CookieDomain: runtime.CookieDomain,
TrustedDomains: runtime.TrustedDomains,
},
}
bytes, err := json.Marshal(expectedAppContextResponse)
require.NoError(t, err)
@@ -84,13 +93,15 @@ func TestContextController(t *testing.T) {
path: "/api/context/user",
expected: func() string {
expectedUserContextResponse := controller.UserContextResponse{
Status: 200,
Message: "Success",
IsLoggedIn: true,
Username: "johndoe",
Name: "John Doe",
Email: utils.CompileUserEmail("johndoe", runtime.CookieDomain),
Provider: "local",
Status: 200,
Message: "Success",
Auth: controller.UCRAuth{
Authenticated: true,
Username: "johndoe",
Name: "John Doe",
Email: utils.CompileUserEmail("johndoe", runtime.CookieDomain),
ProviderID: "local",
},
}
bytes, err := json.Marshal(expectedUserContextResponse)
require.NoError(t, err)
+8 -2
View File
@@ -306,12 +306,18 @@ func (m *ContextMiddleware) tailscaleWhois(ctx context.Context, ip string) (*mod
return nil, nil
}
return &model.TailscaleContext{
uctx := model.TailscaleContext{
BaseContext: model.BaseContext{
Username: whois.NodeName,
Email: whois.LoginName,
Name: whois.DisplayName,
},
UserID: whois.UserID,
}, nil
}
if !strings.ContainsAny(uctx.Email, "@") {
uctx.Email = utils.CompileUserEmail(uctx.Email+"-tailscale", m.runtime.CookieDomain)
}
return &uctx, nil
}
+1
View File
@@ -13,6 +13,7 @@ type RuntimeConfig struct {
OAuthWhitelist []string
ConfiguredProviders []Provider
OIDCClients []OIDCClientConfig
TrustedDomains []string
}
type Provider struct {
+27 -1
View File
@@ -7,6 +7,7 @@ import (
"net"
"strings"
"sync"
"time"
"github.com/tinyauthapp/tinyauth/internal/model"
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
@@ -59,6 +60,15 @@ func NewTailscaleService(log *logger.Logger, config model.Config, ctx context.Co
lc: lc,
}
connectCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
err = service.waitForConn(connectCtx)
if err != nil {
return nil, fmt.Errorf("failed to connect to tailscale network: %w", err)
}
wg.Go(service.watchAndClose)
return service, nil
@@ -89,7 +99,7 @@ func (ts *TailscaleService) Whois(ctx context.Context, addr string) (*model.Tail
UserID: who.UserProfile.ID.String(),
LoginName: who.UserProfile.LoginName,
DisplayName: who.UserProfile.DisplayName,
NodeName: who.Node.Name,
NodeName: strings.TrimSuffix(who.Node.Name, "."),
}
return &res, nil
@@ -117,3 +127,19 @@ func (ts *TailscaleService) GetHostname() string {
return strings.TrimSuffix(status.Self.DNSName, ".")
}
func (ts *TailscaleService) waitForConn(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return fmt.Errorf("timed out waiting for tailscale connection")
default:
ip4, _ := ts.srv.TailscaleIPs()
if !ip4.IsValid() {
time.Sleep(1 * time.Second)
continue
}
return nil
}
}
}