use crate::{edit::EditPlan, names::GeneratedNames, FrontendDriver, Generator, ProjectConfig};
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
pub fn make_auth(root: &Path) -> Result<Vec<PathBuf>> {
make_auth_with_frontend(root, false)
}
pub fn make_auth_with_frontend(root: &Path, frontend: bool) -> Result<Vec<PathBuf>> {
let mut plan = EditPlan::new(root)?;
let react = ProjectConfig::load(root)?.frontend.driver == FrontendDriver::React;
if frontend && !react {
bail!("--frontend requires a Capy React application. No files changed.");
}
let existing = plan.exists("app/auth.rs");
if existing && !frontend {
bail!("app/auth.rs already exists. Capy never overwrites application files.");
}
if existing && frontend {
let manifest = plan.read("Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
let auth = manifest
.get("dependencies")
.and_then(|v| v.get("capy"))
.and_then(|v| v.get("features"))
.and_then(toml_edit::Item::as_array)
.is_some_and(|features| features.iter().any(|f| f.as_str() == Some("auth")));
let helper = plan.read("frontend/src/lib/api.ts")?;
if !auth || !helper.contains("apiResponses") || !plan.exists("frontend/src/lib/auth.ts") {
bail!("The existing backend needs the capy auth feature and 0.9 endpoint-typed auth helper before adding frontend pages. Follow docs/upgrading-0.9.md; no files changed.");
}
}
if !existing {
plan.create(
"app/auth.rs",
include_str!("../templates/auth/auth.rs.txt").into(),
)?;
plan.create(
"app/models/user.rs",
include_str!("../templates/auth/user.rs.txt").into(),
)?;
plan.create(
"config/auth.toml",
include_str!("../templates/auth/config.toml.txt").into(),
)?;
register(
&mut plan,
"app/mod.rs",
"auth",
"",
Generator::Controller,
"Auth",
)?;
register(
&mut plan,
"app/models/mod.rs",
"user",
"pub use user::Entity as User;\npub use user::Model as UserModel;",
Generator::Model,
"User",
)?;
plan.create(
"database/migrations/m_identity.rs",
include_str!("../templates/auth/migration.rs.txt").into(),
)?;
migration(&mut plan, "m_identity")?;
let factory = crate::project::application_file(root);
let source = plan.read(factory)?;
plan.replace(
factory,
crate::project::wire_application(&source, ".auth(application::app::auth::delivery())")?,
)?;
let mut manifest = plan.read("Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
let dependency = manifest["dependencies"]["capy"]
.as_table_like_mut()
.context("Use a table-style capy-framework dependency before installing auth.")?;
let mut features = dependency
.get("features")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
if !features.iter().any(|v| v.as_str() == Some("auth")) {
features.push("auth");
}
dependency.insert("features", toml_edit::value(features));
plan.replace("Cargo.toml", manifest.to_string())?;
let ignore = plan.read(".gitignore")?;
plan.replace(".gitignore", format!("{ignore}\n/.capy-reset-outbox/\n"))?;
plan.create(
"database/seeds/identity.rs",
include_str!("../templates/auth/seed.rs.txt").into(),
)?;
plan.anchor("database/seeds.rs", "// capy:seed-modules", "mod identity;")?;
plan.anchor(
"database/seeds.rs",
"// capy:seeds",
"identity::run(&ctx).await?;",
)?;
if react {
let helper = plan.read("frontend/src/lib/api.ts")?;
if helper == include_str!("../templates/auth/legacy-api.ts.txt") {
plan.replace(
"frontend/src/lib/api.ts",
include_str!("../templates/frontend/src/lib/api.ts.txt").into(),
)?;
} else if !helper.contains("export function setCsrfTokenProvider(")
|| !helper.contains("apiResponses")
{
bail!("The customized frontend API helper needs the 0.9 endpoint-typed client and setCsrfTokenProvider. Follow docs/upgrading-0.9.md; no files changed.");
}
plan.create(
"frontend/src/lib/auth.ts",
include_str!("../templates/auth/auth.ts.txt").into(),
)?;
let main = plan.read("frontend/src/main.tsx")?;
plan.replace(
"frontend/src/main.tsx",
format!("import './lib/auth'\n{main}"),
)?;
}
}
if frontend {
install_frontend(&mut plan)?;
}
plan.commit()
}
fn register(
plan: &mut EditPlan<'_>,
path: &str,
module: &str,
exports: &str,
kind: Generator,
name: &str,
) -> Result<()> {
let source = plan.read(path)?;
GeneratedNames::new(name)?.check_registry(&source, module, kind)?;
plan.replace(path, format!("{source}\npub mod {module};\n{exports}\n"))
}
fn migration(plan: &mut EditPlan<'_>, module: &str) -> Result<()> {
GeneratedNames::new(module)?.check_registry(
&plan.read("database/migrations/mod.rs")?,
module,
Generator::Migration,
)?;
plan.anchor(
"database/migrations/mod.rs",
"// capy:modules",
&format!("mod {module};"),
)?;
plan.anchor(
"database/migrations/mod.rs",
"// capy:migrations",
&format!("Box::new({module}::Migration),"),
)
}
fn install_frontend(plan: &mut EditPlan<'_>) -> Result<()> {
let source = plan.read("app/auth.rs")?;
GeneratedNames::new("VerificationDelivery")?.check_registry(
&source,
"verification_delivery",
Generator::Controller,
)?;
plan.replace("app/auth.rs", format!("{source}\n/// Private development verification inbox; replace before production.\npub fn verification_delivery() -> impl capy::auth::VerificationDelivery {{ capy::auth::LocalVerificationDelivery::new(\".capy-verification-outbox\") }}\n"))?;
plan.create(
"database/migrations/m_email_verification.rs",
include_str!("../templates/auth/verification-migration.rs.txt").into(),
)?;
migration(plan, "m_email_verification")?;
let factory = if plan.exists("src/bootstrap.rs") {
"src/bootstrap.rs"
} else {
"src/main.rs"
};
let source = plan.read(factory)?;
plan.replace(
factory,
crate::project::wire_application(
&source,
".email_verification(application::app::auth::verification_delivery())",
)?,
)?;
let ignore = plan.read(".gitignore")?;
plan.replace(
".gitignore",
format!("{ignore}\n/.capy-verification-outbox/\n"),
)?;
for (path, source) in [
(
"AuthProvider.tsx",
include_str!("../templates/auth/frontend/AuthProvider.tsx.txt"),
),
(
"index.tsx",
include_str!("../templates/auth/frontend/index.tsx.txt"),
),
(
"verification.ts",
include_str!("../templates/auth/frontend/verification.ts.txt"),
),
(
"useProof.ts",
include_str!("../templates/auth/frontend/useProof.ts.txt"),
),
(
"pages/Login.tsx",
include_str!("../templates/auth/frontend/Login.tsx.txt"),
),
(
"pages/Register.tsx",
include_str!("../templates/auth/frontend/Register.tsx.txt"),
),
(
"pages/ForgotPassword.tsx",
include_str!("../templates/auth/frontend/ForgotPassword.tsx.txt"),
),
(
"pages/ResetPassword.tsx",
include_str!("../templates/auth/frontend/ResetPassword.tsx.txt"),
),
(
"pages/VerifyEmail.tsx",
include_str!("../templates/auth/frontend/VerifyEmail.tsx.txt"),
),
(
"pages/Account.tsx",
include_str!("../templates/auth/frontend/Account.tsx.txt"),
),
] {
plan.create(&format!("frontend/src/features/auth/{path}"), source.into())?;
}
plan.anchor(
"frontend/src/features/index.ts",
"// capy:feature-imports",
"import { authRoutes } from './auth'",
)?;
plan.anchor(
"frontend/src/features/index.ts",
"// capy:feature-routes",
"...authRoutes,",
)?;
plan.anchor(
"frontend/src/lib/providers.tsx",
"// capy:provider-imports",
"import { AuthProvider } from '../features/auth/AuthProvider'",
)?;
plan.anchor(
"frontend/src/lib/providers.tsx",
"// capy:providers",
"AuthProvider,",
)?;
Ok(())
}