3.5 KiB · text History 2264215
use axum::{
    extract::{Multipart, Path, State},
    http::{header, StatusCode},
    response::{IntoResponse, Redirect, Response},
};
use sea_orm::*;
use tracing::error;
use uuid::Uuid;

use crate::avatar::letter_avatar_svg;
use crate::entities::users;
use crate::middleware::UserContext;
use crate::AppState;

const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
const MAX_AVATAR_BYTES: usize = 5 * 1024 * 1024;

/// Serve a user's avatar: their uploaded image if present, otherwise a
/// generated letter avatar. Always returns an image so templates can use a
/// single `<img>` unconditionally.
pub async fn serve_avatar(State(state): State<AppState>, Path(id): Path<Uuid>) -> Response {
    let user = match users::Entity::find_by_id(id).one(state.db.as_ref()).await {
        Ok(Some(u)) => u,
        Ok(None) => return StatusCode::NOT_FOUND.into_response(),
        Err(e) => {
            error!(error = %e, "load user for avatar");
            return StatusCode::INTERNAL_SERVER_ERROR.into_response();
        }
    };

    let cache = (header::CACHE_CONTROL, "public, max-age=300");
    match (user.avatar_data, user.avatar_content_type) {
        (Some(bytes), Some(ct)) => {
            ([(header::CONTENT_TYPE, ct), (cache.0, cache.1.to_string())], bytes).into_response()
        }
        _ => {
            let svg = letter_avatar_svg(&user.username);
            (
                [
                    (header::CONTENT_TYPE, "image/svg+xml".to_string()),
                    (cache.0, cache.1.to_string()),
                ],
                svg,
            )
                .into_response()
        }
    }
}

/// Handle an avatar upload (multipart) from the profile panel.
pub async fn upload_avatar(
    State(state): State<AppState>,
    user: UserContext,
    mut multipart: Multipart,
) -> Result<Redirect, StatusCode> {
    while let Some(field) = multipart.next_field().await.map_err(|_| StatusCode::BAD_REQUEST)? {
        if field.name() != Some("avatar") {
            continue;
        }
        let content_type = field.content_type().map(|s| s.to_string());
        let data = field.bytes().await.map_err(|_| StatusCode::BAD_REQUEST)?;
        if data.is_empty() {
            return Ok(Redirect::to("/profile"));
        }
        if data.len() > MAX_AVATAR_BYTES {
            return Err(StatusCode::PAYLOAD_TOO_LARGE);
        }
        let content_type = content_type
            .filter(|ct| ALLOWED_TYPES.contains(&ct.as_str()))
            .ok_or(StatusCode::UNSUPPORTED_MEDIA_TYPE)?;

        let mut am: users::ActiveModel = user.user.clone().into();
        am.avatar_data = Set(Some(data.to_vec()));
        am.avatar_content_type = Set(Some(content_type));
        am.updated_at = Set(chrono::Utc::now().into());
        am.update(state.db.as_ref()).await.map_err(|e| {
            error!(error = %e, "save avatar");
            StatusCode::INTERNAL_SERVER_ERROR
        })?;
        return Ok(Redirect::to("/profile"));
    }
    Ok(Redirect::to("/profile"))
}

/// Clear an uploaded avatar, reverting to the generated letter avatar.
pub async fn delete_avatar(
    State(state): State<AppState>,
    user: UserContext,
) -> Result<Redirect, StatusCode> {
    let mut am: users::ActiveModel = user.user.clone().into();
    am.avatar_data = Set(None);
    am.avatar_content_type = Set(None);
    am.updated_at = Set(chrono::Utc::now().into());
    am.update(state.db.as_ref()).await.map_err(|e| {
        error!(error = %e, "clear avatar");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    Ok(Redirect::to("/profile"))
}