diff options
author | Joris | 2021-01-03 13:40:40 +0100 |
---|---|---|
committer | Joris | 2021-01-03 13:54:20 +0100 |
commit | 11052951b74b9ad4b6a9412ae490086235f9154b (patch) | |
tree | 64526ac926c1bf470ea113f6cac8a33158684e8d /src/controller/login.rs | |
parent | 371449b0e312a03162b78797b83dee9d81706669 (diff) |
Rewrite in Rust
Diffstat (limited to 'src/controller/login.rs')
-rw-r--r-- | src/controller/login.rs | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/src/controller/login.rs b/src/controller/login.rs new file mode 100644 index 0000000..ea9db57 --- /dev/null +++ b/src/controller/login.rs @@ -0,0 +1,86 @@ +use bcrypt; +use hyper::{Body, Response}; +use sqlx::sqlite::SqlitePool; +use std::collections::HashMap; +use tera::{Context, Tera}; +use uuid::Uuid; + +use crate::controller::wallet::Wallet; +use crate::controller::{error, utils}; +use crate::db; +use crate::model::config::Config; +use crate::model::user::User; +use crate::validation; + +pub async fn page( + assets: &HashMap<String, String>, + templates: &Tera, + error: Option<String>, +) -> Response<Body> { + let connected_user: Option<User> = None; + + let mut context = Context::new(); + context.insert("connected_user", &connected_user); + context.insert("error", &error); + + utils::template(assets, templates, "login.html", context) +} + +pub async fn login( + config: Config, + assets: &HashMap<String, String>, + templates: &Tera, + form: HashMap<String, String>, + pool: SqlitePool, +) -> Response<Body> { + let not_authorized = page( + assets, + templates, + Some("Vous n’êtes pas autorisé à vous connecter.".to_string()), + ) + .await; + let server_error = + page(assets, templates, Some("Erreur serveur.".to_string())).await; + match validation::login::login(&form) { + Some(login) => { + match db::users::get_password_hash(&pool, login.email.clone()).await + { + Some(hash) => match bcrypt::verify(login.password, &hash) { + Ok(true) => { + let login_token = Uuid::new_v4(); + if db::users::set_login_token( + &pool, + login.email, + login_token.clone().to_string(), + ) + .await + { + utils::with_login_cookie( + config, + login_token, + utils::redirect("/"), + ) + } else { + server_error + } + } + Ok(false) => not_authorized, + Err(err) => { + error!("Error verifying bcrypt password: {:?}", err); + server_error + } + }, + None => not_authorized, + } + } + None => not_authorized, + } +} + +pub async fn logout(config: Config, wallet: &Wallet) -> Response<Body> { + if db::users::remove_login_token(&wallet.pool, wallet.user.id).await { + utils::with_logout_cookie(config, utils::redirect("/")) + } else { + error::error(&wallet, "Erreur serveur", "Erreur serveur") + } +} |