1use crate::{edit::EditPlan, names::GeneratedNames, FrontendDriver, Generator, ProjectConfig};
2use anyhow::{bail, Context, Result};
3use std::path::{Path, PathBuf};
4
5pub fn make_auth(root: &Path) -> Result<Vec<PathBuf>> {
7 make_auth_with_frontend(root, false)
8}
9
10pub fn make_auth_with_frontend(root: &Path, frontend: bool) -> Result<Vec<PathBuf>> {
13 let mut plan = EditPlan::new(root)?;
14 let react = ProjectConfig::load(root)?.frontend.driver == FrontendDriver::React;
15 if frontend && !react {
16 bail!("--frontend requires a Capy React application. No files changed.");
17 }
18 let existing = plan.exists("app/auth.rs");
19 if existing && !frontend {
20 bail!("app/auth.rs already exists. Capy never overwrites application files.");
21 }
22 if existing && frontend {
23 let manifest = plan.read("Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
24 let auth = manifest
25 .get("dependencies")
26 .and_then(|v| v.get("capy"))
27 .and_then(|v| v.get("features"))
28 .and_then(toml_edit::Item::as_array)
29 .is_some_and(|features| features.iter().any(|f| f.as_str() == Some("auth")));
30 let helper = plan.read("frontend/src/lib/api.ts")?;
31 if !auth || !helper.contains("apiResponses") || !plan.exists("frontend/src/lib/auth.ts") {
32 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.");
33 }
34 }
35 if !existing {
36 plan.create(
37 "app/auth.rs",
38 include_str!("../templates/auth/auth.rs.txt").into(),
39 )?;
40 plan.create(
41 "app/models/user.rs",
42 include_str!("../templates/auth/user.rs.txt").into(),
43 )?;
44 plan.create(
45 "config/auth.toml",
46 include_str!("../templates/auth/config.toml.txt").into(),
47 )?;
48 register(
49 &mut plan,
50 "app/mod.rs",
51 "auth",
52 "",
53 Generator::Controller,
54 "Auth",
55 )?;
56 register(
57 &mut plan,
58 "app/models/mod.rs",
59 "user",
60 "pub use user::Entity as User;\npub use user::Model as UserModel;",
61 Generator::Model,
62 "User",
63 )?;
64 plan.create(
65 "database/migrations/m_identity.rs",
66 include_str!("../templates/auth/migration.rs.txt").into(),
67 )?;
68 migration(&mut plan, "m_identity")?;
69 let factory = crate::project::application_file(root);
70 let source = plan.read(factory)?;
71 plan.replace(
72 factory,
73 crate::project::wire_application(&source, ".auth(application::app::auth::delivery())")?,
74 )?;
75 let mut manifest = plan.read("Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
76 let dependency = manifest["dependencies"]["capy"]
77 .as_table_like_mut()
78 .context("Use a table-style capy-framework dependency before installing auth.")?;
79 let mut features = dependency
80 .get("features")
81 .and_then(|v| v.as_array())
82 .cloned()
83 .unwrap_or_default();
84 if !features.iter().any(|v| v.as_str() == Some("auth")) {
85 features.push("auth");
86 }
87 dependency.insert("features", toml_edit::value(features));
88 plan.replace("Cargo.toml", manifest.to_string())?;
89 let ignore = plan.read(".gitignore")?;
90 plan.replace(".gitignore", format!("{ignore}\n/.capy-reset-outbox/\n"))?;
91 plan.create(
92 "database/seeds/identity.rs",
93 include_str!("../templates/auth/seed.rs.txt").into(),
94 )?;
95 plan.anchor("database/seeds.rs", "// capy:seed-modules", "mod identity;")?;
96 plan.anchor(
97 "database/seeds.rs",
98 "// capy:seeds",
99 "identity::run(&ctx).await?;",
100 )?;
101 if react {
102 let helper = plan.read("frontend/src/lib/api.ts")?;
103 if helper == include_str!("../templates/auth/legacy-api.ts.txt") {
104 plan.replace(
105 "frontend/src/lib/api.ts",
106 include_str!("../templates/frontend/src/lib/api.ts.txt").into(),
107 )?;
108 } else if !helper.contains("export function setCsrfTokenProvider(")
109 || !helper.contains("apiResponses")
110 {
111 bail!("The customized frontend API helper needs the 0.9 endpoint-typed client and setCsrfTokenProvider. Follow docs/upgrading-0.9.md; no files changed.");
112 }
113 plan.create(
114 "frontend/src/lib/auth.ts",
115 include_str!("../templates/auth/auth.ts.txt").into(),
116 )?;
117 let main = plan.read("frontend/src/main.tsx")?;
118 plan.replace(
119 "frontend/src/main.tsx",
120 format!("import './lib/auth'\n{main}"),
121 )?;
122 }
123 }
124 if frontend {
125 install_frontend(&mut plan)?;
126 }
127 plan.commit()
128}
129
130fn register(
131 plan: &mut EditPlan<'_>,
132 path: &str,
133 module: &str,
134 exports: &str,
135 kind: Generator,
136 name: &str,
137) -> Result<()> {
138 let source = plan.read(path)?;
139 GeneratedNames::new(name)?.check_registry(&source, module, kind)?;
140 plan.replace(path, format!("{source}\npub mod {module};\n{exports}\n"))
141}
142fn migration(plan: &mut EditPlan<'_>, module: &str) -> Result<()> {
143 GeneratedNames::new(module)?.check_registry(
144 &plan.read("database/migrations/mod.rs")?,
145 module,
146 Generator::Migration,
147 )?;
148 plan.anchor(
149 "database/migrations/mod.rs",
150 "// capy:modules",
151 &format!("mod {module};"),
152 )?;
153 plan.anchor(
154 "database/migrations/mod.rs",
155 "// capy:migrations",
156 &format!("Box::new({module}::Migration),"),
157 )
158}
159fn install_frontend(plan: &mut EditPlan<'_>) -> Result<()> {
160 let source = plan.read("app/auth.rs")?;
161 GeneratedNames::new("VerificationDelivery")?.check_registry(
162 &source,
163 "verification_delivery",
164 Generator::Controller,
165 )?;
166 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"))?;
167 plan.create(
168 "database/migrations/m_email_verification.rs",
169 include_str!("../templates/auth/verification-migration.rs.txt").into(),
170 )?;
171 migration(plan, "m_email_verification")?;
172 let factory = if plan.exists("src/bootstrap.rs") {
174 "src/bootstrap.rs"
175 } else {
176 "src/main.rs"
177 };
178 let source = plan.read(factory)?;
179 plan.replace(
180 factory,
181 crate::project::wire_application(
182 &source,
183 ".email_verification(application::app::auth::verification_delivery())",
184 )?,
185 )?;
186 let ignore = plan.read(".gitignore")?;
187 plan.replace(
188 ".gitignore",
189 format!("{ignore}\n/.capy-verification-outbox/\n"),
190 )?;
191 for (path, source) in [
192 (
193 "AuthProvider.tsx",
194 include_str!("../templates/auth/frontend/AuthProvider.tsx.txt"),
195 ),
196 (
197 "index.tsx",
198 include_str!("../templates/auth/frontend/index.tsx.txt"),
199 ),
200 (
201 "verification.ts",
202 include_str!("../templates/auth/frontend/verification.ts.txt"),
203 ),
204 (
205 "useProof.ts",
206 include_str!("../templates/auth/frontend/useProof.ts.txt"),
207 ),
208 (
209 "pages/Login.tsx",
210 include_str!("../templates/auth/frontend/Login.tsx.txt"),
211 ),
212 (
213 "pages/Register.tsx",
214 include_str!("../templates/auth/frontend/Register.tsx.txt"),
215 ),
216 (
217 "pages/ForgotPassword.tsx",
218 include_str!("../templates/auth/frontend/ForgotPassword.tsx.txt"),
219 ),
220 (
221 "pages/ResetPassword.tsx",
222 include_str!("../templates/auth/frontend/ResetPassword.tsx.txt"),
223 ),
224 (
225 "pages/VerifyEmail.tsx",
226 include_str!("../templates/auth/frontend/VerifyEmail.tsx.txt"),
227 ),
228 (
229 "pages/Account.tsx",
230 include_str!("../templates/auth/frontend/Account.tsx.txt"),
231 ),
232 ] {
233 plan.create(&format!("frontend/src/features/auth/{path}"), source.into())?;
234 }
235 plan.anchor(
236 "frontend/src/features/index.ts",
237 "// capy:feature-imports",
238 "import { authRoutes } from './auth'",
239 )?;
240 plan.anchor(
241 "frontend/src/features/index.ts",
242 "// capy:feature-routes",
243 "...authRoutes,",
244 )?;
245 plan.anchor(
246 "frontend/src/lib/providers.tsx",
247 "// capy:provider-imports",
248 "import { AuthProvider } from '../features/auth/AuthProvider'",
249 )?;
250 plan.anchor(
251 "frontend/src/lib/providers.tsx",
252 "// capy:providers",
253 "AuthProvider,",
254 )?;
255 Ok(())
256}