Put locale in compliance portal URLs

Path-segment locales make each language crawlable with self
canonical and hreflang, while identity.locale persists an
explicit choice without client storage or cookie banners.

Signed-off-by: Émile Ré <emile@probo.com>
This commit is contained in:
Émile Ré
2026-07-21 11:02:44 +02:00
parent 2a250ab7d4
commit c223873e96
52 changed files with 1306 additions and 105 deletions

View File

@@ -44,6 +44,7 @@ type (
HashedPassword []byte `db:"hashed_password"`
EmailAddressVerified bool `db:"email_address_verified"`
SAMLSubject *string `db:"saml_subject"`
Locale *string `db:"locale"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
@@ -74,6 +75,7 @@ SELECT
hashed_password,
email_address_verified,
saml_subject,
locale,
created_at,
updated_at
FROM
@@ -118,6 +120,7 @@ SELECT
hashed_password,
email_address_verified,
saml_subject,
locale,
created_at,
updated_at
FROM
@@ -206,7 +209,17 @@ func (i *Identity) Insert(
) error {
q := `
INSERT INTO
identities (id, email_address, full_name, hashed_password, email_address_verified, saml_subject, created_at, updated_at)
identities (
id,
email_address,
full_name,
hashed_password,
email_address_verified,
saml_subject,
locale,
created_at,
updated_at
)
VALUES (
@identity_id,
@email_address,
@@ -214,6 +227,7 @@ VALUES (
@hashed_password,
@email_address_verified,
@saml_subject,
@locale,
@created_at,
@updated_at
)
@@ -225,6 +239,7 @@ VALUES (
"full_name": i.FullName,
"hashed_password": i.HashedPassword,
"saml_subject": i.SAMLSubject,
"locale": i.Locale,
"created_at": i.CreatedAt,
"updated_at": i.UpdatedAt,
"email_address_verified": i.EmailAddressVerified,
@@ -254,6 +269,7 @@ SET
email_address_verified = @email_address_verified,
saml_subject = @saml_subject,
hashed_password = @hashed_password,
locale = @locale,
updated_at = @updated_at
WHERE
id = @identity_id
@@ -265,8 +281,9 @@ WHERE
"full_name": i.FullName,
"email_address_verified": i.EmailAddressVerified,
"saml_subject": i.SAMLSubject,
"updated_at": i.UpdatedAt,
"hashed_password": i.HashedPassword,
"locale": i.Locale,
"updated_at": i.UpdatedAt,
}
result, err := conn.Exec(ctx, q, args)
@@ -295,6 +312,7 @@ SELECT
hashed_password,
email_address_verified,
saml_subject,
locale,
created_at,
updated_at
FROM

View File

@@ -0,0 +1,2 @@
ALTER TABLE identities
ADD COLUMN locale TEXT NULL;

View File

@@ -62,8 +62,18 @@ type (
UpdateIdentityRequest struct {
FullName string `json:"fullName"`
}
UpdateLocaleRequest struct {
Locale string `json:"locale"`
}
)
// Short URL locale tags accepted for Identity.locale (must stay in sync with
// the compliance-portal URL_LOCALES list).
var supportedIdentityLocales = []string{
"en", "fr", "de", "es", "id", "it", "ja", "ko", "pl", "pt", "tr", "uk", "zh",
}
const (
TokenTypeEmailConfirmation = "email_confirmation"
)
@@ -88,6 +98,20 @@ func (req UpdateIdentityRequest) Validate() error {
return v.Error()
}
func (req UpdateLocaleRequest) Validate() error {
v := validator.New()
v.Check(
req.Locale,
"locale",
validator.NotEmpty(),
validator.MaxLen(8),
validator.OneOfSlice(supportedIdentityLocales),
)
return v.Error()
}
func (s AccountService) ChangeEmail(ctx context.Context, identityID gid.GID, req *ChangeEmailRequest) error {
if err := req.Validate(); err != nil {
return fmt.Errorf("invalid request: %w", err)
@@ -402,6 +426,42 @@ func (s AccountService) UpdateIdentity(ctx context.Context, identityID gid.GID,
return identity, nil
}
func (s AccountService) UpdateLocale(ctx context.Context, identityID gid.GID, req *UpdateLocaleRequest) (*coredata.Identity, error) {
if err := req.Validate(); err != nil {
return nil, fmt.Errorf("invalid request: %w", err)
}
identity := &coredata.Identity{}
err := s.pg.WithTx(
ctx,
func(ctx context.Context, tx pg.Tx) error {
err := identity.LoadByID(ctx, tx, identityID)
if err != nil {
if err == coredata.ErrResourceNotFound {
return NewIdentityNotFoundError(identityID)
}
return fmt.Errorf("cannot load identity: %w", err)
}
identity.Locale = &req.Locale
identity.UpdatedAt = time.Now()
if err := identity.Update(ctx, tx); err != nil {
return fmt.Errorf("cannot update identity locale: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return identity, nil
}
func (s AccountService) ListPersonalAPIKeys(
ctx context.Context,
identityID gid.GID,

View File

@@ -97,6 +97,42 @@ func (r *mutationResolver) UpdateFullName(ctx context.Context, input types.Updat
return &types.UpdateFullNamePayload{Success: true}, nil
}
// UpdateLocale is the resolver for the updateLocale field.
func (r *mutationResolver) UpdateLocale(ctx context.Context, input types.UpdateLocaleInput) (*types.UpdateLocalePayload, error) {
identity := authn.IdentityFromContext(ctx)
if identity == nil {
return nil, gqlutils.Unauthenticatedf(ctx, "authentication is required to update locale")
}
identity, err := r.iam.AccountService.UpdateLocale(
ctx,
identity.ID,
&iam.UpdateLocaleRequest{
Locale: input.Locale,
},
)
if err != nil {
if validationErrors, ok := errors.AsType[validator.ValidationErrors](err); ok {
return nil, gqlutils.InvalidValidationErrors(ctx, validationErrors)
}
r.logger.ErrorCtx(ctx, "cannot update identity locale", log.Error(err))
return nil, gqlutils.Internal(ctx)
}
return &types.UpdateLocalePayload{
Identity: &types.Identity{
ID: identity.ID,
Email: identity.EmailAddress,
FullName: identity.FullName,
EmailVerified: identity.EmailAddressVerified,
Locale: identity.Locale,
CreatedAt: identity.CreatedAt,
UpdatedAt: identity.UpdatedAt,
},
}, nil
}
// SignOut is the resolver for the signOut field.
func (r *mutationResolver) SignOut(ctx context.Context) (*types.SignOutPayload, error) {
session := authn.SessionFromContext(ctx)

View File

@@ -35,6 +35,7 @@ func (r *queryResolver) Viewer(ctx context.Context) (*types.Identity, error) {
Email: identity.EmailAddress,
FullName: identity.FullName,
EmailVerified: identity.EmailAddressVerified,
Locale: identity.Locale,
CreatedAt: identity.CreatedAt,
UpdatedAt: identity.UpdatedAt,
}, nil

View File

@@ -1,6 +1,8 @@
extend type Mutation {
updateFullName(input: UpdateFullNameInput!): UpdateFullNamePayload
@authentication(required: PRESENT) @sessionOnly
updateLocale(input: UpdateLocaleInput!): UpdateLocalePayload
@authentication(required: PRESENT) @sessionOnly
signOut: SignOutPayload! @authentication(required: PRESENT) @sessionOnly
}
@@ -12,6 +14,15 @@ type UpdateFullNamePayload {
success: Boolean!
}
input UpdateLocaleInput {
# Short URL locale tag (en, fr, de, …).
locale: String!
}
type UpdateLocalePayload {
identity: Identity!
}
type SignOutPayload {
success: Boolean!
}

View File

@@ -54,6 +54,9 @@ type Identity implements Node {
email: EmailAddr!
fullName: String!
emailVerified: Boolean!
# Preferred UI locale as a short URL tag (en, fr, de, …). Null until the
# viewer explicitly chooses a language in the portal.
locale: String
createdAt: Datetime!
updatedAt: Datetime!
}

View File

@@ -134,16 +134,21 @@ func compliancePageHeadData() HeadDataFunc {
}
compliancePageBaseURL := complianceportal.CompliancePortalBaseURLFromContext(r.Context())
pageBase := ref.UnrefOrZero(compliancePageBaseURL)
htmlLang, canonical, hreflang := SEOFromRequest(r, pageBase)
description := tc.Title + " Compliance Page"
description := tc.Title
if tc.Description != nil && *tc.Description != "" {
description = *tc.Description
}
headData := HeadData{
Title: tc.Title,
Description: description,
OGURL: ref.UnrefOrZero(compliancePageBaseURL),
Title: tc.Title,
Description: description,
OGURL: pageBase,
HtmlLang: htmlLang,
CanonicalURL: canonical,
Hreflang: hreflang,
}
if tc.LogoFileID != nil && compliancePageBaseURL != nil {

View File

@@ -0,0 +1,116 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package complianceportal_v1
import (
"net/http"
"strings"
)
// Short locale tags used in compliance-portal URL paths. Keep in sync with the
// frontend URL_LOCALES list and iam.supportedIdentityLocales.
var compliancePortalLocales = []string{
"en", "fr", "de", "es", "id", "it", "ja", "ko", "pl", "pt", "tr", "uk", "zh",
}
const defaultCompliancePortalLocale = "en"
// SEOFromRequest derives html lang, a self-referencing canonical URL, and
// hreflang alternates (including x-default → English) for the SPA shell.
func SEOFromRequest(r *http.Request, pageBaseURL string) (htmlLang, canonical string, hreflang []HreflangLink) {
appPath := complianceAppPath(r.URL.Path)
locale, rest := splitLocaleFromAppPath(appPath)
htmlLang = locale
canonical = localizedPageURL(pageBaseURL, locale, rest)
hreflang = make([]HreflangLink, 0, len(compliancePortalLocales)+1)
for _, loc := range compliancePortalLocales {
hreflang = append(hreflang, HreflangLink{
Lang: loc,
Href: localizedPageURL(pageBaseURL, loc, rest),
})
}
hreflang = append(hreflang, HreflangLink{
Lang: "x-default",
Href: localizedPageURL(pageBaseURL, defaultCompliancePortalLocale, rest),
})
return htmlLang, canonical, hreflang
}
// complianceAppPath returns the path relative to the portal root: under
// /trust/:slug it strips that prefix; on a custom domain it returns the path as-is.
func complianceAppPath(pathname string) string {
trimmed := strings.TrimPrefix(pathname, "/")
if strings.HasPrefix(trimmed, "trust/") {
parts := strings.SplitN(trimmed, "/", 3)
if len(parts) < 2 {
return "/"
}
if len(parts) == 2 {
return "/"
}
return "/" + parts[2]
}
if pathname == "" {
return "/"
}
return pathname
}
func splitLocaleFromAppPath(appPath string) (locale, rest string) {
segments := strings.Split(strings.Trim(appPath, "/"), "/")
if len(segments) == 0 || segments[0] == "" {
return defaultCompliancePortalLocale, "/"
}
if isCompliancePortalLocale(segments[0]) {
locale = segments[0]
if len(segments) == 1 {
return locale, "/"
}
return locale, "/" + strings.Join(segments[1:], "/")
}
// Unprefixed legacy path — treat content path as-is; default lang for tags.
return defaultCompliancePortalLocale, appPath
}
func isCompliancePortalLocale(value string) bool {
for _, locale := range compliancePortalLocales {
if locale == value {
return true
}
}
return false
}
func localizedPageURL(pageBaseURL, locale, rest string) string {
base := strings.TrimRight(pageBaseURL, "/")
if rest == "/" || rest == "" {
return base + "/" + locale
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
return base + "/" + locale + rest
}

View File

@@ -0,0 +1,55 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package complianceportal_v1_test
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
complianceportal_v1 "go.probo.inc/probo/pkg/server/api/complianceportal/v1"
)
func TestSEOFromRequest(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "https://app.example.com/trust/acme/fr/documents", nil)
require.NoError(t, err)
lang, canonical, hreflang := complianceportal_v1.SEOFromRequest(req, "https://app.example.com/trust/acme")
assert.Equal(t, "fr", lang)
assert.Equal(t, "https://app.example.com/trust/acme/fr/documents", canonical)
require.NotEmpty(t, hreflang)
var xDefault string
var enHref string
for _, link := range hreflang {
if link.Lang == "x-default" {
xDefault = link.Href
}
if link.Lang == "en" {
enHref = link.Href
}
}
assert.Equal(t, "https://app.example.com/trust/acme/en/documents", enHref)
assert.Equal(t, enHref, xDefault)
}

View File

@@ -33,10 +33,18 @@ import (
type (
HeadData struct {
Title string
Description string
OGURL string
FaviconURL string
Title string
Description string
OGURL string
FaviconURL string
HtmlLang string
CanonicalURL string
Hreflang []HreflangLink
}
HreflangLink struct {
Lang string
Href string
}
HeadDataFunc func(r *http.Request) HeadData