package main import ( "context" "database/sql" "embed" "errors" "strconv" "time" "github.com/carlosframework/rastrillo/migrate" "github.com/carlosframework/rastrillo/password" "github.com/carlosframework/rastrillo/sessions" "gorm.io/gorm" "amadan.net/rastrillo/idear" ) // Models is every model THIS APP's schema generator manages. // // idear's models are deliberately NOT in it, and NOTHING STOPS YOU // PUTTING THEM THERE: idear exports the types (idear.Member, // idear.Invitation — this app's own templates use them) but not the // list, so `[]any{&User{}, &Post{}, &idear.Member{}}` compiles fine. // // It is wrong because `rastrillo migration generate` and `rastrillo // migration check` replay this app's Schema into a scratch database // and diff the result against this list, as a MATCHED PAIR. idear's // tables are created by idear's OWN migrations, which reach the // database through BootSchema below and never through Schema, so a // list naming &idear.Member{} is diffed against a schema that has no // idear migrations in it: `check` goes permanently red, and `generate` // writes a second, GORM-flavoured CREATE TABLE idear_members into this // app's migration file that collides at boot with idear's own. // // TestSchemaAndModelsAgree is `migration check` in test form, and it // is the only thing that catches this — the compiler will not. var Models = []any{&User{}, &Post{}} // User is the app's own identity row: an address and a password hash, // and nothing about membership. // // That split is the whole point of idear. idear owns who is IN this // instance and at what rank; the app owns credentials. The join // between them is the session Subject — see subjectFor. type User struct { ID int64 Email string `gorm:"uniqueIndex"` PasswordHash string CreatedAt time.Time } // Post is the app's domain: one message on a shared board. // // Author is a display cache — the address as it was when the post was // written — for the same reason idear.Member.Email is one: the roster // row it names can be deactivated, renamed, or transferred, and a post // from two years ago should still say who wrote it. AuthorID is the // idear member id, and it is why removal in idear is a deactivation // and never a delete: a deleted row would dangle every one of these. type Post struct { ID int64 AuthorID int64 `gorm:"index"` Author string Body string CreatedAt time.Time } //go:embed migrations/*.sql var migrationFS embed.FS // Schema is THIS APP's own migrations and nothing else — the half // `migration generate` writes into and `migration check` diffs against // Models. var Schema = migrate.MustFromFS(migrationFS, "board") // BootSchema is everything applied at boot, in apply order: the shared // session core, then idear, then this app. // // idear.Schema is merged HERE and never into Schema. See Models for // what merging it into the wrong one costs. var BootSchema = migrate.Merge(sessions.Schema, idear.Schema, Schema) // subjectFor is the session Subject a User row has under the password // identity plugin. // // password mints its session as // sessions.Session{Subject: strconv.FormatInt(id, 10)} — one place, // signInAndRedirect, which both Signin and Signup pass through — so // this is the spelling a Member row must carry to be resolvable by any // session this app ever mints. Get it wrong and the person signs in // successfully and then 404s on every guarded route forever, because // idear's Require looks the Subject up and finds nothing. // // idear writes this spelling itself on the admission path (Admitting), // which is why nothing outside seeding needs this function. It is // unexported by idear, so a seed that writes roster rows behind the // HTTP flows has to restate it — noted in the friction log. func subjectFor(id int64) string { return strconv.FormatInt(id, 10) } // lookupUser is password.Config.Lookup. It knows nothing about // membership: a deactivated member still has a User row and still // verifies their password. What refuses them is idear's Require on // every route — which is why this app has no ungated landing page. func lookupUser(g *gorm.DB) func(context.Context, string) (int64, string, error) { return func(ctx context.Context, email string) (int64, string, error) { var u User err := g.WithContext(ctx).Where("email = ?", email).First(&u).Error if errors.Is(err, gorm.ErrRecordNotFound) { return 0, "", sql.ErrNoRows } if err != nil { return 0, "", err } return u.ID, u.PasswordHash, nil } } // emailForSubject is idear.Config.EmailForSubject: it answers "which // address is this session subject?" out of THIS APP's user table. // // It is one lookup, and it is what makes reconciliation apply the same // rule admission does. Without it, POST /invitations/{token} under the // password plugin has no address to match the invitation against, so // possession of the token is the whole credential and any signed-in // orphan may spend a token issued to somebody else — at whatever role // that token carries. idear cannot resolve a decimal user id itself; // only this table can. // // The two "not this app's" answers are ("", nil), not an error: a // subject that is not a decimal id, and a decimal id with no row // behind it. idear refuses the redemption for both. An error is // reserved for a database that failed, which idear answers 500 rather // than rendering as a policy refusal. func emailForSubject(g *gorm.DB) func(context.Context, string) (string, error) { return func(ctx context.Context, subject string) (string, error) { id, err := strconv.ParseInt(subject, 10, 64) if err != nil { return "", nil } var u User switch err := g.WithContext(ctx).Where("id = ?", id).Take(&u).Error; { case errors.Is(err, gorm.ErrRecordNotFound): return "", nil case err != nil: return "", err } return u.Email, nil } } // createUser is the app's half of password.Config.Create: it writes a // User row and nothing else. // // It is never wired to password directly. App() wraps it as // idear.Roster.Admitting(createUser(g)), which decides the ROLE first — // claim, invitation, open sign-up, or refusal — and writes the Member // row after this returns. See App. func createUser(g *gorm.DB) func(context.Context, string, string) (int64, error) { return func(ctx context.Context, email, hash string) (int64, error) { u := User{Email: email, PasswordHash: hash} if err := g.WithContext(ctx).Create(&u).Error; err != nil { return 0, err } return u.ID, nil } } // The seeded accounts. Three, at three different roles, because a role // gate you cannot click on is a role gate nobody checks: signing in as // SeedAdmin and as SeedMember shows two visibly different members // pages, and SeedAdmin cannot promote anybody to Admin while SeedOwner // can. const ( SeedOwner = "ada@example.test" SeedAdmin = "kim@example.test" SeedMember = "sam@example.test" SeedPassword = "demo-password" ) // Seed writes those three accounts, and is idempotent: it does nothing // at all unless the roster is empty. // // It goes through the REAL flows rather than inserting roster rows — // Claim for the Owner, then Invite and Accept for the other two — // because those are the only paths that exist. The store will not mint // a second Owner, and it will not mint an Admin without an invitation // to spend; a seed that wrote the rows directly would be demonstrating // a way in that no running app has. func Seed(ctx context.Context, g *gorm.DB, rs *idear.Roster) error { empty, err := rs.IsEmpty(ctx) if err != nil { return err } if !empty { return nil } ownerID, err := seedUser(ctx, g, SeedOwner) if err != nil { return err } owner, err := rs.Claim(ctx, subjectFor(ownerID), SeedOwner, "Ada") if err != nil { return err } for _, want := range []struct { email string name string role idear.Role }{ {SeedAdmin, "Kim", idear.RoleAdmin}, {SeedMember, "Sam", idear.RoleMember}, } { _, token, err := rs.Invite(ctx, owner, want.email, want.role) if err != nil { return err } id, err := seedUser(ctx, g, want.email) if err != nil { return err } if _, err := rs.Accept(ctx, token, subjectFor(id), want.name); err != nil { return err } } return g.WithContext(ctx).Create(&Post{ AuthorID: owner.ID, Author: owner.Email, Body: "Welcome to the board. Everyone here can post; admins can delete.", }).Error } func seedUser(ctx context.Context, g *gorm.DB, email string) (int64, error) { hash, err := password.Hash(SeedPassword) if err != nil { return 0, err } return createUser(g)(ctx, email, hash) }