Skip to content

Commit

Permalink
⚡️ Limit the frequency of login actions.
Browse files Browse the repository at this point in the history
  • Loading branch information
langyo committed Mar 31, 2024
1 parent a279e11 commit 4642726
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion packages/server/src/routes/backend/auth/login.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use anyhow::Result;
use std::net::SocketAddr;
use chrono::{DateTime, Utc};
use once_cell::sync::Lazy;
use std::{
net::SocketAddr,
sync::{Arc, Mutex},
};

use axum::{
extract::{ConnectInfo, Json},
Expand All @@ -9,12 +14,58 @@ use hyper::{HeaderMap, StatusCode};

use _database::{functions::frontend::auth::login as do_login, types::request::LoginInfo};

static LOGIN_LOG: Lazy<Arc<Mutex<Vec<(SocketAddr, DateTime<Utc>)>>>> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));

#[tracing::instrument]
pub async fn login(
headers: HeaderMap,
ConnectInfo(real_ip): ConnectInfo<SocketAddr>,
args: Json<LoginInfo>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
// Write the login log
let now = Utc::now();
LOGIN_LOG
.lock()
.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Cannot lock login log: {}", err),
)
})?
.push((real_ip, now));

// Clear the login log that is older than 1 minute
LOGIN_LOG
.lock()
.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Cannot lock login log: {}", err),
)
})?
.retain(|(_, time)| now.signed_duration_since(*time).num_seconds() < 60);

// Check if the user is trying to login too frequently
// Limit to 5 times per minute
let count = LOGIN_LOG
.lock()
.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Cannot lock login log: {}", err),
)
})?
.iter()
.filter(|(ip, time)| ip == &real_ip && now.signed_duration_since(*time).num_seconds() < 60)
.count();
if count > 5 {
return Err((
StatusCode::TOO_MANY_REQUESTS,
"Too many requests".to_string(),
));
}

let ret = do_login(args.name.clone(), args.password_raw.clone())
.await
.map_err(|err| {
Expand Down

0 comments on commit 4642726

Please sign in to comment.