feat: rebuild auth identity foundation flow

This commit is contained in:
IanShaw027
2026-04-20 17:39:57 +08:00
parent fbd0a2e3c4
commit e9de839d87
123 changed files with 33599 additions and 772 deletions

View File

@@ -0,0 +1,93 @@
package schema
import (
"fmt"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
var authProviderTypes = map[string]struct{}{
"email": {},
"linuxdo": {},
"oidc": {},
"wechat": {},
}
func validateAuthProviderType(value string) error {
if _, ok := authProviderTypes[value]; ok {
return nil
}
return fmt.Errorf("invalid auth provider type %q", value)
}
// AuthIdentity stores the canonical login identity for an account.
type AuthIdentity struct {
ent.Schema
}
func (AuthIdentity) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "auth_identities"},
}
}
func (AuthIdentity) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
func (AuthIdentity) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id"),
field.String("provider_type").
MaxLen(20).
NotEmpty().
Validate(validateAuthProviderType),
field.String("provider_key").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("provider_subject").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Time("verified_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.String("issuer").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.JSON("metadata", map[string]any{}).
Default(func() map[string]any { return map[string]any{} }).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
}
}
func (AuthIdentity) Edges() []ent.Edge {
return []ent.Edge{
edge.From("user", User.Type).
Ref("auth_identities").
Field("user_id").
Required().
Unique(),
edge.To("channels", AuthIdentityChannel.Type),
edge.To("adoption_decisions", IdentityAdoptionDecision.Type),
}
}
func (AuthIdentity) Indexes() []ent.Index {
return []ent.Index{
index.Fields("provider_type", "provider_key", "provider_subject").Unique(),
index.Fields("user_id"),
index.Fields("user_id", "provider_type"),
}
}

View File

@@ -0,0 +1,72 @@
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// AuthIdentityChannel stores channel-scoped identifiers for a canonical identity.
type AuthIdentityChannel struct {
ent.Schema
}
func (AuthIdentityChannel) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "auth_identity_channels"},
}
}
func (AuthIdentityChannel) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
func (AuthIdentityChannel) Fields() []ent.Field {
return []ent.Field{
field.Int64("identity_id"),
field.String("provider_type").
MaxLen(20).
NotEmpty().
Validate(validateAuthProviderType),
field.String("provider_key").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("channel").
MaxLen(20).
NotEmpty(),
field.String("channel_app_id").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("channel_subject").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.JSON("metadata", map[string]any{}).
Default(func() map[string]any { return map[string]any{} }).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
}
}
func (AuthIdentityChannel) Edges() []ent.Edge {
return []ent.Edge{
edge.From("identity", AuthIdentity.Type).
Ref("channels").
Field("identity_id").
Required().
Unique(),
}
}
func (AuthIdentityChannel) Indexes() []ent.Index {
return []ent.Index{
index.Fields("provider_type", "provider_key", "channel", "channel_app_id", "channel_subject").Unique(),
index.Fields("identity_id"),
}
}

View File

@@ -0,0 +1,124 @@
package schema
import (
"testing"
"entgo.io/ent/entc/load"
"github.com/stretchr/testify/require"
)
func TestAuthIdentityFoundationSchemas(t *testing.T) {
spec, err := (&load.Config{Path: "."}).Load()
require.NoError(t, err)
schemas := map[string]*load.Schema{}
for _, schema := range spec.Schemas {
schemas[schema.Name] = schema
}
authIdentity := requireSchema(t, schemas, "AuthIdentity")
requireSchemaFields(t, authIdentity,
"user_id",
"provider_type",
"provider_key",
"provider_subject",
"verified_at",
"issuer",
"metadata",
)
requireHasUniqueIndex(t, authIdentity, "provider_type", "provider_key", "provider_subject")
authIdentityChannel := requireSchema(t, schemas, "AuthIdentityChannel")
requireSchemaFields(t, authIdentityChannel,
"identity_id",
"provider_type",
"provider_key",
"channel",
"channel_app_id",
"channel_subject",
"metadata",
)
requireHasUniqueIndex(t, authIdentityChannel, "provider_type", "provider_key", "channel", "channel_app_id", "channel_subject")
pendingAuthSession := requireSchema(t, schemas, "PendingAuthSession")
requireSchemaFields(t, pendingAuthSession,
"intent",
"provider_type",
"provider_key",
"provider_subject",
"target_user_id",
"redirect_to",
"resolved_email",
"registration_password_hash",
"upstream_identity_claims",
"local_flow_state",
"browser_session_key",
"completion_code_hash",
"completion_code_expires_at",
"email_verified_at",
"password_verified_at",
"totp_verified_at",
"expires_at",
"consumed_at",
)
adoptionDecision := requireSchema(t, schemas, "IdentityAdoptionDecision")
requireSchemaFields(t, adoptionDecision,
"pending_auth_session_id",
"identity_id",
"adopt_display_name",
"adopt_avatar",
"decided_at",
)
requireHasUniqueIndex(t, adoptionDecision, "pending_auth_session_id")
userSchema := requireSchema(t, schemas, "User")
requireSchemaFields(t, userSchema, "signup_source", "last_login_at", "last_active_at")
}
func requireSchema(t *testing.T, schemas map[string]*load.Schema, name string) *load.Schema {
t.Helper()
schema, ok := schemas[name]
require.True(t, ok, "schema %s should exist", name)
return schema
}
func requireSchemaFields(t *testing.T, schema *load.Schema, names ...string) {
t.Helper()
fields := map[string]struct{}{}
for _, field := range schema.Fields {
fields[field.Name] = struct{}{}
}
for _, name := range names {
_, ok := fields[name]
require.True(t, ok, "schema %s should include field %s", schema.Name, name)
}
}
func requireHasUniqueIndex(t *testing.T, schema *load.Schema, fields ...string) {
t.Helper()
for _, index := range schema.Indexes {
if !index.Unique {
continue
}
if len(index.Fields) != len(fields) {
continue
}
match := true
for i := range fields {
if index.Fields[i] != fields[i] {
match = false
break
}
}
if match {
return
}
}
require.Failf(t, "missing unique index", "schema %s should include unique index on %v", schema.Name, fields)
}

