delete challenge cmd

This commit is contained in:
realaravinth 2021-06-10 18:27:27 +05:30
parent 8490651349
commit a88527a0b5
No known key found for this signature in database
GPG key ID: AD9F0F08E855ED88
5 changed files with 57 additions and 15 deletions

1
Cargo.lock generated
View file

@ -303,6 +303,7 @@ dependencies = [
[[package]] [[package]]
name = "libmcaptcha" name = "libmcaptcha"
version = "0.1.4" version = "0.1.4"
source = "git+https://github.com/mCaptcha/libmcaptcha?branch=master#3671eea67fe247a371cfa6e28493d46c405e0371"
dependencies = [ dependencies = [
"derive_builder", "derive_builder",
"derive_more", "derive_more",

View file

@ -39,7 +39,7 @@ impl Challenge {
pub fn new(duration: u64, difficulty: u32) -> Self { pub fn new(duration: u64, difficulty: u32) -> Self {
Self(AddVisitorResult { Self(AddVisitorResult {
difficulty_factor: difficulty, difficulty_factor: difficulty,
duration: duration, duration,
}) })
} }
@ -55,7 +55,7 @@ impl Challenge {
if key.key_type() != KeyType::Empty { if key.key_type() != KeyType::Empty {
return Err(CacheError::DuplicateChallenge.into()); return Err(CacheError::DuplicateChallenge.into());
} }
let challenge = Self::new(add_challenge.duration, add_challenge.difficulty); let challenge = Self::new(add_challenge.duration, add_challenge.difficulty as u32);
key.set_value(&MCAPTCHA_CHALLENGE_TYPE, challenge)?; key.set_value(&MCAPTCHA_CHALLENGE_TYPE, challenge)?;
key.set_expire(Duration::from_secs(add_challenge.duration))?; key.set_expire(Duration::from_secs(add_challenge.duration))?;
@ -63,6 +63,22 @@ impl Challenge {
REDIS_OK REDIS_OK
} }
pub fn delete_challenge(ctx: &Context, args: Vec<String>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let captcha = args.next_string()?;
let challenge = args.next_string()?;
let challenge_name = get_challenge_name(&captcha, &challenge);
let key = ctx.open_key_writable(&challenge_name);
if key.key_type() == KeyType::Empty {
Err(CacheError::ChallengeNotFound.into())
} else {
key.delete()?;
REDIS_OK
}
}
pub fn get_challenge(ctx: &Context, args: Vec<String>) -> RedisResult { pub fn get_challenge(ctx: &Context, args: Vec<String>) -> RedisResult {
let mut args = args.into_iter().skip(1); let mut args = args.into_iter().skip(1);
let captcha = args.next_string()?; let captcha = args.next_string()?;

View file

@ -35,7 +35,6 @@ use safety::MCAPTCHA_SAFETY_TYPE;
/// Initial allocation ammount of bucket[bucket::Bucket] /// Initial allocation ammount of bucket[bucket::Bucket]
pub const HIT_PER_SECOND: usize = 100; pub const HIT_PER_SECOND: usize = 100;
pub const PKG_NAME: &str = "mcap"; pub const PKG_NAME: &str = "mcap";
pub const PKG_VERSION: usize = 0; pub const PKG_VERSION: usize = 0;
@ -47,14 +46,11 @@ pub const PKG_VERSION: usize = 0;
// and PKG_NAME // and PKG_NAME
pub const PREFIX_BUCKET_TIMER: &str = "timer:"; pub const PREFIX_BUCKET_TIMER: &str = "timer:";
pub const PREFIX_SAFETY: &str = "safety:"; pub const PREFIX_SAFETY: &str = "safety:";
/// If buckets perform clean up at x instant, then buckets themselves will get cleaned /// If buckets perform clean up at x instant, then buckets themselves will get cleaned
/// up at x + BUCKET_EXPIRY_OFFSET(if they haven't already been cleaned up) /// up at x + BUCKET_EXPIRY_OFFSET(if they haven't already been cleaned up)
pub const BUCKET_EXPIRY_OFFSET: u64 = 30; pub const BUCKET_EXPIRY_OFFSET: u64 = 30;
lazy_static! { lazy_static! {
/// node unique identifier, useful when running in cluster mode /// node unique identifier, useful when running in cluster mode
pub static ref ID: usize = { pub static ref ID: usize = {
use rand::prelude::*; use rand::prelude::*;
@ -65,7 +61,6 @@ lazy_static! {
pub static ref PREFIX_CAPTCHA: String = format!("{}:captcha::", PKG_NAME); pub static ref PREFIX_CAPTCHA: String = format!("{}:captcha::", PKG_NAME);
/// bucket key prefix /// bucket key prefix
pub static ref PREFIX_BUCKET: String = format!("{}:bucket:{{{}}}:", PKG_NAME, *ID); pub static ref PREFIX_BUCKET: String = format!("{}:bucket:{{{}}}:", PKG_NAME, *ID);
pub static ref PREFIX_CHALLENGE: String = format!("{}:CHALLENGE", PKG_NAME); pub static ref PREFIX_CHALLENGE: String = format!("{}:CHALLENGE", PKG_NAME);
} }
@ -92,13 +87,14 @@ pub mod redis {
version: PKG_VERSION, version: PKG_VERSION,
data_types: [MCAPTCHA_BUCKET_TYPE, MCAPTCHA_MCAPTCHA_TYPE, MCAPTCHA_SAFETY_TYPE, MCAPTCHA_CHALLENGE_TYPE], data_types: [MCAPTCHA_BUCKET_TYPE, MCAPTCHA_MCAPTCHA_TYPE, MCAPTCHA_SAFETY_TYPE, MCAPTCHA_CHALLENGE_TYPE],
commands: [ commands: [
["mcaptcha_cache.add_visitor", bucket::Bucket::counter_create, "write", 1, 1, 1], ["MCAPTCHA_CACHE.ADD_VISITOR", bucket::Bucket::counter_create, "write", 1, 1, 1],
["mcaptcha_cache.get", mcaptcha::MCaptcha::get_count, "readonly", 1, 1, 1], ["MCAPTCHA_CACHE.GET", mcaptcha::MCaptcha::get_count, "readonly", 1, 1, 1],
["mcaptcha_cache.add_captcha", mcaptcha::MCaptcha::add_captcha, "readonly", 1, 1, 1], ["MCAPTCHA_CACHE.ADD_CAPTCHA", mcaptcha::MCaptcha::add_captcha, "readonly", 1, 1, 1],
["mcaptcha_cache.delete_captcha", mcaptcha::MCaptcha::delete_captcha, "write", 1, 1, 1], ["MCAPTCHA_CACHE.DELETE_CAPTCHA", mcaptcha::MCaptcha::delete_captcha, "write", 1, 1, 1],
["mcaptcha_cache.captcha_exists", mcaptcha::MCaptcha::captcha_exists, "readonly", 1, 1, 1], ["MCAPTCHA_CACHE.CAPTCHA_EXISTS", mcaptcha::MCaptcha::captcha_exists, "readonly", 1, 1, 1],
["mcaptcha_cache.add_challenge", challenge::Challenge::create_challenge, "write", 1, 1, 1], ["MCAPTCHA_CACHE.ADD_CHALLENGE", challenge::Challenge::create_challenge, "write", 1, 1, 1],
["mcaptcha_cache.get_challenge", challenge::Challenge::get_challenge, "write", 1, 1, 1], ["MCAPTCHA_CACHE.GET_CHALLENGE", challenge::Challenge::get_challenge, "write", 1, 1, 1],
["MCAPTCHA_CACHE.DELETE_CHALLENGE", challenge::Challenge::delete_challenge, "write", 1, 1, 1],
], ],
event_handlers: [ event_handlers: [
[@EXPIRED @EVICTED: on_delete], [@EXPIRED @EVICTED: on_delete],

View file

@ -33,11 +33,13 @@ utils.ping(r)
COMMANDS = { COMMANDS = {
"ADD" :"MCAPTCHA_CACHE.ADD_CHALLENGE", "ADD" :"MCAPTCHA_CACHE.ADD_CHALLENGE",
"GET" :"MCAPTCHA_CACHE.GET_CHALLENGE" "GET" :"MCAPTCHA_CACHE.GET_CHALLENGE",
"DEL" :"MCAPTCHA_CACHE.DELETE_CHALLENGE"
} }
CHALLENGE_NOT_FOUND = "Challenge not found" CHALLENGE_NOT_FOUND = "Challenge not found"
DUPLICATE_CHALLENGE = "Challenge already exists" DUPLICATE_CHALLENGE = "Challenge already exists"
REDIS_OK = bytes("OK", 'utf-8')
def add_challenge(captcha, challenge): def add_challenge(captcha, challenge):
"""Add challenge to Redis""" """Add challenge to Redis"""
@ -54,6 +56,15 @@ def get_challenge_from_redis(captcha, challenge):
except Exception as e: except Exception as e:
return e return e
def delete_challenge(captcha, challenge):
"""Add challenge to Redis"""
try :
data = r.execute_command(COMMANDS["DEL"], captcha, challenge)
return data
except Exception as e:
return e
def get_challenge(challenge): def get_challenge(challenge):
"""Get challenge JSON""" """Get challenge JSON"""
challenge = { challenge = {
@ -129,3 +140,20 @@ async def duplicate_challenge_works():
print("[*] Duplicate Challenge works") print("[*] Duplicate Challenge works")
except Exception as e: except Exception as e:
raise e raise e
async def delete_challenge_works():
"""Test: Delete Challenges"""
try:
challenge_name = "delete_challenge"
key = challenge_name
challenge = get_challenge(challenge_name)
add_challenge(key, challenge)
resp = delete_challenge(key, challenge_name)
assert resp == REDIS_OK
resp = delete_challenge(key, challenge_name)
assert str(resp) == CHALLENGE_NOT_FOUND
print("[*] Delete Challenge works")
except Exception as e:
raise e

View file

@ -33,6 +33,7 @@ class Runner(object):
challenge.challenge_doesnt_exist, challenge.challenge_doesnt_exist,
challenge.challenge_ttl_works, challenge.challenge_ttl_works,
challenge.duplicate_challenge_works, challenge.duplicate_challenge_works,
challenge.delete_challenge_works,
] ]
__tasks = [] __tasks = []