Files
Genarrative/server-rs/crates/api-server/src/profile_identity.rs
T
k88936 44748b7846
Project CI / Frontend tests (push) Successful in 34s
Project CI / Backend tests (push) Failing after 39s
Project CI / Repository checks (push) Successful in 52s
Project CI / Native shell tests (push) Successful in 2m4s
fix:前后端校验手机号区域码 (#104)
来自今早群友反映
before:
![shotmd-1784692399.jpg](/attachments/3ab36252-78f4-44e2-bb51-fca84badc79e)
and failed
after:
![shotmd-1784702966.jpg](/attachments/3eea7ec9-8aca-43f6-a675-1316162619d4)
![shotmd-1784702843.jpg](/attachments/29182a41-26cf-4954-be16-de060d844d9c)
![shotmd-1784787134.jpg](/attachments/c04a1981-c6bf-4a26-b5ad-d2af51d74a29)

* https://developers.weixin.qq.com/miniprogram/dev/server/API/user-info/phone-number/api_getphonenumber.html#Res-phone-info-Object-Payload 参考微信这个文档修改了微信返回的struct 手机号 区域码字段不应是Optional

* 登录注册改密码改绑定等 api 把单一 phone字段改成 country_code(可选,缺省为86) + pure_phone_number 分别进行了前后端校验

Reviewed-on: https://git.genarrative.world/git/GenarrativeAI/Genarrative/pulls/104
Co-authored-by: 王德宇 <kvtodev@outlook.com>
Co-committed-by: 王德宇 <kvtodev@outlook.com>
2026-07-23 14:52:57 +08:00

107 lines
3.9 KiB
Rust

use axum::{
Json,
extract::{Extension, State},
http::StatusCode,
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use image::GenericImageView;
use module_auth::{PasswordEntryError, UpdateProfileInput};
use shared_contracts::auth::{ProfileUpdateRequest, ProfileUpdateResponse};
use crate::{
api_response::json_success_body, auth::AuthenticatedAccessToken,
auth_payload::map_auth_user_payload, http_error::AppError, request_context::RequestContext,
state::AppState,
};
const MAX_AVATAR_BYTES: usize = 5 * 1024 * 1024;
const AVATAR_SIZE_PX: u32 = 256;
pub async fn update_profile_identity(
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Extension(authenticated): Extension<AuthenticatedAccessToken>,
Json(payload): Json<ProfileUpdateRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
if let Some(avatar_data_url) = payload.avatar_data_url.as_deref() {
validate_avatar_data_url(avatar_data_url)?;
}
let result = state
.password_entry_service()
.update_profile(UpdateProfileInput {
user_id: authenticated.claims().user_id().to_string(),
display_name: payload.display_name,
avatar_url: payload.avatar_data_url,
})
.map_err(map_profile_update_error)?;
state
.sync_auth_store_tables_to_spacetime()
.await
.map_err(|error| {
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_message(error.to_string())
})?;
Ok(json_success_body(
Some(&request_context),
ProfileUpdateResponse {
user: map_auth_user_payload(result.user),
},
))
}
fn validate_avatar_data_url(value: &str) -> Result<(), AppError> {
let Some((header, payload)) = value.trim().split_once(',') else {
return Err(invalid_avatar_error("头像图片格式不正确"));
};
if !matches!(
header,
"data:image/png;base64" | "data:image/jpeg;base64" | "data:image/webp;base64"
) {
return Err(invalid_avatar_error("头像仅支持 jpg、png、webp"));
}
let bytes = BASE64_STANDARD
.decode(payload)
.map_err(|_| invalid_avatar_error("头像图片格式不正确"))?;
if bytes.len() > MAX_AVATAR_BYTES {
return Err(invalid_avatar_error("头像图片不能超过 5MB"));
}
let image =
image::load_from_memory(&bytes).map_err(|_| invalid_avatar_error("头像图片格式不正确"))?;
let (width, height) = image.dimensions();
if width != AVATAR_SIZE_PX || height != AVATAR_SIZE_PX {
return Err(invalid_avatar_error("头像裁剪尺寸需要为 256x256"));
}
Ok(())
}
fn invalid_avatar_error(message: &'static str) -> AppError {
AppError::from_status(StatusCode::BAD_REQUEST).with_message(message)
}
fn map_profile_update_error(error: PasswordEntryError) -> AppError {
match error {
PasswordEntryError::InvalidDisplayName
| PasswordEntryError::InvalidAvatarDataUrl
| PasswordEntryError::EmptyProfileUpdate => {
AppError::from_status(StatusCode::BAD_REQUEST).with_message(error.to_string())
}
PasswordEntryError::UserNotFound => AppError::from_status(StatusCode::UNAUTHORIZED)
.with_message("当前登录态已失效,请重新登录"),
PasswordEntryError::Store(_) | PasswordEntryError::PasswordHash(_) => {
AppError::from_status(StatusCode::INTERNAL_SERVER_ERROR).with_message(error.to_string())
}
PasswordEntryError::InvalidPhoneNumber
| PasswordEntryError::UnsupportedPhoneCountryCode
| PasswordEntryError::InvalidPasswordLength
| PasswordEntryError::InvalidPublicUserCode
| PasswordEntryError::InvalidCredentials => {
AppError::from_status(StatusCode::BAD_REQUEST).with_message(error.to_string())
}
}
}