View File

@@ -0,0 +1,70 @@
package schema
import (
"time"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// IdentityAdoptionDecision stores the one-time profile adoption choice captured during a pending auth flow.
type IdentityAdoptionDecision struct {
ent.Schema
}
func (IdentityAdoptionDecision) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "identity_adoption_decisions"},
}
}
func (IdentityAdoptionDecision) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
func (IdentityAdoptionDecision) Fields() []ent.Field {
return []ent.Field{
field.Int64("pending_auth_session_id"),
field.Int64("identity_id").
Optional().
Nillable(),
field.Bool("adopt_display_name").
Default(false),
field.Bool("adopt_avatar").
Default(false),
field.Time("decided_at").
Immutable().
Default(time.Now).
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
}
}
func (IdentityAdoptionDecision) Edges() []ent.Edge {
return []ent.Edge{
edge.From("pending_auth_session", PendingAuthSession.Type).
Ref("adoption_decision").
Field("pending_auth_session_id").
Required().
Unique(),
edge.From("identity", AuthIdentity.Type).
Ref("adoption_decisions").
Field("identity_id").
Unique(),
}
}
func (IdentityAdoptionDecision) Indexes() []ent.Index {
return []ent.Index{
index.Fields("pending_auth_session_id").Unique(),
index.Fields("identity_id"),
}
}

View File

@@ -0,0 +1,134 @@
package schema
import (
"fmt"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
var pendingAuthIntents = map[string]struct{}{
"login": {},
"bind_current_user": {},
"adopt_existing_user_by_email": {},
}
func validatePendingAuthIntent(value string) error {
if _, ok := pendingAuthIntents[value]; ok {
return nil
}
return fmt.Errorf("invalid pending auth intent %q", value)
}
// PendingAuthSession stores a short-lived post-auth decision session.
type PendingAuthSession struct {
ent.Schema
}
func (PendingAuthSession) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "pending_auth_sessions"},
}
}
func (PendingAuthSession) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
}
}
func (PendingAuthSession) Fields() []ent.Field {
return []ent.Field{
field.String("session_token").
MaxLen(255).
NotEmpty(),
field.String("intent").
MaxLen(40).
NotEmpty().
Validate(validatePendingAuthIntent),
field.String("provider_type").
MaxLen(20).
NotEmpty().
Validate(validateAuthProviderType),
field.String("provider_key").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("provider_subject").
NotEmpty().
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Int64("target_user_id").
Optional().
Nillable(),
field.String("redirect_to").
Default("").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("resolved_email").
Default("").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("registration_password_hash").
Default("").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.JSON("upstream_identity_claims", map[string]any{}).
Default(func() map[string]any { return map[string]any{} }).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
field.JSON("local_flow_state", map[string]any{}).
Default(func() map[string]any { return map[string]any{} }).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
field.String("browser_session_key").
Default("").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.String("completion_code_hash").
Default("").
SchemaType(map[string]string{dialect.Postgres: "text"}),
field.Time("completion_code_expires_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("email_verified_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("password_verified_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("totp_verified_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("expires_at").
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("consumed_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
}
}
func (PendingAuthSession) Edges() []ent.Edge {
return []ent.Edge{
edge.From("target_user", User.Type).
Ref("pending_auth_sessions").
Field("target_user_id").
Unique(),
edge.To("adoption_decision", IdentityAdoptionDecision.Type).
Unique(),
}
}
func (PendingAuthSession) Indexes() []ent.Index {
return []ent.Index{
index.Fields("session_token").Unique(),
index.Fields("target_user_id"),
index.Fields("expires_at"),
index.Fields("provider_type", "provider_key", "provider_subject"),
index.Fields("completion_code_hash"),
}
}

View File

@@ -72,6 +72,17 @@ func (User) Fields() []ent.Field {
field.Time("totp_enabled_at").
Optional().
Nillable(),
field.String("signup_source").
MaxLen(20).
Default("email"),
field.Time("last_login_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
field.Time("last_active_at").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
// 余额不足通知
field.Bool("balance_notify_enabled").
@@ -104,6 +115,8 @@ func (User) Edges() []ent.Edge {
edge.To("attribute_values", UserAttributeValue.Type),
edge.To("promo_code_usages", PromoCodeUsage.Type),
edge.To("payment_orders", PaymentOrder.Type),
edge.To("auth_identities", AuthIdentity.Type),
edge.To("pending_auth_sessions", PendingAuthSession.Type),
}
}