fix(handlers): add handlers
This commit is contained in:
@@ -1,69 +1,11 @@
|
||||
use crate::models::{CreateUserRequest, User}; // 假设你在 models 定义了这些
|
||||
use crate::utils::{create_jwt, hash_password, verify_password};
|
||||
use axum::Json;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
pub mod auth;
|
||||
pub mod authorization;
|
||||
pub mod role;
|
||||
pub mod tenant;
|
||||
pub mod user;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AuthService {
|
||||
pool: PgPool,
|
||||
jwt_secret: String,
|
||||
}
|
||||
|
||||
impl AuthService {
|
||||
pub fn new(pool: PgPool, jwt_secret: String) -> Self {
|
||||
Self { pool, jwt_secret }
|
||||
}
|
||||
|
||||
// 注册业务
|
||||
pub async fn register(
|
||||
&self,
|
||||
tenant_id: Uuid,
|
||||
req: CreateUserRequest,
|
||||
) -> Result<Json<User>, String> {
|
||||
// 1. 哈希密码
|
||||
let hashed = hash_password(&req.password)?;
|
||||
|
||||
// 2. 存入数据库 (带上 tenant_id)
|
||||
let query = r#"
|
||||
INSERT INTO users (tenant_id, email, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, tenant_id, email, password_hash, created_at
|
||||
"#;
|
||||
let user = sqlx::query_as::<_, User>(query)
|
||||
.bind(tenant_id)
|
||||
.bind(&req.email)
|
||||
.bind(&hashed)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(Json(user))
|
||||
}
|
||||
|
||||
// 登录业务
|
||||
pub async fn login(
|
||||
&self,
|
||||
tenant_id: Uuid,
|
||||
email: &str,
|
||||
password: &str,
|
||||
) -> Result<String, String> {
|
||||
// 1. 查找用户 (带 tenant_id 防止跨租户登录)
|
||||
let query = "SELECT * FROM users WHERE tenant_id = $1 AND email = $2";
|
||||
let user = sqlx::query_as::<_, User>(query)
|
||||
.bind(tenant_id)
|
||||
.bind(email)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
.ok_or("User not found")?;
|
||||
|
||||
// 2. 验证密码
|
||||
if !verify_password(password, &user.password_hash) {
|
||||
return Err("Invalid password".to_string());
|
||||
}
|
||||
|
||||
// 3. 签发 Token
|
||||
create_jwt(user.id, user.tenant_id, &self.jwt_secret)
|
||||
}
|
||||
}
|
||||
pub use auth::AuthService;
|
||||
pub use authorization::AuthorizationService;
|
||||
pub use role::RoleService;
|
||||
pub use tenant::TenantService;
|
||||
pub use user::UserService;
|
||||
|
||||
Reference in New Issue
Block a user