11.3 KiB · text History 60fbb92
use crate::auth::{password, tokens};
use crate::entities::{user_sessions, users};
use anyhow::{Context, Result};
use chrono::Utc;
use sea_orm::sea_query::{Expr, Func};
use sea_orm::*;
use uuid::Uuid;

#[derive(Debug)]
pub struct CreateUserRequest {
    pub username: String,
    pub email: String,
    pub password: String,
    /// An invite. With one, it must be valid (and match its email, if it's
    /// pinned to one) and is redeemed; without one, only when `open`.
    pub registration_token: Option<String>,
    /// `REGISTRATION_ENABLED`: an account may be created without an invite.
    pub open: bool,
}

#[derive(Debug)]
pub struct LoginRequest {
    pub username: String,
    pub password: String,
}

/// Why registration refused. Everything but `Internal` is shown to the
/// person registering.
#[derive(Debug)]
pub enum RegisterError {
    /// Closed registration and no invite.
    InviteRequired,
    InvalidInvite,
    Taken,
    Invalid(&'static str),
    Internal(anyhow::Error),
}

impl RegisterError {
    pub fn message(&self) -> &'static str {
        match self {
            Self::InviteRequired => "You need an invite to register here.",
            Self::InvalidInvite => "This invite is invalid, expired, already used, or for a different email address.",
            Self::Taken => "That username or email is already registered.",
            Self::Invalid(m) => m,
            Self::Internal(_) => "Registration failed. Please try again.",
        }
    }
}

impl std::fmt::Display for RegisterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Internal(e) => write!(f, "{e:#}"),
            other => f.write_str(other.message()),
        }
    }
}

impl From<anyhow::Error> for RegisterError {
    fn from(e: anyhow::Error) -> Self {
        Self::Internal(e)
    }
}

/// Usernames people type in: 3-32 of letters, digits, `_ . -`.
fn valid_username(name: &str) -> bool {
    (3..=32).contains(&name.chars().count())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
}

/// Create an account from the registration form: through an invite (always
/// allowed, redeems it) or, with open registration, without one. The
/// account starts unverified, like every self-made account.
pub async fn create_user(db: &DatabaseConnection, request: CreateUserRequest) -> Result<users::Model, RegisterError> {
    let username = request.username.trim().to_string();
    let email = request.email.trim().to_string();
    if !valid_username(&username) {
        return Err(RegisterError::Invalid("Usernames are 3 to 32 letters, digits, dots, dashes or underscores."));
    }
    if !email.contains('@') || email.len() > 254 || email.chars().any(char::is_whitespace) {
        return Err(RegisterError::Invalid("Enter a valid email address."));
    }
    if request.password.chars().count() < 8 {
        return Err(RegisterError::Invalid("Passwords need at least 8 characters."));
    }
    let token = request.registration_token.as_deref().map(str::trim).filter(|t| !t.is_empty());
    let reg_token = match token {
        Some(t) => Some(
            tokens::validate_registration_token(db, t, &email)
                .await
                .context("Failed to validate registration token")?
                .ok_or(RegisterError::InvalidInvite)?,
        ),
        None if request.open => None,
        None => return Err(RegisterError::InviteRequired),
    };

    let existing_user = users::Entity::find()
        .filter(
            Condition::any()
                .add(Expr::expr(Func::lower(Expr::col(users::Column::Username))).eq(username.to_lowercase()))
                .add(Expr::expr(Func::lower(Expr::col(users::Column::Email))).eq(email.to_lowercase())),
        )
        .one(db)
        .await
        .context("Failed to check existing users")?;

    if existing_user.is_some() {
        return Err(RegisterError::Taken);
    }

    let password_hash =
        password::hash_password(&request.password).context("Failed to hash password")?;

    // Staff is never granted implicitly: use `manage user create --staff` or
    // `manage user set-staff`.
    let new_user = new_user_model(username, email, password_hash, false);

    let user = new_user.insert(db).await.context("Failed to create user")?;

    if let Some(t) = reg_token {
        tokens::mark_registration_token_used(db, t.id, user.id)
            .await
            .context("Failed to mark registration token as used")?;
    }

    Ok(user)
}

/// A fresh `users` row with recourse's defaults (trust level 0, latest sort,
/// reaction notifications on, no avatar).
pub(crate) fn new_user_model(
    username: String,
    email: String,
    password_hash: String,
    is_staff: bool,
) -> users::ActiveModel {
    let now = Utc::now();
    users::ActiveModel {
        id: Set(Uuid::now_v7()),
        username: Set(username),
        email: Set(email),
        password_hash: Set(password_hash),
        is_active: Set(true),
        is_staff: Set(is_staff),
        preferred_sort: Set("latest".to_string()),
        preferred_view: Set("classic".to_string()),
        reaction_notifications: Set(true),
        trust_level: Set(0),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
        last_login_at: Set(None),
        email_verified_at: Set(None),
        avatar_data: Set(None),
        avatar_content_type: Set(None),
        silenced_at: Set(None),
        silenced_until: Set(None),
        silence_reason: Set(None),
        suspended_at: Set(None),
        suspended_until: Set(None),
        suspend_reason: Set(None),
        flags_ignored_at: Set(None),
    }
}

