Add hCaptcha support.

This commit is contained in:
Paul Makles
2020-08-13 13:06:06 +02:00
parent 8ee867eec7
commit f44180a980
7 changed files with 75 additions and 5 deletions

42
src/util/captcha.rs Normal file
View File

@@ -0,0 +1,42 @@
use serde::{Serialize, Deserialize};
use reqwest::blocking::Client;
use std::collections::HashMap;
use std::env;
#[derive(Serialize, Deserialize)]
struct CaptchaResponse {
success: bool
}
pub fn verify(user_token: &Option<String>) -> Result<(), String> {
if let Ok(key) = env::var("HCAPTCHA_KEY") {
if let Some(token) = user_token {
let mut map = HashMap::new();
map.insert("secret", key);
map.insert("response", token.to_string());
let client = Client::new();
if let Ok(response) = client
.post("https://hcaptcha.com/siteverify")
.json(&map)
.send()
{
let result: CaptchaResponse = response
.json()
.map_err(|_| "Failed to deserialise captcha result.".to_string())?;
if result.success {
Ok(())
} else {
Err("Unsuccessful captcha verification".to_string())
}
} else {
Err("Failed to verify with hCaptcha".to_string())
}
} else {
Err("Missing hCaptcha token!".to_string())
}
} else {
Ok(())
}
}

View File

@@ -2,6 +2,8 @@ use hashbrown::HashSet;
use rand::{distributions::Alphanumeric, Rng};
use std::iter::FromIterator;
pub mod captcha;
pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> {
HashSet::from_iter(data.iter().cloned())
}