// Copyright (c) 2025-2026 Probo Inc . // // 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 coredata import ( "context" "errors" "fmt" "strings" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "go.gearno.de/kit/pg" "go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/iam/policy" "go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/page" ) type ( Identity struct { ID gid.GID `db:"id"` EmailAddress mail.Addr `db:"email_address"` FullName string `db:"full_name"` 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"` } Identities []*Identity ) var ( ErrSAMLSubjectAlreadyExists = errors.New("saml subject already exists") ) func (i Identity) CursorKey(orderBy IdentityOrderField) page.CursorKey { switch orderBy { case IdentityOrderFieldCreatedAt: return page.NewCursorKey(i.ID, i.CreatedAt) } panic(fmt.Sprintf("unsupported order by: %s", orderBy)) } // Tenant id scope is not applied because we want to access identities across all tenants for authentication purposes. func (i *Identity) LoadByEmail( ctx context.Context, conn pg.Querier, email mail.Addr, ) error { q := ` SELECT id, email_address, full_name, hashed_password, email_address_verified, saml_subject, locale, created_at, updated_at FROM identities WHERE email_address = @identity_email LIMIT 1; ` args := pgx.StrictNamedArgs{"identity_email": email} rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query identity: %w", err) } identity, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Identity]) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return ErrResourceNotFound } return fmt.Errorf("cannot collect identity: %w", err) } *i = identity return nil } // Tenant id scope is not applied because we want to access identities across all tenants for authentication purposes. func (i *Identity) LoadByID( ctx context.Context, conn pg.Querier, identityID gid.GID, ) error { q := ` SELECT id, email_address, full_name, hashed_password, email_address_verified, saml_subject, locale, created_at, updated_at FROM identities WHERE id = @identity_id LIMIT 1; ` args := pgx.StrictNamedArgs{"identity_id": identityID} rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query identity: %w", err) } identity, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Identity]) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return ErrResourceNotFound } return fmt.Errorf("cannot collect identity: %w", err) } *i = identity return nil } // AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation. // It is intentionally lightweight and does not populate the Identity struct. func (i *Identity) AuthorizationAttributes( ctx context.Context, conn pg.Querier, resourceIDs []gid.GID, ) (policy.AttributesByID, error) { q := ` SELECT id, email_address FROM identities WHERE id = ANY(@resource_ids::text[]) ` args := pgx.StrictNamedArgs{ "resource_ids": resourceIDs, } rows, err := conn.Query(ctx, q, args) if err != nil { return nil, fmt.Errorf("cannot query identity authorization attributes: %w", err) } defer rows.Close() attrsByID := make(policy.AttributesByID, len(resourceIDs)) for rows.Next() { var ( id gid.GID emailAddress string ) if err := rows.Scan(&id, &emailAddress); err != nil { return nil, fmt.Errorf("cannot scan identity authorization attributes: %w", err) } attrsByID[id] = policy.Attributes{ "identity_id": id.String(), "email": emailAddress, } } if err := rows.Err(); err != nil { return nil, fmt.Errorf("cannot iterate identity authorization attributes: %w", err) } return attrsByID, nil } func (i *Identity) Insert( ctx context.Context, conn pg.Tx, ) error { q := ` INSERT INTO identities ( id, email_address, full_name, hashed_password, email_address_verified, saml_subject, locale, created_at, updated_at ) VALUES ( @identity_id, @email_address, @full_name, @hashed_password, @email_address_verified, @saml_subject, @locale, @created_at, @updated_at ) ` args := pgx.StrictNamedArgs{ "identity_id": i.ID, "email_address": i.EmailAddress, "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, } _, err := conn.Exec(ctx, q, args) if err != nil { if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == "23505" { switch pgErr.ConstraintName { case "idx_users_saml_subject": return ErrSAMLSubjectAlreadyExists case "usrmgr_users_email_address_key": return ErrResourceAlreadyExists } } return err } return nil } func (i *Identity) Update(ctx context.Context, conn pg.Tx) error { q := ` UPDATE identities SET email_address = @email_address, full_name = @full_name, email_address_verified = @email_address_verified, saml_subject = @saml_subject, hashed_password = @hashed_password, locale = @locale, updated_at = @updated_at WHERE id = @identity_id ` args := pgx.StrictNamedArgs{ "identity_id": i.ID, "email_address": i.EmailAddress, "full_name": i.FullName, "email_address_verified": i.EmailAddressVerified, "saml_subject": i.SAMLSubject, "hashed_password": i.HashedPassword, "locale": i.Locale, "updated_at": i.UpdatedAt, } result, err := conn.Exec(ctx, q, args) if err != nil { if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == "23505" { switch pgErr.ConstraintName { case "idx_users_saml_subject": return ErrSAMLSubjectAlreadyExists case "usrmgr_users_email_address_key": return ErrResourceAlreadyExists } } return fmt.Errorf("cannot update identity: %w", err) } if result.RowsAffected() == 0 { return ErrResourceNotFound } return nil } // LoadBySAMLSubject loads an identity by their SAML subject (NameID) func (i *Identity) LoadBySAMLSubject( ctx context.Context, conn pg.Querier, samlSubject string, ) error { if strings.TrimSpace(samlSubject) == "" { return ErrResourceNotFound } q := ` SELECT id, email_address, full_name, hashed_password, email_address_verified, saml_subject, locale, created_at, updated_at FROM identities WHERE saml_subject = @saml_subject LIMIT 1; ` args := pgx.StrictNamedArgs{"saml_subject": samlSubject} rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query identity by SAML subject: %w", err) } identity, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Identity]) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return ErrResourceNotFound } return fmt.Errorf("cannot collect identity: %w", err) } *i = identity return nil } func (i *Identity) CountMemberships( ctx context.Context, conn pg.Querier, ) (int, error) { q := ` SELECT COUNT(*) FROM iam_memberships WHERE identity_id = @identity_id ` args := pgx.StrictNamedArgs{"identity_id": i.ID} var count int err := conn.QueryRow(ctx, q, args).Scan(&count) if err != nil { return 0, fmt.Errorf("cannot count identity memberships: %w", err) } return count, nil } func (i *Identities) LoadByIDs( ctx context.Context, conn pg.Querier, identityIDs []gid.GID, ) error { q := ` SELECT id, email_address, full_name, hashed_password, email_address_verified, saml_subject, locale, created_at, updated_at FROM identities WHERE id = ANY(@identity_ids) ` args := pgx.StrictNamedArgs{"identity_ids": identityIDs} rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query identities: %w", err) } identities, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Identity]) if err != nil { return fmt.Errorf("cannot collect identities: %w", err) } *i = identities return nil }