use bcrypt; use http_body_util::Full; use hyper::body::Bytes; use hyper::header::SET_COOKIE; use hyper::Response; use sqlx::sqlite::SqlitePool; use std::collections::HashMap; use tera::{Context, Tera}; use crate::controller::utils::with_headers; 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::utils::cookie; use crate::validation; pub async fn page( assets: &HashMap, templates: &Tera, error: Option<&str>, ) -> 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> { 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 = cookie::generate_token(); if db::users::set_login_token( &pool, login.email, login_token.clone().to_string(), ) .await { match cookie::login(config, &login_token) { Ok(str) => with_headers( utils::redirect("/"), vec![(SET_COOKIE, &str)], ), Err(msg) => { server_error( assets, templates, &format!( "Error generating cookie: {msg}" ), ) .await } } } else { server_error(assets, templates, "Erreur server") .await } } Ok(false) => not_authorized(assets, templates).await, Err(err) => { log::error!("Error verifying bcrypt password: {:?}", err); server_error(assets, templates, "Erreur serveur").await } }, None => not_authorized(assets, templates).await, } } None => not_authorized(assets, templates).await, } } async fn server_error( assets: &HashMap, templates: &Tera, msg: &str, ) -> Response> { page(assets, templates, Some(msg)).await } async fn not_authorized( assets: &HashMap, templates: &Tera, ) -> Response> { page( assets, templates, Some("Vous n’êtes pas autorisé à vous connecter."), ) .await } pub async fn logout(config: &Config, wallet: &Wallet) -> Response> { if db::users::remove_login_token(&wallet.pool, wallet.user.id).await { with_headers( utils::redirect("/"), vec![(SET_COOKIE, &cookie::logout(config))], ) } else { error::error(wallet, "Erreur serveur", "Erreur serveur") } }