//! recourse admin CLI.
//!
//! Grouped subcommands so new management surfaces (categories, topics, …) can
//! be added as new `Command` variants without disturbing the existing ones.
//!
//! manage user create <username> --email E [--staff] [--password-stdin]
//! manage user list
//! manage user verify-email <username>
//! manage user resend-verification <username>
//! manage user set-staff <username> [--revoke]
//! manage user activate|deactivate <username>
//! manage user delete <username> --yes
//! manage invite create [--email E] [--days N] [--created-by UUID]
//! manage invite list
//! manage invite show <token>
//! manage email test <to>
use clap::{Parser, Subcommand};
use recourse::config::{create_db_connection, Config};
use recourse::auth;
use recourse::entities::{registration_tokens, users};
use sea_orm::*;
use std::sync::Arc;
use uuid::Uuid;
type DynErr = Box<dyn std::error::Error>;
#[derive(Parser)]
#[command(name = "manage", author, version, about = "recourse admin CLI", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// User management
User {
#[command(subcommand)]
cmd: UserCmd,
},
/// Invite (registration token) management
Invite {
#[command(subcommand)]
cmd: InviteCmd,
},
/// Outbound mail (mail-prism)
Email {
#[command(subcommand)]
cmd: EmailCmd,
},
}
#[derive(Subcommand)]
enum EmailCmd {
/// Send a plain test message through mail-prism (or report that mail
/// isn't configured)
Test { to: String },
}
#[derive(Subcommand)]
enum UserCmd {
/// Create an account directly (no invite). Prints a generated password
/// unless --password-stdin is given.
Create {
username: String,
#[arg(long)]
email: String,
/// Grant staff/admin rights (category, reaction and moderation tools)
#[arg(long)]
staff: bool,
/// Read the password from the first line of stdin instead of
/// generating one
#[arg(long)]
password_stdin: bool,
},
/// List all users
List,
/// Grant (or with --revoke, remove) staff/admin rights
SetStaff {
username: String,
#[arg(long)]
revoke: bool,
},
/// Mark a user's email address verified (no link needed)
VerifyEmail { username: String },
/// Send a fresh verification link (logged when mail-prism isn't configured)
ResendVerification { username: String },
/// Set a user's trust level (0=New 1=Basic 2=Member 3=Regular 4=Leader)
SetTrust { username: String, level: i32 },
/// Reactivate a deactivated account
Activate { username: String },
/// Deactivate an account and drop its sessions
Deactivate { username: String },
/// Permanently delete a user and all their content (topics, posts, …)
Delete {
username: String,
/// Required confirmation — deletion cascades.
#[arg(long)]
yes: bool,
},
}
#[derive(Subcommand)]
enum InviteCmd {
/// Create a new invite (registration token)
Create {
#[arg(short, long)]
email: Option<String>,
#[arg(short, long, default_value = "7")]
days: i64,
#[arg(short, long)]
created_by: Option<Uuid>,
},
/// List all invites
List,
/// Show details for a single invite
Show { token: String },
}
#[tokio::main]
async fn main() -> Result<(), DynErr> {
// recourse's own INFO lines show by default, so a logged verification
// link (no mail-prism) is visible; RUST_LOG overrides.
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "warn,recourse=info,manage=info".into()),
)
.init();
let cli = Cli::parse();
let config = Config::from_env();
let db = Arc::new(create_db_connection(&config.database_url).await?);
match cli.command {
Command::User { cmd } => run_user(&db, &config, cmd).await,
Command::Email { cmd } => run_email(&config, cmd).await,
Command::Invite { cmd } => run_invite(&db, &config, cmd).await,
}
}
// ----------------------------------------------------------------------------
// users
// ----------------------------------------------------------------------------
async fn find_user(db: &DatabaseConnection, username: &str) -> Result<users::Model, DynErr> {
users::Entity::find()
.filter(users::Column::Username.eq(username))
.one(db)
.await?
.ok_or_else(|| format!("user '{username}' not found").into())
}
async fn run_user(db: &DatabaseConnection, config: &Config, cmd: UserCmd) -> Result<(), DynErr> {
match cmd {
UserCmd::Create {
username,
email,
staff,
password_stdin,
} => {
let (password, generated) = if password_stdin {
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
let pw = line.trim_end_matches(['\r', '\n']).to_string();
if pw.is_empty() {
return Err("empty password on stdin".into());
}
(pw, false)
} else {
(auth::generate_password(), true)
};
let user = auth::create_user_direct(db, &username, &email, &password, staff).await?;
println!(
"Created {}{} <{}>.",
user.username,
if user.is_staff { " (staff)" } else { "" },
user.email
);
if generated {
println!();
println!("Password (shown once, store it now): {password}");
}
}
UserCmd::List => {
let rows = users::Entity::find()
.order_by_asc(users::Column::CreatedAt)
.all(db)
.await?;
if rows.is_empty() {
println!("No users.");
return Ok(());
}
println!("{:<20} {:<28} {:<7} {:<7} {:<10}", "Username", "Email", "Staff", "Active", "Trust");
for u in rows {
println!(
"{:<20} {:<28} {:<7} {:<7} {:<10}",
u.username,
u.email,
if u.is_staff { "yes" } else { "no" },
if u.is_active { "yes" } else { "no" },
format!("{} ({})", u.trust_level, recourse::trust::tier_name(u.trust_level)),
);
}
}
UserCmd::SetStaff { username, revoke } => {
let user = find_user(db, &username).await?;
let mut am: users::ActiveModel = user.into();
am.is_staff = Set(!revoke);
am.updated_at = Set(chrono::Utc::now().into());
am.update(db).await?;
println!(
"{} is {} staff.",
username,
if revoke { "no longer" } else { "now" }
);
}
UserCmd::VerifyEmail { username } => {
let user = find_user(db, &username).await?;
if user.email_verified_at.is_some() {
println!("{username}'s email ({}) is already verified.", user.email);
} else {
auth::verification::mark_verified(db, &user).await?;
println!("{username}'s email ({}) is now verified.", user.email);
}
}
UserCmd::ResendVerification { username } => {
use auth::verification::Sent;
let user = find_user(db, &username).await?;
let mailer = recourse::mailer::build(config, false);
// The operator asked explicitly, so skip the resend rate limit.
match auth::verification::send(db, mailer.as_ref(), config, &user).await {
Sent::Yes if mailer.delivers() => println!("Verification link sent to {}.", user.email),
Sent::Yes => println!(
"mail-prism isn't configured: the verification link was logged above."
),
Sent::AlreadyVerified => println!("{username}'s email is already verified."),
Sent::Recently => println!("A link went out moments ago."),
Sent::Failed => return Err("sending the verification link failed (see the log)".into()),
}
}
UserCmd::SetTrust { username, level } => {
let user = find_user(db, &username).await?;
let level = level.clamp(0, 4);
let mut am: users::ActiveModel = user.into();
am.trust_level = Set(level);
am.updated_at = Set(chrono::Utc::now().into());
am.update(db).await?;
println!("{username} is now trust level {level} ({}).", recourse::trust::tier_name(level));
}
UserCmd::Activate { username } => {
let user = find_user(db, &username).await?;
let mut am: users::ActiveModel = user.into();
am.is_active = Set(true);
am.updated_at = Set(chrono::Utc::now().into());
am.update(db).await?;
println!("{username} activated.");
}
UserCmd::Deactivate { username } => {
let user = find_user(db, &username).await?;
auth::deactivate_user(db, user.id).await?;
println!("{username} deactivated (sessions dropped).");
}
UserCmd::Delete { username, yes } => {
let user = find_user(db, &username).await?;
if !yes {
eprintln!(
"Refusing to delete '{username}': pass --yes to confirm. \
This cascades to their topics and posts."
);
return Err("confirmation required".into());
}
users::Entity::delete_by_id(user.id).exec(db).await?;
println!("{username} deleted.");
}
}
Ok(())
}
// ----------------------------------------------------------------------------
// invites
// ----------------------------------------------------------------------------
fn token_status(is_used: bool, expires_at: chrono::DateTime<chrono::FixedOffset>) -> &'static str {
if is_used {
"Used"
} else if expires_at < chrono::Utc::now() {
"Expired"
} else {
"Active"
}
}
async fn run_invite(db: &DatabaseConnection, config: &Config, cmd: InviteCmd) -> Result<(), DynErr> {
match cmd {
InviteCmd::Create {
email,
days,
created_by,
} => {
let token =
auth::create_registration_token(db, created_by, email.clone(), days).await?;
println!("Invite created.");
println!();
println!("Token: {}", token.token);
println!("Email: {}", email.unwrap_or_else(|| "Any".to_string()));
println!("Expires: {}", token.expires_at);
println!();
println!("Registration URL:");
println!(" http://{}/register?token={}", config.bind_address, token.token);
}
InviteCmd::List => {
let rows = registration_tokens::Entity::find()
.order_by_desc(registration_tokens::Column::CreatedAt)
.all(db)
.await?;
if rows.is_empty() {
println!("No invites.");
return Ok(());
}
println!("{:<40} {:<20} {:<8} {:<20}", "Token", "Email", "Status", "Expires");
for t in rows {
println!(
"{:<40} {:<20} {:<8} {:<20}",
t.token,
t.email.as_deref().unwrap_or("Any"),
token_status(t.is_used, t.expires_at),
t.expires_at.format("%Y-%m-%d %H:%M:%S"),
);
}
}
InviteCmd::Show { token } => {
let found = registration_tokens::Entity::find()
.filter(registration_tokens::Column::Token.eq(&token))
.one(db)
.await?;
match found {
Some(t) => {
println!("Token: {}", t.token);
println!("Email: {}", t.email.clone().unwrap_or_else(|| "Any".to_string()));
println!("Status: {}", token_status(t.is_used, t.expires_at));
println!("Created: {}", t.created_at);
println!("Expires: {}", t.expires_at);
println!(
"Created by: {}",
t.created_by_user_id
.map_or_else(|| "System".to_string(), |id| id.to_string())
);
if t.is_used {
println!(
"Used by: {}",
t.used_by_user_id
.map_or_else(|| "Unknown".to_string(), |id| id.to_string())
);
}
}
None => println!("Token not found: {token}"),
}
}
}
Ok(())
}
// ----------------------------------------------------------------------------
// email
// ----------------------------------------------------------------------------
async fn run_email(config: &Config, cmd: EmailCmd) -> Result<(), DynErr> {
match cmd {
EmailCmd::Test { to } => match recourse::mailer::mail_prism_mailer(config) {
None => {
println!(
"mail-prism is not configured (MAIL_PRISM_URL / MAIL_PRISM_API_KEY unset): \
outbound mail is only logged, nothing was sent."
);
}
Some(Err(e)) => return Err(format!("mail-prism client: {e}").into()),
Some(Ok(mailer)) => {
let id = mailer.send_test(&to, &config.app_name).await?;
println!("Queued with mail-prism as message {id}.");
}
},
}
Ok(())
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions running · Badges · Packages
⭐
Log in to mark this repository.
13.9 KiB · text
History
de2cabc