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, templates: &Tera, error: Option, ) -> Response { let connected_user: Option = 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, templates: &Tera, form: HashMap, pool: SqlitePool, ) -> Response { 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 { 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") } }