Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
pub mod invitations;
pub mod memberships;
pub mod oauth;
pub mod setup;
pub mod sign_in;
pub mod tokens;

Expand Down Expand Up @@ -270,4 +271,5 @@ pub fn routes(route: &mut laravel::prelude::Router) {
route.get("/auth/session", sign_in::session);
route.get("/auth/providers", sign_in::providers);
route.post("/auth/logout", sign_in::logout);
setup::routes(route);
}
95 changes: 95 additions & 0 deletions app/src/auth/setup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//! The "Set up VisualCI" checklist (sc-8900, ported from today's server): each step ticks itself from what has actually
//! happened, with no "mark done". An organization's admins can close it, or open it again.

use laravel::auth::Authenticated;
use laravel::db;
use laravel::prelude::*;
use serde_json::{Value, json};

use super::Role;
use crate::models::User;

pub fn routes(route: &mut Router) {
route.post("/api/ui/orgs/{org}/setup", update);
}

/// The steps, in order.
pub const STEPS: &[&str] = &["connect_agent", "create_project", "install_github_app", "add_to_ci", "review_changes"];

/// The checklist for an organization as `user_pid` sees it (a connected agent is per person: an MCP connection, or a
/// personal token that has been used; with no person, such as a project token, it isn't done): each step and whether
/// it's done, the next one, whether it's complete (a build has been approved) and whether someone closed it. Callers
/// check first that the person may see the organization: this reads it as asked.
///
/// # Errors
/// On a database error.
pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> laravel::Result<Value> {
// An OAuth token's subject is the person's pid as text; the users table is matched on the uuid, by its index
let subject = user_pid.map(|p| p.to_string());
let row = db::query!(
"SELECT \
{subject}::text IS NOT NULL AND ( \
EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.subject = {subject}) \
OR EXISTS (SELECT 1 FROM user_tokens ut JOIN users u ON u.id = ut.user_id \
WHERE u.pid = {subject}::uuid AND ut.last_used_at IS NOT NULL)) AS connect_agent, \
EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id}) AS create_project, \
EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id} AND forge_installation IS NOT NULL) \
AS install_github_app, \
EXISTS (SELECT 1 FROM builds b JOIN projects p ON p.id = b.project_id \
WHERE p.organization_id = {org_id} AND b.mode = 'ci') AS add_to_ci, \
EXISTS (SELECT 1 FROM reviews r JOIN builds b ON b.id = r.build_id JOIN projects p ON p.id = b.project_id \
WHERE p.organization_id = {org_id} AND r.action = 'approve') AS review_changes, \
(SELECT setup_dismissed_at IS NOT NULL FROM organizations WHERE id = {org_id}) AS dismissed"
)
.select_one()
.await?
.ok_or_else(|| laravel::Error::msg("no setup row"))?;
let mut steps = Vec::new();
for key in STEPS {
steps.push((*key, row.try_get::<bool>(*key)?));
}
let next = steps.iter().find(|(_, done)| !done).map(|(key, _)| *key);
let complete = steps.last().is_some_and(|(_, done)| *done);
Ok(json!({
"steps": steps.iter().map(|(key, done)| json!({ "key": key, "done": done })).collect::<Vec<_>>(),
"next": next,
"complete": complete,
"dismissed": row.try_get::<Option<bool>>("dismissed")?.unwrap_or(false),
}))
}

#[laravel::input]
#[validate(authenticated)]
pub struct SetupInput {
dismissed: bool,
}

/// `POST /api/ui/orgs/{org}/setup` (admins): close the checklist, or open it again.
pub async fn update(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
Valid(p): Valid<SetupInput>,
) -> laravel::Result<Json<Value>> {
let user_id = user.id;
let row = db::query!(
"SELECT o.id, m.role FROM organizations o \
LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}"
)
.select_one()
.await?
.ok_or_else(|| laravel::abort(404))?;
let org_id: i64 = row.try_get("id")?;
match row.try_get::<Option<String>>("role")?.as_deref().and_then(Role::parse) {
Some(Role::Admin) => {}
Some(_) => return Err(laravel::abort_with(403, "only admins can change the setup checklist")),
None => return Err(laravel::abort(404)),
}
let dismissed = p.dismissed;
db::query!(
"UPDATE organizations SET setup_dismissed_at = CASE WHEN {dismissed} THEN now() END, updated_at = now() \
WHERE id = {org_id}"
)
.update()
.await?;
Ok(Json(state(org_id, Some(user.pid)).await?))
}
56 changes: 56 additions & 0 deletions app/tests/setup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! The setup checklist ticks itself from what happened, and an organization's admins can close it.

use app::models::User;
use laravel::db;
use laravel::model::create;
use laravel::testing::prelude::*;

#[laravel::test]
async fn the_checklist_follows_what_happened(app: Application) -> laravel::Result<()> {
let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?;
let ada_id = ada.id;
let org: i64 = db::query!(
"INSERT INTO organizations (pid, slug, name, created_at, updated_at) \
VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id"
)
.scalar()
.await?
.unwrap();
db::query!(
"INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \
VALUES ({org}, {ada_id}, 'admin', 'created', now(), now())"
)
.insert()
.await?;
let state = app::auth::setup::state(org, Some(ada.pid)).await?;
assert_eq!(state["next"], "connect_agent");
// A used personal token ticks it for her; nobody's (a project token's view) never does
db::query!(
"INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, last_used_at, created_at, updated_at) \
VALUES ({ada_id}, 'laptop', 'h', 'vcu_abcdef', now(), now(), now())"
)
.insert()
.await?;
assert_eq!(app::auth::setup::state(org, Some(ada.pid)).await?["steps"][0]["done"], true);
assert_eq!(app::auth::setup::state(org, None).await?["steps"][0]["done"], false);
db::query!(
"INSERT INTO projects (pid, organization_id, slug, name, forge_installation, created_at, updated_at) \
VALUES (gen_random_uuid(), {org}, 'web', 'Web', '7', now(), now())"
)
.insert()
.await?;
let state = app::auth::setup::state(org, Some(ada.pid)).await?;
assert_eq!(state["steps"][1]["done"], true);
assert_eq!(state["steps"][2]["done"], true);
assert_eq!(state["complete"], false);

let close = |dismissed: bool| {
app.post("/api/ui/orgs/acme/setup")
.acting_as(&ada)
.header("sec-fetch-site", "same-origin")
.json(json!({ "dismissed": dismissed }))
};
close(true).await.assert_ok().assert_json_path("dismissed", true);
close(false).await.assert_ok().assert_json_path("dismissed", false);
Ok(())
}
Loading