pharmacy/src/captcha.rs

65 lines
1.8 KiB
Rust

// Generate & verify CAPTCHA's
extern crate captcha;
use std::fs::File;
use captcha::filters::{Grid, Noise, Wave};
use captcha::Captcha;
use std::path::Path;
use crate::structures::{CaptchaAnswer, Status};
use rocket::{form::Form, http::Cookie, http::CookieJar, serde::json::Json};
use uuid::Uuid;
// Create a new captcha image
fn create_captcha() -> Captcha {
let mut captcha = Captcha::new(); // create empty captcha
captcha
.add_chars(7)
.apply_filter(Noise::new(0.2))
.apply_filter(Grid::new(41, 67))
.add_text_area()
.apply_filter(Wave::new(1.6373, 5.1363))
.view(220, 120); // create image
let captcha_text = captcha.chars_as_string();
captcha
.save(Path::new(
&("/tmp/captcha".to_owned() + &captcha_text + ".png"),
))
.expect("save failed"); // save captcha
return captcha;
}
// API to get a new captcha
#[get("/api/captcha")]
pub fn return_captcha(cookies: &CookieJar<'_>) -> File {
let captcha = create_captcha(); // Create a new captcha
let captcha_text = captcha.chars_as_string(); // Store the captcha answer text
let file = File::open(&("/tmp/captcha".to_owned() + &captcha_text + ".png")); // Open the captcha image file
println!("created new captcha {}", captcha_text); // Print the captcha text
cookies.add(Cookie::new(
"token", // Add a cookie to store the captcha answer
Uuid::new_v5(&Uuid::NAMESPACE_X500, &captcha_text.as_bytes())
.to_simple()
.to_string(),
));
return file.unwrap(); // Return the captcha image
}
// Check if the provided captcha answer is correct
#[post("/api/captcha", data = "<answer>")]
pub fn check_captcha(answer: Form<CaptchaAnswer>) -> Json<Status> {
return Json(Status {
status: "fail".to_string(),
reason: "meow".to_string(),
});
}