BasicOIDC/src/controllers/login_controller.rs

190 lines
5.7 KiB
Rust
Raw Normal View History

2022-03-30 10:41:22 +00:00
use actix::Addr;
2022-03-30 14:58:00 +00:00
use actix_identity::Identity;
2022-04-05 15:23:26 +00:00
use actix_web::{HttpResponse, Responder, web};
2022-03-30 08:29:10 +00:00
use askama::Template;
use crate::actors::{bruteforce_actor, users_actor};
use crate::actors::bruteforce_actor::BruteForceActor;
2022-04-03 13:50:49 +00:00
use crate::actors::users_actor::{ChangePasswordResult, LoginResult, UsersActor};
use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS, MIN_PASS_LEN};
use crate::controllers::base_controller::{FatalErrorPage, redirect_user};
2022-04-05 15:23:26 +00:00
use crate::data::remote_ip::RemoteIP;
2022-04-02 06:30:01 +00:00
use crate::data::session_identity::{SessionIdentity, SessionStatus};
2022-03-30 08:29:10 +00:00
2022-03-30 09:00:20 +00:00
#[derive(Template)]
#[template(path = "login/base_login_page.html")]
2022-03-30 09:00:20 +00:00
struct BaseLoginPage {
danger: String,
success: String,
page_title: &'static str,
app_name: &'static str,
2022-04-02 17:44:13 +00:00
redirect_uri: String,
2022-03-30 09:00:20 +00:00
}
2022-03-30 08:29:10 +00:00
#[derive(Template)]
#[template(path = "login/login.html")]
2022-03-30 09:00:20 +00:00
struct LoginTemplate {
_parent: BaseLoginPage,
2022-03-30 10:41:22 +00:00
login: String,
2022-03-30 08:29:10 +00:00
}
2022-04-02 06:30:01 +00:00
#[derive(Template)]
#[template(path = "login/password_reset.html")]
2022-04-02 06:30:01 +00:00
struct PasswordResetTemplate {
_parent: BaseLoginPage,
min_pass_len: usize,
}
2022-03-30 10:41:22 +00:00
#[derive(serde::Deserialize)]
2022-04-01 17:05:40 +00:00
pub struct LoginRequestBody {
2022-03-30 10:41:22 +00:00
login: String,
password: String,
}
2022-04-01 17:05:40 +00:00
#[derive(serde::Deserialize)]
pub struct LoginRequestQuery {
logout: Option<bool>,
2022-04-02 17:44:13 +00:00
redirect: Option<String>,
2022-04-01 17:05:40 +00:00
}
2022-03-30 10:41:22 +00:00
/// Authenticate user
2022-04-03 13:50:49 +00:00
pub async fn login_route(
2022-04-05 15:23:26 +00:00
remote_ip: RemoteIP,
2022-04-03 13:50:49 +00:00
users: web::Data<Addr<UsersActor>>,
bruteforce: web::Data<Addr<BruteForceActor>>,
2022-04-03 13:50:49 +00:00
query: web::Query<LoginRequestQuery>,
req: Option<web::Form<LoginRequestBody>>,
id: Identity,
) -> impl Responder {
2022-03-30 10:41:22 +00:00
let mut danger = String::new();
2022-04-01 17:05:40 +00:00
let mut success = String::new();
2022-03-30 10:41:22 +00:00
let mut login = String::new();
2022-04-05 15:23:26 +00:00
let failed_attempts = bruteforce.send(bruteforce_actor::CountFailedAttempt { ip: remote_ip.into() })
.await.unwrap();
if failed_attempts > MAX_FAILED_LOGIN_ATTEMPTS {
2022-04-03 15:48:55 +00:00
return HttpResponse::TooManyRequests().body(
FatalErrorPage {
message: "Too many failed login attempts, please try again later!"
}.render().unwrap()
);
}
2022-04-02 17:44:13 +00:00
let redirect_uri = match query.redirect.as_deref() {
None => "/",
Some(s) => match s.starts_with('/') && !s.starts_with("//") {
true => s,
false => "/",
2022-04-03 13:50:49 +00:00
},
2022-04-02 17:44:13 +00:00
};
2022-04-01 17:05:40 +00:00
// Check if user session must be closed
if let Some(true) = query.logout {
id.forget();
success = "Goodbye!".to_string();
}
2022-04-01 16:59:17 +00:00
// Check if user is already authenticated
2022-04-01 20:51:33 +00:00
if SessionIdentity(&id).is_authenticated() {
2022-04-02 17:44:13 +00:00
return redirect_user(redirect_uri);
2022-04-01 16:59:17 +00:00
}
2022-04-02 06:30:01 +00:00
// Check if user is setting a new password
if let (Some(req), true) = (&req, SessionIdentity(&id).need_new_password()) {
if req.password.len() < MIN_PASS_LEN {
danger = "Password is too short!".to_string();
} else {
2022-04-03 13:50:49 +00:00
let res: ChangePasswordResult = users
.send(users_actor::ChangePasswordRequest {
user_id: SessionIdentity(&id).user_id(),
new_password: req.password.clone(),
temporary: false,
})
.await
.unwrap();
2022-04-02 06:30:01 +00:00
if !res.0 {
danger = "Failed to change password!".to_string();
} else {
SessionIdentity(&id).set_status(SessionStatus::SignedIn);
2022-04-02 17:44:13 +00:00
return redirect_user(redirect_uri);
2022-04-02 06:30:01 +00:00
}
}
}
2022-03-30 10:41:22 +00:00
// Try to authenticate user
2022-04-02 06:30:01 +00:00
else if let Some(req) = &req {
2022-03-30 10:41:22 +00:00
login = req.login.clone();
2022-04-03 13:50:49 +00:00
let response: LoginResult = users
.send(users_actor::LoginRequest {
login: login.clone(),
password: req.password.clone(),
})
.await
.unwrap();
2022-03-30 10:41:22 +00:00
2022-04-01 16:59:17 +00:00
match response {
LoginResult::Success(user) => {
2022-04-01 20:51:33 +00:00
SessionIdentity(&id).set_user(&user);
2022-04-01 16:59:17 +00:00
2022-04-02 06:30:01 +00:00
if user.need_reset_password {
SessionIdentity(&id).set_status(SessionStatus::NeedNewPassword);
} else {
2022-04-02 17:44:13 +00:00
return redirect_user(redirect_uri);
2022-04-02 06:30:01 +00:00
}
2022-04-01 16:59:17 +00:00
}
2022-04-03 12:42:16 +00:00
LoginResult::AccountDisabled => {
log::warn!("Failed login for username {} : account is disabled", login);
danger = "Your account is disabled!".to_string();
}
2022-04-01 16:59:17 +00:00
c => {
log::warn!("Failed login for ip {:?} / username {}: {:?}", remote_ip, login, c);
2022-04-01 16:59:17 +00:00
danger = "Login failed.".to_string();
2022-04-05 15:23:26 +00:00
bruteforce.send(bruteforce_actor::RecordFailedAttempt { ip: remote_ip.into() }).await.unwrap();
2022-04-01 16:59:17 +00:00
}
}
2022-03-30 10:41:22 +00:00
}
2022-04-02 06:30:01 +00:00
// Display password reset form if it is appropriate
if SessionIdentity(&id).need_new_password() {
2022-04-03 13:50:49 +00:00
return HttpResponse::Ok().content_type("text/html").body(
PasswordResetTemplate {
2022-04-02 06:30:01 +00:00
_parent: BaseLoginPage {
page_title: "Password reset",
danger,
success,
app_name: APP_NAME,
2022-04-02 17:44:13 +00:00
redirect_uri: urlencoding::encode(redirect_uri).to_string(),
2022-04-02 06:30:01 +00:00
},
min_pass_len: MIN_PASS_LEN,
2022-04-03 13:50:49 +00:00
}
.render()
.unwrap(),
2022-04-03 13:50:49 +00:00
);
2022-04-02 06:30:01 +00:00
}
2022-04-03 13:50:49 +00:00
HttpResponse::Ok().content_type("text/html").body(
LoginTemplate {
2022-03-30 09:00:20 +00:00
_parent: BaseLoginPage {
page_title: "Login",
2022-03-30 10:41:22 +00:00
danger,
2022-04-01 17:05:40 +00:00
success,
2022-03-30 09:00:20 +00:00
app_name: APP_NAME,
2022-04-02 17:44:13 +00:00
redirect_uri: urlencoding::encode(redirect_uri).to_string(),
2022-03-30 09:00:20 +00:00
},
2022-03-30 10:41:22 +00:00
login,
2022-04-03 13:50:49 +00:00
}
.render()
.unwrap(),
2022-04-03 13:50:49 +00:00
)
2022-04-01 17:05:40 +00:00
}
/// Sign out user
pub async fn logout_route() -> impl Responder {
redirect_user("/login?logout=true")
2022-04-03 13:50:49 +00:00
}