Add set group image endpoint

This commit is contained in:
Niels Andriesse 2021-04-23 11:16:31 +10:00
parent 6b6f5be366
commit 9c50877110
2 changed files with 67 additions and 0 deletions

View File

@ -250,6 +250,51 @@ pub async fn get_group_image(room_id: &str) -> Result<Response, Rejection> {
return Ok(warp::reply::json(&json).into_response());
}
pub async fn set_group_image(
base64_encoded_bytes: &str, room_id: &str, auth_token: &str,
pool: &storage::DatabaseConnectionPool,
) -> Result<Response, Rejection> {
// Check authorization level
let (has_authorization_level, _) =
has_authorization_level(auth_token, AuthorizationLevel::Moderator, pool)?;
if !has_authorization_level {
return Err(warp::reject::custom(Error::Unauthorized));
}
// Parse bytes
let bytes = match base64::decode(base64_encoded_bytes) {
Ok(bytes) => bytes,
Err(e) => {
error!("Couldn't parse bytes from invalid base64 encoding due to error: {}.", e);
return Err(warp::reject::custom(Error::ValidationFailed));
}
};
// Write to file
let raw_path = format!("files/{}", room_id);
let path = Path::new(&raw_path);
let mut file = match File::create(path).await {
Ok(file) => file,
Err(e) => {
error!("Couldn't set group image due to error: {}.", e);
return Err(warp::reject::custom(Error::DatabaseFailedInternally));
}
};
match file.write_all(&bytes).await {
Ok(_) => (),
Err(e) => {
error!("Couldn't set group image due to error: {}.", e);
return Err(warp::reject::custom(Error::DatabaseFailedInternally));
}
};
// Return
#[derive(Debug, Deserialize, Serialize)]
struct Response {
status_code: u16,
room_id: String,
}
let response = Response { status_code: StatusCode::OK.as_u16(), room_id: room_id.to_string() };
return Ok(warp::reply::json(&response).into_response());
}
// Authentication
pub fn get_auth_token_challenge(

View File

@ -191,6 +191,28 @@ async fn handle_post_request(
let auth_token = auth_token.ok_or(warp::reject::custom(Error::NoAuthToken))?;
let pool = get_pool_for_room(&rpc_call)?;
// Switch on the path
if path.starts_with("rooms") {
reject_if_file_server_mode(path)?;
let components: Vec<&str> = path.split("/").collect(); // Split on subsequent slashes
if components.len() == 3 && components[2] == "image" {
#[derive(Debug, Deserialize)]
struct JSON {
file: String,
}
let json: JSON = match serde_json::from_str(&rpc_call.body) {
Ok(message) => message,
Err(e) => {
warn!("Couldn't parse JSON from: {} due to error: {}.", rpc_call.body, e);
return Err(warp::reject::custom(Error::InvalidRpcCall));
}
};
let room_id = components[1];
return handlers::set_group_image(&json.file, &room_id, &auth_token, &pool).await;
} else {
warn!("Invalid endpoint: {}.", rpc_call.endpoint);
return Err(warp::reject::custom(Error::InvalidRpcCall));
}
}
match path {
"messages" => {
reject_if_file_server_mode(path)?;