test
This commit is contained in:
253
Cargo.lock
generated
253
Cargo.lock
generated
@ -83,6 +83,7 @@ dependencies = [
|
||||
"axum",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"jsonwebtoken",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
@ -92,6 +93,12 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
@ -146,6 +153,12 @@ version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
@ -162,7 +175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -219,6 +232,19 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
@ -351,6 +377,21 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonwebtoken"
|
||||
version = "9.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"js-sys",
|
||||
"pem",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simple_asn1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
@ -410,7 +451,7 @@ checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -436,7 +477,32 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -477,6 +543,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@ -489,6 +565,12 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@ -522,6 +604,20 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
@ -532,7 +628,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -644,6 +740,18 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simple_asn1"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"thiserror",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
@ -663,7 +771,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -707,10 +815,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -722,6 +850,36 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.53.1"
|
||||
@ -736,7 +894,7 @@ dependencies = [
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -858,6 +1016,12 @@ version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "valuable"
|
||||
version = "0.1.1"
|
||||
@ -980,6 +1144,15 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
@ -989,6 +1162,70 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "backend-local"
|
||||
name = "unitprint-backend"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
@ -14,6 +14,7 @@ serde_json = "1"
|
||||
bytes = "1"
|
||||
tracing = "0.1"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
jsonwebtoken = "9"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@ -3,6 +3,9 @@ mod general;
|
||||
#[cfg(local)]
|
||||
mod local;
|
||||
|
||||
#[cfg(not(local))]
|
||||
mod server;
|
||||
|
||||
use axum::{
|
||||
extract::DefaultBodyLimit,
|
||||
routing::get,
|
||||
@ -28,6 +31,9 @@ async fn main() {
|
||||
#[cfg(local)]
|
||||
let app = app.merge(local::routes());
|
||||
|
||||
#[cfg(not(local))]
|
||||
let app = app.merge(server::routes());
|
||||
|
||||
let app = app
|
||||
.layer(DefaultBodyLimit::max(50 * 1024 * 1024))
|
||||
.layer(CorsLayer::permissive());
|
||||
|
||||
173
src/server/auth/handlers.rs
Normal file
173
src/server/auth/handlers.rs
Normal file
@ -0,0 +1,173 @@
|
||||
// src/server/auth/handlers.rs
|
||||
use super::models::*;
|
||||
use super::otp;
|
||||
use super::token;
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{HeaderMap, StatusCode},
|
||||
Json,
|
||||
};
|
||||
|
||||
/// POST /auth/send-otp
|
||||
pub async fn send_otp(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<SendOtpRequest>,
|
||||
) -> Result<Json<SendOtpResponse>, (StatusCode, String)> {
|
||||
// 1. Нормализация номера
|
||||
let phone = otp::normalize_phone(&req.phone)
|
||||
.map_err(|e| (StatusCode::BAD_REQUEST, e))?;
|
||||
|
||||
// 2. Rate-limit + cleanup под мьютексом
|
||||
{
|
||||
let mut otps = state.otps.lock().unwrap();
|
||||
otp::cleanup_expired(&mut otps);
|
||||
|
||||
if let Some(entry) = otps.get(&phone) {
|
||||
let elapsed = chrono::Utc::now()
|
||||
.signed_duration_since(entry.created_at)
|
||||
.num_seconds();
|
||||
if elapsed < OTP_COOLDOWN_SECS {
|
||||
let wait = OTP_COOLDOWN_SECS - elapsed;
|
||||
return Err((
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
format!("Повторная отправка через {} сек", wait),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Отправка SMS (блокирующая операция → spawn_blocking)
|
||||
let phone_clone = phone.clone();
|
||||
let sms_result = tokio::task::spawn_blocking(move || {
|
||||
otp::send_sms_and_get_otp(&phone_clone)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("spawn: {}", e)))?;
|
||||
|
||||
let code = sms_result.map_err(|e| {
|
||||
tracing::error!("SMS error: {}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Не удалось отправить SMS".into())
|
||||
})?;
|
||||
|
||||
// 4. Сохранение OTP
|
||||
{
|
||||
let mut otps = state.otps.lock().unwrap();
|
||||
let now = chrono::Utc::now();
|
||||
otps.insert(
|
||||
phone.clone(),
|
||||
OtpEntry {
|
||||
code,
|
||||
phone: phone.clone(),
|
||||
expires_at: now + chrono::Duration::seconds(OTP_TTL_SECS),
|
||||
attempts: 0,
|
||||
created_at: now,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
tracing::info!("📨 OTP отправлен на {}", phone);
|
||||
|
||||
Ok(Json(SendOtpResponse {
|
||||
success: true,
|
||||
message: "Код отправлен".into(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// POST /auth/verify-otp
|
||||
pub async fn verify_otp(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<VerifyOtpRequest>,
|
||||
) -> Result<Json<VerifyOtpResponse>, (StatusCode, String)> {
|
||||
let phone = otp::normalize_phone(&req.phone)
|
||||
.map_err(|e| (StatusCode::BAD_REQUEST, e))?;
|
||||
|
||||
let code = req.code.trim().to_string();
|
||||
if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
|
||||
return Err((StatusCode::BAD_REQUEST, "Код должен содержать 6 цифр".into()));
|
||||
}
|
||||
|
||||
// 1. Проверка OTP
|
||||
{
|
||||
let mut otps = state.otps.lock().unwrap();
|
||||
let entry = otps
|
||||
.get_mut(&phone)
|
||||
.ok_or_else(|| (StatusCode::NOT_FOUND, "Код не найден. Запросите новый.".into()))?;
|
||||
|
||||
// Просрочен?
|
||||
if chrono::Utc::now() > entry.expires_at {
|
||||
otps.remove(&phone);
|
||||
return Err((StatusCode::GONE, "Код истёк. Запросите новый.".into()));
|
||||
}
|
||||
|
||||
// Превышено число попыток?
|
||||
if entry.attempts >= OTP_MAX_ATTEMPTS {
|
||||
otps.remove(&phone);
|
||||
return Err((
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"Превышено число попыток. Запросите новый код.".into(),
|
||||
));
|
||||
}
|
||||
|
||||
// Неверный код?
|
||||
if entry.code != code {
|
||||
entry.attempts += 1;
|
||||
let left = OTP_MAX_ATTEMPTS - entry.attempts;
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
format!("Неверный код. Осталось попыток: {}", left),
|
||||
));
|
||||
}
|
||||
|
||||
// Успех → удаляем OTP
|
||||
otps.remove(&phone);
|
||||
}
|
||||
|
||||
// 2. Регистрация / вход пользователя
|
||||
{
|
||||
let mut users = state.users.lock().unwrap();
|
||||
users.entry(phone.clone()).or_insert_with(|| User {
|
||||
phone: phone.clone(),
|
||||
registered_at: chrono::Utc::now(),
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Генерация JWT
|
||||
let jwt = token::create_token(&phone)
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
|
||||
|
||||
tracing::info!("✅ Пользователь авторизован: {}", phone);
|
||||
|
||||
Ok(Json(VerifyOtpResponse {
|
||||
success: true,
|
||||
token: jwt,
|
||||
phone,
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /auth/me (защищённый эндпоинт)
|
||||
pub async fn get_me(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<MeResponse>, (StatusCode, String)> {
|
||||
// 1. Извлечение токена из заголовка
|
||||
let token = headers
|
||||
.get("Authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.strip_prefix("Bearer "))
|
||||
.ok_or_else(|| (StatusCode::UNAUTHORIZED, "Нет токена".into()))?;
|
||||
|
||||
// 2. Верификация JWT
|
||||
let claims = token::verify_token(token)
|
||||
.map_err(|_| (StatusCode::UNAUTHORIZED, "Недействительный токен".into()))?;
|
||||
|
||||
// 3. Поиск пользователя
|
||||
let users = state.users.lock().unwrap();
|
||||
let user = users
|
||||
.get(&claims.sub)
|
||||
.ok_or_else(|| (StatusCode::NOT_FOUND, "Пользователь не найден".into()))?;
|
||||
|
||||
Ok(Json(MeResponse {
|
||||
phone: user.phone.clone(),
|
||||
registered_at: user.registered_at.to_rfc3339(),
|
||||
}))
|
||||
}
|
||||
5
src/server/auth/mod.rs
Normal file
5
src/server/auth/mod.rs
Normal file
@ -0,0 +1,5 @@
|
||||
// src/server/auth/mod.rs
|
||||
pub mod handlers;
|
||||
pub mod models;
|
||||
pub mod otp;
|
||||
pub mod token;
|
||||
79
src/server/auth/models.rs
Normal file
79
src/server/auth/models.rs
Normal file
@ -0,0 +1,79 @@
|
||||
// src/server/auth/models.rs
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
/// Запись OTP в хранилище
|
||||
pub struct OtpEntry {
|
||||
pub code: String,
|
||||
pub phone: String,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub attempts: u32,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
/// Пользователь (минимальная модель)
|
||||
#[derive(Clone)]
|
||||
pub struct User {
|
||||
pub phone: String,
|
||||
pub registered_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
/// Общее состояние для auth-роутов
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub otps: Arc<Mutex<HashMap<String, OtpEntry>>>,
|
||||
pub users: Arc<Mutex<HashMap<String, User>>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
otps: Arc::new(Mutex::new(HashMap::new())),
|
||||
users: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Request / Response DTO ───
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SendOtpRequest {
|
||||
pub phone: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SendOtpResponse {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct VerifyOtpRequest {
|
||||
pub phone: String,
|
||||
pub code: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct VerifyOtpResponse {
|
||||
pub success: bool,
|
||||
pub token: String,
|
||||
pub phone: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct MeResponse {
|
||||
pub phone: String,
|
||||
pub registered_at: String,
|
||||
}
|
||||
|
||||
// ─── Константы ───
|
||||
|
||||
pub const OTP_TTL_SECS: i64 = 300; // 5 минут
|
||||
pub const OTP_MAX_ATTEMPTS: u32 = 3;
|
||||
pub const OTP_COOLDOWN_SECS: i64 = 60; // 60 сек между запросами
|
||||
pub const JWT_TTL_DAYS: i64 = 7; // токен на 7 дней
|
||||
pub const SMS_SCRIPT_ENV: &str = "SMS_SCRIPT_PATH";
|
||||
pub const SMS_SCRIPT_DEFAULT: &str = "/pkg/gnu/unitprint/simd/bin/send_sms.sh";
|
||||
75
src/server/auth/otp.rs
Normal file
75
src/server/auth/otp.rs
Normal file
@ -0,0 +1,75 @@
|
||||
// src/server/auth/otp.rs
|
||||
use super::models::*;
|
||||
use std::process::Command;
|
||||
|
||||
/// Нормализация российского номера → +7XXXXXXXXXX
|
||||
pub fn normalize_phone(raw: &str) -> Result<String, String> {
|
||||
let digits: String = raw.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
|
||||
let normalized = match digits.len() {
|
||||
11 if digits.starts_with('7') => format!("+{}", digits),
|
||||
11 if digits.starts_with('8') => format!("+7{}", &digits[1..]),
|
||||
10 => format!("+7{}", digits),
|
||||
_ => return Err("Некорректный номер телефона".into()),
|
||||
};
|
||||
|
||||
if normalized.len() != 12 {
|
||||
return Err("Некорректный номер телефона".into());
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
/// Путь к скрипту отправки SMS
|
||||
fn sms_script_path() -> std::path::PathBuf {
|
||||
let p = std::env::var(SMS_SCRIPT_ENV).unwrap_or_else(|_| SMS_SCRIPT_DEFAULT.into());
|
||||
std::path::PathBuf::from(p)
|
||||
}
|
||||
|
||||
/// Вызывает send_sms.sh и парсит OTP из stdout.
|
||||
///
|
||||
/// Пример строки в выводе: «ТЕКСТ : OTP 019352»
|
||||
pub fn send_sms_and_get_otp(phone: &str) -> Result<String, String> {
|
||||
let script = sms_script_path();
|
||||
if !script.exists() {
|
||||
return Err(format!("Скрипт не найден: {}", script.display()));
|
||||
}
|
||||
|
||||
let output = Command::new(&script)
|
||||
.arg(phone)
|
||||
.env("LC_ALL", "C")
|
||||
.output()
|
||||
.map_err(|e| format!("Не удалось запустить скрипт: {}", e))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(format!("Скрипт завершился с ошибкой: {}", stderr.trim()));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
parse_otp_from_output(&stdout)
|
||||
.ok_or_else(|| "Не удалось извлечь OTP из вывода скрипта".into())
|
||||
}
|
||||
|
||||
/// Парсинг шестизначного кода из строки вида «ТЕКСТ : OTP 019352»
|
||||
fn parse_otp_from_output(output: &str) -> Option<String> {
|
||||
for line in output.lines() {
|
||||
if !line.contains("ТЕКСТ") {
|
||||
continue;
|
||||
}
|
||||
// Ищем подстроку после "OTP"
|
||||
if let Some(pos) = line.find("OTP") {
|
||||
let after = &line[pos + 3..];
|
||||
let digits: String = after.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
if digits.len() == 6 {
|
||||
return Some(digits);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Удаляет просроченные OTP-записи (вызывается под уже захваченным мьютексом)
|
||||
pub fn cleanup_expired(map: &mut std::collections::HashMap<String, OtpEntry>) {
|
||||
let now = chrono::Utc::now();
|
||||
map.retain(|_, entry| entry.expires_at > now);
|
||||
}
|
||||
53
src/server/auth/token.rs
Normal file
53
src/server/auth/token.rs
Normal file
@ -0,0 +1,53 @@
|
||||
// src/server/auth/token.rs
|
||||
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Claims {
|
||||
/// phone number как subject
|
||||
pub sub: String,
|
||||
/// Unix-таймстамп истечения
|
||||
pub exp: usize,
|
||||
/// Unix-таймстамп выдачи
|
||||
pub iat: usize,
|
||||
}
|
||||
|
||||
fn jwt_secret() -> Vec<u8> {
|
||||
std::env::var("JWT_SECRET")
|
||||
.unwrap_or_else(|_| {
|
||||
// ⚠️ Только для разработки! В продакшене ОБЯЗАТЕЛЬНО задать JWT_SECRET
|
||||
"unitprint-dev-secret-change-me-in-production".into()
|
||||
})
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// Создаёт JWT для данного номера телефона
|
||||
pub fn create_token(phone: &str) -> Result<String, String> {
|
||||
let now = chrono::Utc::now();
|
||||
let ttl = super::models::JWT_TTL_DAYS * 24 * 3600;
|
||||
|
||||
let claims = Claims {
|
||||
sub: phone.to_string(),
|
||||
iat: now.timestamp() as usize,
|
||||
exp: (now.timestamp() + ttl) as usize,
|
||||
};
|
||||
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claims,
|
||||
&EncodingKey::from_secret(&jwt_secret()),
|
||||
)
|
||||
.map_err(|e| format!("JWT encode: {}", e))
|
||||
}
|
||||
|
||||
/// Проверяет JWT и возвращает Claims
|
||||
pub fn verify_token(token: &str) -> Result<Claims, String> {
|
||||
let data = decode::<Claims>(
|
||||
token,
|
||||
&DecodingKey::from_secret(&jwt_secret()),
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|e| format!("JWT verify: {}", e))?;
|
||||
|
||||
Ok(data.claims)
|
||||
}
|
||||
19
src/server/mod.rs
Normal file
19
src/server/mod.rs
Normal file
@ -0,0 +1,19 @@
|
||||
// src/server/mod.rs
|
||||
pub mod auth;
|
||||
|
||||
use axum::{
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
|
||||
use self::auth::{handlers, models::AppState};
|
||||
|
||||
pub fn routes() -> Router {
|
||||
let state = AppState::new();
|
||||
|
||||
Router::new()
|
||||
.route("/auth/send-otp", post(handlers::send_otp))
|
||||
.route("/auth/verify-otp", post(handlers::verify_otp))
|
||||
.route("/auth/me", get(handlers::get_me))
|
||||
.with_state(state)
|
||||
}
|
||||
Reference in New Issue
Block a user