/// Create a user directly, without an invite — the operator path used by
/// `manage user create` (and the demo seed). Refuses a taken username or
/// email. The operator vouches for the address, so it starts verified.
pub async fn create_user_direct(
    db: &DatabaseConnection,
    username: &str,
    email: &str,
    password: &str,
    is_staff: bool,
) -> Result<users::Model> {
    let username = username.trim();
    let email = email.trim();
    if username.is_empty() || email.is_empty() {
        return Err(anyhow::anyhow!("username and email are required"));
    }
    let taken = users::Entity::find()
        .filter(
            Condition::any()
                .add(users::Column::Username.eq(username))
                .add(users::Column::Email.eq(email)),
        )
        .one(db)
        .await
        .context("Failed to check existing users")?;
    if let Some(other) = taken {
        return Err(if other.username == username {
            anyhow::anyhow!("username '{username}' is already taken")
        } else {
            anyhow::anyhow!("email '{email}' is already in use")
        });
    }
    let password_hash = password::hash_password(password).context("Failed to hash password")?;
    let mut am = new_user_model(username.to_string(), email.to_string(), password_hash, is_staff);
    am.email_verified_at = Set(Some(Utc::now().into()));
    am.insert(db)
        .await
        .context("Failed to create user")
}

/// Authenticate a user by username + password, bumping `last_login_at`.
pub async fn authenticate_user(
    db: &DatabaseConnection,
    request: LoginRequest,
) -> Result<Option<users::Model>> {
    let user = users::Entity::find()
        .filter(users::Column::Username.eq(&request.username))
        .filter(users::Column::IsActive.eq(true))
        .one(db)
        .await
        .context("Failed to query user")?;

    if let Some(mut user) = user {
        let password_valid = password::verify_password(&request.password, &user.password_hash)
            .context("Failed to verify password")?;

        if password_valid {
            let mut user_update: users::ActiveModel = user.clone().into();
            user_update.last_login_at = Set(Some(Utc::now().into()));
            user = user_update.update(db).await.context("Failed to update last login")?;
            Ok(Some(user))
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}

/// Get a user by id.
pub async fn get_user_by_id(db: &DatabaseConnection, user_id: Uuid) -> Result<Option<users::Model>> {
    users::Entity::find_by_id(user_id)
        .one(db)
        .await
        .context("Failed to query user")
}

/// Update a user's username and/or email, enforcing uniqueness.
pub async fn update_user(
    db: &DatabaseConnection,
    user_id: Uuid,
    username: Option<String>,
    email: Option<String>,
) -> Result<users::Model> {
    let user = get_user_by_id(db, user_id)
        .await?
        .ok_or_else(|| anyhow::anyhow!("User not found"))?;

    let mut user_update: users::ActiveModel = user.into();
    user_update.updated_at = Set(Utc::now().into());

    if let Some(username) = username {
        let existing = users::Entity::find()
            .filter(users::Column::Username.eq(&username))
            .filter(users::Column::Id.ne(user_id))
            .one(db)
            .await
            .context("Failed to check username availability")?;
        if existing.is_some() {
            return Err(anyhow::anyhow!("Username already taken"));
        }
        user_update.username = Set(username);
    }

    if let Some(email) = email {
        let existing = users::Entity::find()
            .filter(users::Column::Email.eq(&email))
            .filter(users::Column::Id.ne(user_id))
            .one(db)
            .await
            .context("Failed to check email availability")?;
        if existing.is_some() {
            return Err(anyhow::anyhow!("Email already taken"));
        }
        // A new address has to be verified again.
        user_update.email = Set(email);
        user_update.email_verified_at = Set(None);
    }

    user_update.update(db).await.context("Failed to update user")
}

/// Change a user's password after verifying the old one.
pub async fn change_password(
    db: &DatabaseConnection,
    user_id: Uuid,
    old_password: &str,
    new_password: &str,
) -> Result<()> {
    let user = get_user_by_id(db, user_id)
        .await?
        .ok_or_else(|| anyhow::anyhow!("User not found"))?;

    let old_password_valid = password::verify_password(old_password, &user.password_hash)
        .context("Failed to verify old password")?;
    if !old_password_valid {
        return Err(anyhow::anyhow!("Invalid old password"));
    }

    let new_password_hash =
        password::hash_password(new_password).context("Failed to hash new password")?;

    let mut user_update: users::ActiveModel = user.into();
    user_update.password_hash = Set(new_password_hash);
    user_update.updated_at = Set(Utc::now().into());
    user_update.update(db).await.context("Failed to update password")?;
    Ok(())
}

/// Deactivate a user and drop all their sessions.
pub async fn deactivate_user(db: &DatabaseConnection, user_id: Uuid) -> Result<()> {
    let user = get_user_by_id(db, user_id)
        .await?
        .ok_or_else(|| anyhow::anyhow!("User not found"))?;

    let mut user_update: users::ActiveModel = user.into();
    user_update.is_active = Set(false);
    user_update.updated_at = Set(Utc::now().into());
    user_update.update(db).await.context("Failed to deactivate user")?;

    user_sessions::Entity::delete_many()
        .filter(user_sessions::Column::UserId.eq(user_id))
        .exec(db)
        .await
        .context("Failed to delete user sessions")?;

    Ok(())
}