feat: Implement WebFinger discovery and ActivityPub user actor endpoint
- Added a new router for handling well-known endpoints, specifically WebFinger. - Implemented the `webfinger` function to respond to WebFinger queries. - Created a new route for WebFinger in the router. - Refactored user retrieval logic to support both user ID and username in a single endpoint. - Updated user router to use the new `get_user_by_param` function. - Added tests for WebFinger discovery and ActivityPub user actor endpoint. - Updated dependencies in Cargo.toml files to include necessary libraries.
This commit is contained in:
@@ -5,8 +5,9 @@ pub mod feed;
|
||||
pub mod root;
|
||||
pub mod thought;
|
||||
pub mod user;
|
||||
pub mod well_known;
|
||||
|
||||
use crate::routers::auth::create_auth_router;
|
||||
use crate::routers::{auth::create_auth_router, well_known::create_well_known_router};
|
||||
use app::state::AppState;
|
||||
use root::create_root_router;
|
||||
use tower_http::cors::CorsLayer;
|
||||
@@ -19,6 +20,7 @@ pub fn create_router(state: AppState) -> Router {
|
||||
|
||||
Router::new()
|
||||
.merge(create_root_router())
|
||||
.nest("/.well-known", create_well_known_router())
|
||||
.nest("/auth", create_auth_router())
|
||||
.nest("/users", create_user_router())
|
||||
.nest("/thoughts", create_thought_router())
|
||||
|
@@ -1,10 +1,11 @@
|
||||
use axum::{
|
||||
extract::{Path, Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
use app::persistence::{
|
||||
follow,
|
||||
@@ -44,28 +45,6 @@ async fn users_get(
|
||||
Ok(Json(UserListSchema::from(users)))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/{id}",
|
||||
params(
|
||||
("id" = i32, Path, description = "User id")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get user", body = UserSchema),
|
||||
(status = 404, description = "Not found", body = ApiErrorResponse),
|
||||
(status = 500, description = "Internal server error", body = ApiErrorResponse),
|
||||
)
|
||||
)]
|
||||
async fn users_id_get(
|
||||
state: State<AppState>,
|
||||
Path(id): Path<i32>,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
let user = get_user(&state.conn, id).await.map_err(ApiError::from)?;
|
||||
|
||||
user.map(|user| Json(UserSchema::from(user)))
|
||||
.ok_or_else(|| UserError::NotFound.into())
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/{username}/thoughts",
|
||||
@@ -165,10 +144,84 @@ async fn user_follow_delete(
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/{param}",
|
||||
params(
|
||||
("param" = String, Path, description = "User ID or username")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "User profile or ActivityPub actor", body = UserSchema, content_type = "application/json"),
|
||||
(status = 200, description = "ActivityPub actor", body = Object, content_type = "application/activity+json"),
|
||||
(status = 404, description = "User not found", body = ApiErrorResponse),
|
||||
(status = 500, description = "Internal server error", body = ApiErrorResponse),
|
||||
),
|
||||
security(
|
||||
("api_key" = []),
|
||||
("bearer_auth" = [])
|
||||
)
|
||||
)]
|
||||
async fn get_user_by_param(
|
||||
State(state): State<AppState>,
|
||||
headers: axum::http::HeaderMap,
|
||||
Path(param): Path<String>,
|
||||
) -> Response {
|
||||
// First, try to handle it as a numeric ID.
|
||||
if let Ok(id) = param.parse::<i32>() {
|
||||
return match get_user(&state.conn, id).await {
|
||||
Ok(Some(user)) => Json(UserSchema::from(user)).into_response(),
|
||||
Ok(None) => ApiError::from(UserError::NotFound).into_response(),
|
||||
Err(db_err) => ApiError::from(db_err).into_response(),
|
||||
};
|
||||
}
|
||||
|
||||
// If it's not a number, treat it as a username and perform content negotiation.
|
||||
let username = param;
|
||||
let is_activitypub_request = headers
|
||||
.get(axum::http::header::ACCEPT)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map_or(false, |s| s.contains("application/activity+json"));
|
||||
|
||||
if is_activitypub_request {
|
||||
// This is the logic from `user_actor_get`.
|
||||
match get_user_by_username(&state.conn, &username).await {
|
||||
Ok(Some(user)) => {
|
||||
let base_url = "http://localhost:3000";
|
||||
let user_url = format!("{}/users/{}", base_url, user.username);
|
||||
let actor = json!({
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
"https://w3id.org/security/v1"
|
||||
],
|
||||
"id": user_url,
|
||||
"type": "Person",
|
||||
"preferredUsername": user.username,
|
||||
"inbox": format!("{}/inbox", user_url),
|
||||
"outbox": format!("{}/outbox", user_url),
|
||||
});
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"application/activity+json".parse().unwrap(),
|
||||
);
|
||||
(headers, Json(actor)).into_response()
|
||||
}
|
||||
Ok(None) => ApiError::from(UserError::NotFound).into_response(),
|
||||
Err(e) => ApiError::from(e).into_response(),
|
||||
}
|
||||
} else {
|
||||
match get_user_by_username(&state.conn, &username).await {
|
||||
Ok(Some(user)) => Json(UserSchema::from(user)).into_response(),
|
||||
Ok(None) => ApiError::from(UserError::NotFound).into_response(),
|
||||
Err(e) => ApiError::from(e).into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_user_router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/", get(users_get))
|
||||
.route("/{id}", get(users_id_get))
|
||||
.route("/{param}", get(get_user_by_param))
|
||||
.route("/{username}/thoughts", get(user_thoughts_get))
|
||||
.route(
|
||||
"/{username}/follow",
|
||||
|
71
thoughts-backend/api/src/routers/well_known.rs
Normal file
71
thoughts-backend/api/src/routers/well_known.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use app::state::AppState;
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
response::{IntoResponse, Json},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct WebFingerQuery {
|
||||
resource: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct WebFingerLink {
|
||||
rel: String,
|
||||
#[serde(rename = "type")]
|
||||
type_: String,
|
||||
href: Url,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct WebFingerResponse {
|
||||
subject: String,
|
||||
links: Vec<WebFingerLink>,
|
||||
}
|
||||
|
||||
pub async fn webfinger(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<WebFingerQuery>,
|
||||
) -> Result<impl IntoResponse, impl IntoResponse> {
|
||||
if let Some((scheme, account_info)) = query.resource.split_once(':') {
|
||||
if scheme != "acct" {
|
||||
return Err((
|
||||
axum::http::StatusCode::BAD_REQUEST,
|
||||
"Invalid resource scheme",
|
||||
));
|
||||
}
|
||||
|
||||
let account_parts: Vec<&str> = account_info.split('@').collect();
|
||||
let username = account_parts[0];
|
||||
|
||||
let user = match app::persistence::user::get_user_by_username(&state.conn, username).await {
|
||||
Ok(Some(user)) => user,
|
||||
_ => return Err((axum::http::StatusCode::NOT_FOUND, "User not found")),
|
||||
};
|
||||
|
||||
let base_url = "http://localhost:3000";
|
||||
let user_url = Url::parse(&format!("{}/users/{}", base_url, user.username)).unwrap();
|
||||
|
||||
let response = WebFingerResponse {
|
||||
subject: query.resource,
|
||||
links: vec![WebFingerLink {
|
||||
rel: "self".to_string(),
|
||||
type_: "application/activity+json".to_string(),
|
||||
href: user_url,
|
||||
}],
|
||||
};
|
||||
|
||||
Ok(Json(response))
|
||||
} else {
|
||||
Err((
|
||||
axum::http::StatusCode::BAD_REQUEST,
|
||||
"Invalid resource format",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_well_known_router() -> axum::Router<AppState> {
|
||||
axum::Router::new().route("/webfinger", axum::routing::get(webfinger))
|
||||
}
|
Reference in New Issue
Block a user