5.2 KiB · text History 63417ef
//! `me`, devices, and signing this device out.
use axum::extract::{Multipart, State};
use axum::http::StatusCode;
use axum::Json;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use uuid::Uuid;

use super::views::{utc, MeResponse};
use super::{ApiError, ApiJson, ApiPath, ApiResult};
use crate::actions::{self, Preferences};
use crate::auth;
use crate::handlers::focus::ViewMode;
use crate::handlers::forum::TopicSort;
use crate::middleware::{ApiDevice, UserContext};
use crate::AppState;

/// `GET /me` — who this token belongs to. The app's pairing probe.
pub async fn show(State(state): State<AppState>, uc: UserContext) -> Json<MeResponse> {
    Json(MeResponse::new(&state, &uc.user))
}

#[derive(Debug, Deserialize)]
pub struct MePatch {
    /// `classic` or `focus` (the web's aliases `list` / `visual` too).
    pub layout: Option<String>,
    /// `latest`, `top`, `bottom` or `hot`.
    pub sort: Option<String>,
    pub reaction_notifications: Option<bool>,
}

/// `PATCH /me` — the profile's preferences. Absent fields stay as they are.
pub async fn update(
    State(state): State<AppState>,
    uc: UserContext,
    ApiJson(body): ApiJson<MePatch>,
) -> ApiResult<Json<MeResponse>> {
    let layout = match body.layout.as_deref() {
        None => None,
        Some(s) => Some(ViewMode::parse(s).ok_or_else(|| ApiError::invalid("Layout is classic or focus."))?),
    };
    let sort = match body.sort.as_deref() {
        None => None,
        Some(s) => {
            Some(TopicSort::parse(s).ok_or_else(|| ApiError::invalid("Sort is latest, top, bottom or hot."))?)
        }
    };
    let user = actions::update_preferences(
        &state,
        &uc.user,
        Preferences { reaction_notifications: body.reaction_notifications, layout, sort },
    )
    .await?;
    Ok(Json(MeResponse::new(&state, &user)))
}

/// `PUT /me/avatar` — multipart, one `avatar` part.
pub async fn set_avatar(
    State(state): State<AppState>,
    uc: UserContext,
    mut multipart: Multipart,
) -> ApiResult<Json<MeResponse>> {
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|_| ApiError::invalid("That upload couldn't be read."))?
    {
        if field.name() != Some("avatar") {
            continue;
        }
        let content_type = field.content_type().map(str::to_string);
        let data = field.bytes().await.map_err(|_| ApiError::invalid("That upload couldn't be read."))?;
        let user = actions::set_avatar(&state, &uc.user, content_type.as_deref(), data.to_vec()).await?;
        return Ok(Json(MeResponse::new(&state, &user)));
    }
    Err(ApiError::invalid("Send the image as a multipart part named avatar."))
}

/// `DELETE /me/avatar` — back to the letter avatar.
pub async fn clear_avatar(State(state): State<AppState>, uc: UserContext) -> ApiResult<Json<MeResponse>> {
    let user = actions::clear_avatar(&state, &uc.user).await?;
    Ok(Json(MeResponse::new(&state, &user)))
}

/// `POST /me/verification` — mail a fresh verification link, rate-limited
/// exactly as the web's banner button. `result` is `sent`, `recent` (one went
/// out in the last few minutes), `verified` (nothing to do) or `failed`.
pub async fn resend_verification(State(state): State<AppState>, uc: UserContext) -> Json<serde_json::Value> {
    let sent = auth::verification::send_if_due(&state.db, state.mailer.as_ref(), &state.config, &uc.user).await;
    Json(json!({ "result": sent.as_str() }))
}

#[derive(Serialize)]
pub struct Device {
    pub id: Uuid,
    pub label: Option<String>,
    pub created_at: DateTime<Utc>,
    pub last_used_at: Option<DateTime<Utc>>,
    pub expires_at: Option<DateTime<Utc>>,
    /// The token this request came with.
    pub current: bool,
}

#[derive(Serialize)]
pub struct Devices {
    pub devices: Vec<Device>,
}

/// `GET /me/devices` — every paired device (token) on this account.
pub async fn devices(
    State(state): State<AppState>,
    uc: UserContext,
    device: ApiDevice,
) -> ApiResult<Json<Devices>> {
    let tokens = auth::list_api_tokens(state.db.as_ref(), uc.user.id).await?;
    Ok(Json(Devices {
        devices: tokens
            .into_iter()
            .map(|t| Device {
                current: t.id == device.token_id,
                id: t.id,
                label: t.label,
                created_at: utc(t.created_at),
                last_used_at: t.last_used_at.map(utc),
                expires_at: t.expires_at.map(utc),
            })
            .collect(),
    }))
}

/// `DELETE /me/devices/{id}` — revoke a device. Its next request is a 401.
pub async fn revoke_device(
    State(state): State<AppState>,
    uc: UserContext,
    ApiPath(id): ApiPath<Uuid>,
) -> ApiResult<StatusCode> {
    match auth::delete_api_token(state.db.as_ref(), uc.user.id, id).await? {
        0 => Err(ApiError::not_found("No such device.")),
        _ => Ok(StatusCode::NO_CONTENT),
    }
}

/// `DELETE /sessions/current` — unpair this device: its own token goes.
pub async fn sign_out(
    State(state): State<AppState>,
    uc: UserContext,
    device: ApiDevice,
) -> ApiResult<StatusCode> {
    auth::delete_api_token(state.db.as_ref(), uc.user.id, device.token_id).await?;
    Ok(StatusCode::NO_CONTENT)
}