Skip to main content

capy_cli/
auth.rs

1use crate::{
2    generate::format_rust, names::GeneratedNames, FrontendDriver, Generator, ProjectConfig,
3};
4use anyhow::{bail, Context, Result};
5use fs2::FileExt;
6use std::{
7    fs::{self, OpenOptions},
8    io::Write,
9    path::{Path, PathBuf},
10    time::{SystemTime, UNIX_EPOCH},
11};
12
13struct Change {
14    path: PathBuf,
15    before: Option<Vec<u8>>,
16    after: Vec<u8>,
17}
18
19/// Install conventional auth without overwriting application-owned files.
20/// All sources and registry edits are validated/formatted before the first mutation.
21pub fn make_auth(root: &Path) -> Result<Vec<PathBuf>> {
22    reject_symlinks(root, &root.join(".capy-generator.lock"))?;
23    let lock = OpenOptions::new()
24        .read(true)
25        .write(true)
26        .create(true)
27        .truncate(false)
28        .open(root.join(".capy-generator.lock"))?;
29    lock.lock_exclusive()
30        .context("Cannot lock the Capy generator registry")?;
31    let mut changes = Vec::new();
32    let mut add = |relative: &str, after: String, replace: bool| -> Result<()> {
33        let path = root.join(relative);
34        reject_symlinks(root, &path)?;
35        let before = match fs::read(&path) {
36            Ok(bytes) => Some(bytes),
37            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
38            Err(error) => return Err(error.into()),
39        };
40        if !replace && before.is_some() {
41            bail!("{} already exists. Auth may already be installed; Capy never overwrites application files.", path.display());
42        }
43        if replace && before.is_none() {
44            bail!("Required registry {} is missing.", path.display());
45        }
46        let after = if relative.ends_with(".rs") {
47            format_rust(&after)?
48        } else {
49            after
50        };
51        changes.push(Change {
52            path,
53            before,
54            after: after.into_bytes(),
55        });
56        Ok(())
57    };
58    add(
59        "app/auth.rs",
60        include_str!("../templates/auth/auth.rs.txt").into(),
61        false,
62    )?;
63    add(
64        "app/models/user.rs",
65        include_str!("../templates/auth/user.rs.txt").into(),
66        false,
67    )?;
68    add("config/auth.toml", "# Auth is activated explicitly by App::auth in src/main.rs.\nsession_lifetime_seconds = 2592000\npassword_reset_lifetime_seconds = 1800\nsame_site = \"lax\"\n# cookie_name = \"my_app_session\"\n# Secure defaults to true in production, false on local HTTP.\n".into(), false)?;
69    let app_registry = read(root, "app/mod.rs")?;
70    GeneratedNames::new("Auth")?.check_registry(&app_registry, "auth", Generator::Controller)?;
71    add(
72        "app/mod.rs",
73        format!("{app_registry}\npub mod auth;\n"),
74        true,
75    )?;
76    let models = read(root, "app/models/mod.rs")?;
77    GeneratedNames::new("User")?.check_registry(&models, "user", Generator::Model)?;
78    add("app/models/mod.rs", format!("{models}\npub mod user;\npub use user::Entity as User;\npub use user::Model as UserModel;\n"), true)?;
79    let migration = format!(
80        "m{}_create_identity",
81        SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
82    );
83    add(
84        &format!("database/migrations/{migration}.rs"),
85        include_str!("../templates/auth/migration.rs.txt").into(),
86        false,
87    )?;
88    let registry = read(root, "database/migrations/mod.rs")?;
89    if registry.matches("// capy:modules").count() != 1
90        || registry.matches("// capy:migrations").count() != 1
91    {
92        bail!("Restore // capy:modules and // capy:migrations in the migration registry before installing auth.");
93    }
94    add(
95        "database/migrations/mod.rs",
96        registry
97            .replace(
98                "// capy:modules",
99                &format!("mod {migration};\n// capy:modules"),
100            )
101            .replace(
102                "// capy:migrations",
103                &format!("Box::new({migration}::Migration),\n// capy:migrations"),
104            ),
105        true,
106    )?;
107    let main = read(root, "src/main.rs")?;
108    if main.matches("App::new()").count() != 1 || !main.contains("as application;") {
109        bail!("Auth installation needs the conventional App::new() builder and `application` crate alias in src/main.rs. Restore that entry point or install auth manually; no files changed.");
110    }
111    add(
112        "src/main.rs",
113        main.replace(
114            "App::new()",
115            "App::new().auth(application::app::auth::delivery())",
116        ),
117        true,
118    )?;
119    let mut manifest = read(root, "Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
120    let dependency = manifest["dependencies"]["capy"]
121        .as_table_like_mut()
122        .context("Use a table-style capy-framework dependency before installing auth.")?;
123    let mut features = dependency
124        .get("features")
125        .and_then(|v| v.as_array())
126        .cloned()
127        .unwrap_or_default();
128    if !features.iter().any(|v| v.as_str() == Some("auth")) {
129        features.push("auth");
130    }
131    dependency.insert("features", toml_edit::value(features));
132    add("Cargo.toml", manifest.to_string(), true)?;
133    let gitignore = read(root, ".gitignore")?;
134    add(
135        ".gitignore",
136        format!("{gitignore}\n/.capy-reset-outbox/\n"),
137        true,
138    )?;
139    if ProjectConfig::load(root)?.frontend.driver == FrontendDriver::React {
140        // Upgrade only the byte-for-byte previous conventional helper. Customized
141        // clients must expose the hook explicitly; never replace application edits.
142        let helper = read(root, "frontend/src/lib/api.ts")?;
143        if helper == include_str!("../templates/auth/legacy-api.ts.txt") {
144            add(
145                "frontend/src/lib/api.ts",
146                include_str!("../templates/frontend/src/lib/api.ts.txt").into(),
147                true,
148            )?;
149        } else if !helper.contains("export function setCsrfTokenProvider(") {
150            bail!("The customized frontend API helper needs setCsrfTokenProvider support. Add the hook from the current Capy template before installing auth; no files changed.");
151        }
152        add(
153            "frontend/src/lib/auth.ts",
154            include_str!("../templates/auth/auth.ts.txt").into(),
155            false,
156        )?;
157        let main = read(root, "frontend/src/main.tsx")?;
158        add(
159            "frontend/src/main.tsx",
160            format!("import './lib/auth'\n{main}"),
161            true,
162        )?;
163    }
164    // Stage and sync every file before committing. Cooperative generators share the lock.
165    let mut staged = Vec::new();
166    for change in &changes {
167        let mut file =
168            tempfile::NamedTempFile::new_in(change.path.parent().context("Missing parent")?)?;
169        if change.before.is_some() {
170            file.as_file()
171                .set_permissions(fs::metadata(&change.path)?.permissions())?;
172        }
173        file.write_all(&change.after)?;
174        file.as_file().sync_all()?;
175        staged.push(file);
176    }
177    for (index, (file, change)) in staged.into_iter().zip(&changes).enumerate() {
178        let result = if change.before.is_some() {
179            file.persist(&change.path).map(|_| ()).map_err(|e| e.error)
180        } else {
181            file.persist_noclobber(&change.path)
182                .map(|_| ())
183                .map_err(|e| e.error)
184        };
185        if let Err(error) = result {
186            for previous in changes[..index].iter().rev() {
187                match &previous.before {
188                    Some(bytes) => fs::write(&previous.path, bytes).with_context(|| {
189                        format!(
190                            "Auth rollback failed for {}; inspect the partially installed files.",
191                            previous.path.display()
192                        )
193                    })?,
194                    None => fs::remove_file(&previous.path)?,
195                }
196            }
197            return Err(error)
198                .context("Auth installation failed; committed file changes were rolled back");
199        }
200    }
201    Ok(changes.into_iter().map(|change| change.path).collect())
202}
203fn read(root: &Path, relative: &str) -> Result<String> {
204    let path = root.join(relative);
205    reject_symlinks(root, &path)?;
206    fs::read_to_string(&path).with_context(|| format!("Cannot read {}", path.display()))
207}
208fn reject_symlinks(root: &Path, path: &Path) -> Result<()> {
209    for ancestor in path.ancestors().take_while(|p| *p != root) {
210        if let Ok(metadata) = fs::symlink_metadata(ancestor) {
211            if metadata.file_type().is_symlink() {
212                bail!("Auth installer refuses symlink {}", ancestor.display());
213            }
214        }
215    }
216    Ok(())
217}