use crate::AppState; use actix_web::{ cookie::{time::Duration, Cookie, SameSite}, get, post, web::{Data, Form}, HttpRequest, HttpResponse, Responder, }; #[get("/workspace")] async fn admin_workspace() -> impl Responder { // TODO return admin static web view with js application actix_web::HttpResponse::Ok().body("Welcome Admin") } #[derive(serde::Deserialize)] struct Credentials { username: String, password: String, } #[post("/login")] async fn admin_authenticate( credentials: Form<Credentials>, app_state: Data<std::sync::Mutex<AppState>>, req: HttpRequest, ) -> impl Responder { let (admin_username, admin_pwd, cookie_name) = { let app_state = app_state.lock().unwrap(); ( app_state.config.admin_username.to_owned(), app_state.config.admin_pwd.to_owned(), app_state.config.admin_cookie_name.to_owned(), ) }; if admin_username.eq(&credentials.username) && admin_pwd.eq(&credentials.password) { let cookie_value = { let mut app_state = app_state.lock().unwrap(); app_state.admin_auth_token.generate(); app_state .admin_auth_token .value .as_ref() .unwrap() .to_owned() }; let cookie = Cookie::build(cookie_name, cookie_value) .path("/") .http_only(true) .max_age(Duration::days(7)) .same_site(SameSite::Strict) .secure(true) .finish(); return HttpResponse::Accepted().cookie(cookie).finish(); } else { let mut res = HttpResponse::Unauthorized().finish(); match req.cookie(&cookie_name) { Some(_) => { res.del_cookie(&cookie_name); return res; } None => return res, } } } #[get("/login")] pub async fn admin_login() -> impl Responder { // TODO create a module with built-in admin static views HttpResponse::Ok().body( " <html lang='en' prefix='og: https://ogp.me/ns#'> <head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Krutacea - Admin Login</title> <link rel='stylesheet' href='/static/default/admin.css'> </head> <body> <form id='admin-login-form'> <div> <label for='username'>Admin Id</label> <input type='text' name='username'/> </div> <div> <label for='password'>Password</label> <input type='password' name='password' /> </div> <input type='submit' /> </form> </body> <script src='/static/default/admin.js'></script> </html> ", ) }